diff --git a/README.md b/README.md index 4e7adae00e..6f56e4eab7 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ jclouds ====== jclouds allows provisioning and control of cloud resources, including blobstore and compute, from Java and Clojure. Our API gives allows developers to use -both portable abstractions and cloud-specific features. We test support of 30 +both portable abstractions and cloud-specific features. We test support of dozens of cloud providers and cloud software stacks, including Amazon, Azure, GoGrid, Ninefold, OpenStack, and vCloud. jclouds is licensed under the Apache License, Version 2.0 @@ -107,7 +107,7 @@ Check out https://github.com/jclouds/jclouds-examples for more examples! Downloads ------------------------ -* release notes: http://www.jclouds.org/documentation/releasenotes/1.3 +* release notes: http://www.jclouds.org/documentation/releasenotes/1.5 * installation guide: http://www.jclouds.org/documentation/userguide/installation-guide * maven repo: http://repo2.maven.org/maven2 (maven central - the default repository) * snapshot repo: https://oss.sonatype.org/content/repositories/snapshots @@ -116,8 +116,6 @@ Resources ---------------------------- * Project page: http://jclouds.org/ * Documentation: http://www.jclouds.org/documentation/index -* Javadocs (1.1.0): http://jclouds.rimuhosting.com/apidocs/ -* Javadocs (1.0-SNAPSHOT): http://jclouds.rimuhosting.com/apidocs-SNAPSHOT/ * Community: http://www.jclouds.org/documentation/reference/apps-that-use-jclouds * User group: http://groups.google.com/group/jclouds * Dev group: http://groups.google.com/group/jclouds-dev @@ -128,4 +126,4 @@ License ------- Copyright (C) 2009-2012 jclouds, Inc. -Licensed under the Apache License, Version 2.0 \ No newline at end of file +Licensed under the Apache License, Version 2.0 diff --git a/README.txt b/README.txt deleted file mode 100644 index c765ebaf56..0000000000 --- a/README.txt +++ /dev/null @@ -1,136 +0,0 @@ -Overview: - -jclouds allows provisioning and control of cloud resources, including blobstore -and compute, from Java and Clojure. Our API gives allows developers to use -both portable abstractions and cloud-specific features. We test support of 30 -cloud providers and cloud software stacks, including Amazon, Azure, GoGrid, -Ninefold, OpenStack, and vCloud. jclouds is licensed under the Apache License, -Version 2.0 - -our current version is 1.4.2 -our next maintenance version is 1.4.2-SNAPSHOT -our dev version is 1.5.0-SNAPSHOT - -check out our examples site! https://github.com/jclouds/jclouds-examples - -our compute api supports: aws-ec2, gogrid, cloudservers-us, stub (in-memory), deltacloud, - cloudservers-uk, vcloud (generic), ec2 (generic), byon, nova, - trmk-ecloud, trmk-vcloudexpress, eucalyptus (generic) - cloudsigma-zrh, elasticstack(generic), go2cloud-jhb1, cloudsigma-lvs, - bluelock-vcloud-zone01, stratogen-vcloud-mycloud, rimuhosting, - slicehost, eucalyptus-partnercloud-ec2, elastichosts-lon-p (Peer 1), - elastichosts-sat-p (Peer 1), elastichosts-lon-b (BlueSquare), - openhosting-east1, serverlove-z1-man, skalicloud-sdg-my, - greenhousedata-element-vcloud, softlayer, cloudsigma (generic), - cloudstack (generic), ninefold-compute, openstack-nov (keystone), - hpcloud-compute, trystack-nova, openstack-nova-ec2, - rackspace-cloudservers-us (next gen), rackspace-cloudservers-uk (next gen) - - * note * the pom dependency org.jclouds/jclouds-allcompute gives you access to - to all of these providers - -our blobstore api supports: aws-s3, cloudfiles-us, cloudfiles-uk, filesystem, - azureblob, atmos (generic), synaptic-storage, hpcloud-objectstorage, - cloudonestorage, walrus(generic), ninefold-storage, - eucalyptus-partnercloud-s3, swift (generic), transient (in-mem) - - * note * the pom dependency org.jclouds/jclouds-allblobstore gives you access to - to all of these providers - -our loadbalancer api supports: cloudloadbalancers-us - - * note * the pom dependency org.jclouds/jclouds-allloadbalancer gives you access to - to all of these providers - -we also have aws-cloudwatch support. - -we also have support for: ibmdev, mezeo, nirvanix, boxdotnet, openstack nova, scality ring, - hosteurope-storage, tiscali-storage, scaleup-storage, googlestorage, - azurequeue, simpledb, as well as a async-http-client - driver in the sandbox - - -If you want access to all jclouds components, include the maven dependency org.jclouds/jclouds-all - - -BlobStore Example (Java): - // init - context = new BlobStoreContextFactory().createContext( - "aws-s3", - accesskeyid, - secretaccesskey); - blobStore = context.getBlobStore(); - - // create container - blobStore.createContainerInLocation(null, "mycontainer"); - - // add blob - blob = blobStore.blobBuilder("test").payload("testdata").build(); - blobStore.putBlob("mycontainer", blob); - -BlobStore Example (Clojure): - (use 'org.jclouds.blobstore2) - - (def *blobstore* (blobstore "azureblob" account encodedkey)) - (create-container *blobstore* "mycontainer") - (put-blob *blobstore* "mycontainer" (blob "test" :payload "testdata")) - -Compute Example (Java): - // init - context = new ComputeServiceContextFactory().createContext( - "aws-ec2", - accesskeyid, - secretaccesskey, - ImmutableSet.of(new Log4JLoggingModule(), - new SshjSshClientModule())); - client = context.getComputeService(); - - // define the requirements of your node - template = client.templateBuilder().osFamily(UBUNTU).smallest().build(); - - // setup a boot user which is the same as your login - template.getOptions().runScript(AdminAccess.standard()); - - // these nodes will be accessible via ssh when the call returns - nodes = client.createNodesInGroup("mycluster", 2, template); - - // you can now run ad-hoc commands on the nodes based on predicates - responses = client.runScriptOnNodesMatching(inGroup("mycluster"), "uptime", - wrapInInitScript(false)); - -Compute Example (Clojure): - (use 'org.jclouds.compute2) - - ; create a compute service using sshj and log4j extensions - (def compute - (*compute* "trmk`-ecloud" "user" "password" :sshj :log4j)) - - ; launch a couple nodes with the default operating system, installing your user. - (create-nodes *compute* "mycluster" 2 - (TemplateOptions$Builder/runScript (AdminAccess/standard))) - - ; run a command on that group - (run-script-on-nodes-matching *compute* (in-group? "mycluster") "uptime" - (RunScriptOptions$Builder/wrapInInitScript false)) - -Downloads: - * release notes: http://www.jclouds.org/documentation/releasenotes/1.3 - * installation guide: http://www.jclouds.org/documentation/userguide/installation-guide - * maven repo: http://repo2.maven.org/maven2 (maven central - the default repository) - * snapshot repo: https://oss.sonatype.org/content/repositories/snapshots - -Links: - * project page: http://jclouds.org/ - * documentation: http://www.jclouds.org/documentation/index - * javadocs (1.1.0): http://jclouds.rimuhosting.com/apidocs/ - * javadocs (1.0-SNAPSHOT): http://jclouds.rimuhosting.com/apidocs-SNAPSHOT/ - * community: http://www.jclouds.org/documentation/reference/apps-that-use-jclouds - * user group: http://groups.google.com/group/jclouds - * dev group: http://groups.google.com/group/jclouds-dev - * twitter: http://twitter.com/jclouds - -## License - -Copyright (C) 2009-2012 jclouds, Inc. - -Licensed under the Apache License, Version 2.0 diff --git a/all/pom.xml b/all/pom.xml index c0ed79dfd8..3e97bbd5ea 100644 --- a/all/pom.xml +++ b/all/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../project/pom.xml jclouds-all @@ -40,6 +40,11 @@ aws-cloudwatch ${project.version} + + org.jclouds.provider + aws-sqs + ${project.version} + ${project.groupId} jclouds-allloadbalancer diff --git a/allblobstore/pom.xml b/allblobstore/pom.xml index 42485cecdf..d0965c84df 100644 --- a/allblobstore/pom.xml +++ b/allblobstore/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../project/pom.xml jclouds-allblobstore diff --git a/allcompute/pom.xml b/allcompute/pom.xml index c36fd74dbb..4039b2c67d 100644 --- a/allcompute/pom.xml +++ b/allcompute/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../project/pom.xml jclouds-allcompute diff --git a/allloadbalancer/pom.xml b/allloadbalancer/pom.xml index 8d1e2faef5..26cedd4aaf 100644 --- a/allloadbalancer/pom.xml +++ b/allloadbalancer/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../project/pom.xml jclouds-allloadbalancer diff --git a/antcontrib/pom.xml b/antcontrib/pom.xml deleted file mode 100644 index 9d0a6176d3..0000000000 --- a/antcontrib/pom.xml +++ /dev/null @@ -1,91 +0,0 @@ - - - - 4.0.0 - - org.jclouds - jclouds-project - 1.5.0-SNAPSHOT - ../project/pom.xml - - jclouds-antcontrib - Ant-Contrib extensions - - - - - - ${project.groupId} - jclouds-scriptbuilder - ${project.version} - - - ${project.groupId} - jclouds-compute - ${project.version} - - - org.apache.ant - ant - 1.7.1 - provided - - - org.apache.ant - ant-jsch - 1.7.1 - - - org.jclouds.driver - jclouds-jsch - ${project.version} - - - com.jcraft - jsch - - - - - ${project.artifactId} - - - - maven-assembly-plugin - - - package - - single - - - - jar-with-dependencies - - - - - - - - - diff --git a/antcontrib/samples/compute/build.xml b/antcontrib/samples/compute/build.xml deleted file mode 100644 index f473fa8941..0000000000 --- a/antcontrib/samples/compute/build.xml +++ /dev/null @@ -1,183 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/antcontrib/samples/javaoverssh/README.txt b/antcontrib/samples/javaoverssh/README.txt deleted file mode 100644 index a5e1c4c05a..0000000000 --- a/antcontrib/samples/javaoverssh/README.txt +++ /dev/null @@ -1,26 +0,0 @@ -==== - Licensed to jclouds, Inc. (jclouds) under one or more - contributor license agreements. See the NOTICE file - distributed with this work for additional information - regarding copyright ownership. jclouds licenses this file - to you under the Apache License, Version 2.0 (the - "License"); you may not use this file except in compliance - with the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, - software distributed under the License is distributed on an - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - KIND, either express or implied. See the License for the - specific language governing permissions and limitations - under the License. -==== - - this is a simple ant script that executes a java command on a remote machine via ssh - 1. find or download a copy of jclouds-antcontrib-1.0-SNAPSHOT-jar-with-dependencies.jar - - ex. ~/.m2/repository/org/jclouds/jclouds-antcontrib/1.0-SNAPSHOT/jclouds-antcontrib-1.0-SNAPSHOT-jar-with-dependencies.jar - - ex. curl http://jclouds.rimuhosting.com/maven2/snapshots/org/jclouds/jclouds-antcontrib/1.0-SNAPSHOT/jclouds-antcontrib-1.0-20091215.023231-1-jar-with-dependencies.jar >jclouds-antcontrib-all.jar - 2. invoke ant, adding the library above, and passing the properties 'host' 'username' 'keyfile' which corresponds to your remote credentials - - ex. ant -lib ~/.m2/repository/org/jclouds/jclouds-antcontrib/1.0-SNAPSHOT/jclouds-antcontrib-1.0-SNAPSHOT-jar-with-dependencies.jar -Dhost=67.202.42.237 -Dusername=root -Dkeyfile=$HOME/.ssh/id_dsa - - ex. ant -lib ~/.m2/repository/org/jclouds/jclouds-antcontrib/1.0-SNAPSHOT/jclouds-antcontrib-1.0-SNAPSHOT-jar-with-dependencies.jar -Dhost=localhost -Dusername=$USER -Dkeyfile=$HOME/.ssh/id_dsa diff --git a/antcontrib/samples/javaoverssh/build.xml b/antcontrib/samples/javaoverssh/build.xml deleted file mode 100644 index 66ddc8f389..0000000000 --- a/antcontrib/samples/javaoverssh/build.xml +++ /dev/null @@ -1,83 +0,0 @@ - - - - - simple example build file - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/antcontrib/src/main/java/org/jclouds/tools/ant/logging/AntLogger.java b/antcontrib/src/main/java/org/jclouds/tools/ant/logging/AntLogger.java deleted file mode 100644 index 48732ce1b4..0000000000 --- a/antcontrib/src/main/java/org/jclouds/tools/ant/logging/AntLogger.java +++ /dev/null @@ -1,119 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.tools.ant.logging; - -import static com.google.common.base.Preconditions.checkNotNull; - -import java.util.Set; - -import org.apache.tools.ant.Project; -import org.jclouds.logging.BaseLogger; -import org.jclouds.logging.Logger; - -import com.google.common.collect.Sets; - -/** - * {@link org.apache.tools.ant.Project} implementation of {@link Logger}. - * - * @author Adrian Cole - * - */ -public class AntLogger extends BaseLogger { - private final Project project; - private final String category; - private boolean alwaysLog; - - public static class AntLoggerFactory implements LoggerFactory { - private final Project project; - private final Set upgrades; - - public AntLoggerFactory(Project project, String... upgrades) { - this.project = checkNotNull(project, "project"); - this.upgrades = Sets.newHashSet(upgrades); - } - - public Logger getLogger(String category) { - return new AntLogger(project, category, upgrades.contains(category)); - } - } - - public AntLogger(Project project, String category, boolean alwaysLog) { - this.project = checkNotNull(project, "project"); - this.category = category; - this.alwaysLog = alwaysLog; - } - - @Override - protected void logTrace(String message) { - } - - public boolean isTraceEnabled() { - return false; - } - - @Override - protected void logDebug(String message) { - project.log(" " + message, alwaysLog ? Project.MSG_INFO : Project.MSG_DEBUG); - } - - public boolean isDebugEnabled() { - return true; - } - - @Override - protected void logInfo(String message) { - project.log(" " + message); - } - - public boolean isInfoEnabled() { - return true; - } - - @Override - protected void logWarn(String message) { - project.log(" " + message, Project.MSG_WARN); - } - - @Override - protected void logWarn(String message, Throwable e) { - project.log(" " + message, e, Project.MSG_WARN); - } - - public boolean isWarnEnabled() { - return true; - } - - @Override - protected void logError(String message) { - project.log(" " + message, Project.MSG_ERR); - } - - @Override - protected void logError(String message, Throwable e) { - project.log(" " + message, e, Project.MSG_ERR); - } - - public boolean isErrorEnabled() { - return true; - } - - public String getCategory() { - return category; - } -} \ No newline at end of file diff --git a/antcontrib/src/main/java/org/jclouds/tools/ant/taskdefs/compute/ComputeTask.java b/antcontrib/src/main/java/org/jclouds/tools/ant/taskdefs/compute/ComputeTask.java deleted file mode 100644 index f087d1deec..0000000000 --- a/antcontrib/src/main/java/org/jclouds/tools/ant/taskdefs/compute/ComputeTask.java +++ /dev/null @@ -1,298 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.tools.ant.taskdefs.compute; - -import static org.jclouds.compute.util.ComputeServiceUtils.formatStatus; -import static org.jclouds.compute.util.ComputeServiceUtils.getCores; -import static org.jclouds.tools.ant.taskdefs.compute.ComputeTaskUtils.buildComputeMap; -import static org.jclouds.tools.ant.taskdefs.compute.ComputeTaskUtils.createTemplateFromElement; -import static org.jclouds.tools.ant.taskdefs.compute.ComputeTaskUtils.ipOrEmptyString; - -import java.io.IOException; -import java.net.URI; - -import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.Project; -import org.apache.tools.ant.Task; -import org.jclouds.compute.ComputeService; -import org.jclouds.compute.ComputeServiceContext; -import org.jclouds.compute.RunNodesException; -import org.jclouds.compute.domain.ComputeMetadata; -import org.jclouds.compute.domain.Hardware; -import org.jclouds.compute.domain.Image; -import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.domain.Template; -import org.jclouds.compute.predicates.NodePredicates; -import org.jclouds.domain.Location; -import org.jclouds.http.HttpUtils; -import org.jclouds.javax.annotation.Nullable; -import org.jclouds.util.CredentialUtils; - -import com.google.common.base.CaseFormat; -import com.google.common.base.Splitter; -import com.google.common.cache.LoadingCache; -import com.google.common.collect.Iterables; -import com.google.inject.Provider; - -/** - * @author Adrian Cole - * @author Ivan Meredith - */ -public class ComputeTask extends Task { - - private final LoadingCache computeMap; - private String provider; - private String actions; - private NodeElement nodeElement; - - /** - * we don't have a reference to the project during the constructor, so we need to defer expansion - * with a Provider. - */ - private final Provider projectProvider = new Provider() { - @Override - public Project get() { - return getProject(); - } - }; - - public ComputeTask(@Nullable LoadingCache computeMap) { - this.computeMap = computeMap != null ? computeMap : buildComputeMap(projectProvider); - } - - public ComputeTask() throws IOException { - this(null); - } - - public static enum Action { - CREATE, GET, LIST, LIST_DETAILS, DESTROY, REBOOT, LIST_IMAGES, LIST_SIZES, LIST_LOCATIONS - } - - /** - * makes a connection to the compute service and invokes - */ - public void execute() throws BuildException { - ComputeServiceContext context = computeMap.getUnchecked(HttpUtils.createUri(provider)); - - try { - for (String action : Splitter.on(',').split(actions)) { - Action act = Action.valueOf(CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_UNDERSCORE, action)); - try { - invokeActionOnService(act, context.getComputeService()); - } catch (RunNodesException e) { - throw new BuildException(e); - } catch (IOException e) { - throw new BuildException(e); - } - } - } finally { - context.close(); - } - } - - private void invokeActionOnService(Action action, ComputeService computeService) throws RunNodesException, IOException { - switch (action) { - case CREATE: - case GET: - case DESTROY: - case REBOOT: - if (nodeElement != null) { - switch (action) { - case CREATE: - create(computeService); - break; - case GET: - get(computeService); - break; - case DESTROY: - destroy(computeService); - break; - case REBOOT: - reboot(computeService); - break; - } - } else { - this.log("missing node element for action: " + action, Project.MSG_ERR); - } - break; - case LIST: - list(computeService); - break; - case LIST_DETAILS: - listDetails(computeService); - break; - case LIST_IMAGES: - listImages(computeService); - break; - case LIST_SIZES: - listHardwares(computeService); - break; - case LIST_LOCATIONS: - listLocations(computeService); - break; - default: - this.log("bad action: " + action, Project.MSG_ERR); - } - } - - private void listDetails(ComputeService computeService) { - log("list details"); - for (ComputeMetadata node : computeService.listNodes()) {// TODO - // parallel - logDetails(computeService, node); - } - } - - private void listImages(ComputeService computeService) { - log("list images"); - for (Image image : computeService.listImages()) {// TODO - log(String.format(" image location=%s, id=%s, name=%s, version=%s, osArch=%s, osfam=%s, osdesc=%s, desc=%s", - image.getLocation(), image.getProviderId(), image.getName(), image.getVersion(), image - .getOperatingSystem().getArch(), image.getOperatingSystem().getFamily(), image - .getOperatingSystem().getDescription(), image.getDescription())); - } - } - - private void listHardwares(ComputeService computeService) { - log("list hardwares"); - for (Hardware hardware : computeService.listHardwareProfiles()) {// TODO - log(String.format(" hardware id=%s, cores=%s, ram=%s, volumes=%s", hardware.getProviderId(), getCores(hardware), hardware - .getRam(), hardware.getVolumes())); - } - } - - private void listLocations(ComputeService computeService) { - log("list locations"); - for (Location location : computeService.listAssignableLocations()) {// TODO - log(String.format(" location id=%s, scope=%s, description=%s, parent=%s", location.getId(), location - .getScope(), location.getDescription(), location.getParent())); - } - } - - private void list(ComputeService computeService) { - log("list"); - for (ComputeMetadata node : computeService.listNodes()) { - log(String.format(" location=%s, id=%s, group=%s", node.getLocation(), node.getProviderId(), node.getName())); - } - } - - private void create(ComputeService computeService) throws RunNodesException, IOException { - String group = nodeElement.getGroup(); - - log(String.format("create group: %s, count: %d, hardware: %s, os: %s", group, nodeElement.getCount(), nodeElement - .getHardware(), nodeElement.getOs())); - - Template template = createTemplateFromElement(nodeElement, computeService); - - for (NodeMetadata createdNode : computeService.createNodesInGroup(group, nodeElement.getCount(), template)) { - logDetails(computeService, createdNode); - addNodeDetailsAsProjectProperties(createdNode); - } - } - - private void addNodeDetailsAsProjectProperties(NodeMetadata createdNode) { - if (nodeElement.getIdproperty() != null) - getProject().setProperty(nodeElement.getIdproperty(), createdNode.getProviderId()); - if (nodeElement.getHostproperty() != null) - getProject().setProperty(nodeElement.getHostproperty(), ipOrEmptyString(createdNode.getPublicAddresses())); - if (nodeElement.getPasswordproperty() != null && !CredentialUtils.isPrivateKeyCredential(createdNode.getCredentials())) - getProject().setProperty(nodeElement.getPasswordproperty(), createdNode.getCredentials().credential); - if (nodeElement.getUsernameproperty() != null) - getProject().setProperty(nodeElement.getUsernameproperty(), createdNode.getCredentials().identity); - } - - private void reboot(ComputeService computeService) { - if (nodeElement.getId() != null) { - log(String.format("reboot id: %s", nodeElement.getId())); - computeService.rebootNode(nodeElement.getId()); - } else { - log(String.format("reboot group: %s", nodeElement.getGroup())); - computeService.rebootNodesMatching(NodePredicates.inGroup(nodeElement.getGroup())); - } - } - - private void destroy(ComputeService computeService) { - if (nodeElement.getId() != null) { - log(String.format("destroy id: %s", nodeElement.getId())); - computeService.destroyNode(nodeElement.getId()); - } else { - log(String.format("destroy group: %s", nodeElement.getGroup())); - computeService.destroyNodesMatching(NodePredicates.inGroup(nodeElement.getGroup())); - } - } - - private void get(ComputeService computeService) { - if (nodeElement.getId() != null) { - log(String.format("get id: %s", nodeElement.getId())); - logDetails(computeService, computeService.getNodeMetadata(nodeElement.getId())); - } else { - log(String.format("get group: %s", nodeElement.getGroup())); - for (ComputeMetadata node : Iterables.filter(computeService.listNodesDetailsMatching(NodePredicates.all()), - NodePredicates.inGroup(nodeElement.getGroup()))) { - logDetails(computeService, node); - } - } - } - - private void logDetails(ComputeService computeService, ComputeMetadata node) { - NodeMetadata metadata = node instanceof NodeMetadata ? NodeMetadata.class.cast(node) : computeService - .getNodeMetadata(node.getId()); - log(String.format(" node id=%s, name=%s, group=%s, location=%s, state=%s, publicIp=%s, privateIp=%s, hardware=%s", - metadata.getProviderId(), metadata.getName(), metadata.getGroup(), metadata.getLocation(), formatStatus(metadata), ComputeTaskUtils.ipOrEmptyString(metadata.getPublicAddresses()), - ipOrEmptyString(metadata.getPrivateAddresses()), metadata.getHardware())); - } - - /** - * @return the configured {@link NodeElement} element - */ - public final NodeElement createNodes() { - if (getNodes() == null) { - this.nodeElement = new NodeElement(); - } - return this.nodeElement; - } - - public NodeElement getNodes() { - return this.nodeElement; - } - - public String getActions() { - return actions; - } - - public void setActions(String actions) { - this.actions = actions; - } - - public NodeElement getNodeElement() { - return nodeElement; - } - - public void setNodeElement(NodeElement nodeElement) { - this.nodeElement = nodeElement; - } - - public void setProvider(String provider) { - this.provider = provider; - } - - public String getProvider() { - return provider; - } -} diff --git a/antcontrib/src/main/java/org/jclouds/tools/ant/taskdefs/compute/ComputeTaskUtils.java b/antcontrib/src/main/java/org/jclouds/tools/ant/taskdefs/compute/ComputeTaskUtils.java deleted file mode 100644 index 9c6d41afb5..0000000000 --- a/antcontrib/src/main/java/org/jclouds/tools/ant/taskdefs/compute/ComputeTaskUtils.java +++ /dev/null @@ -1,166 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.tools.ant.taskdefs.compute; - -import java.io.IOException; -import java.net.URI; -import java.util.NoSuchElementException; -import java.util.Properties; -import java.util.Set; - -import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.Project; -import org.jclouds.ContextBuilder; -import org.jclouds.compute.ComputeService; -import org.jclouds.compute.ComputeServiceContext; -import org.jclouds.compute.domain.OsFamily; -import org.jclouds.compute.domain.Template; -import org.jclouds.compute.domain.TemplateBuilder; -import org.jclouds.compute.options.TemplateOptions; -import org.jclouds.compute.reference.ComputeServiceConstants; -import org.jclouds.domain.Credentials; -import org.jclouds.scriptbuilder.domain.Statements; -import org.jclouds.ssh.jsch.config.JschSshClientModule; -import org.jclouds.tools.ant.logging.config.AntLoggingModule; - -import com.google.common.base.Charsets; -import com.google.common.base.Splitter; -import com.google.common.cache.CacheBuilder; -import com.google.common.cache.CacheLoader; -import com.google.common.cache.LoadingCache; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Iterables; -import com.google.common.io.Files; -import com.google.inject.Module; -import com.google.inject.Provider; - -/** - * - * @author Adrian Cole - */ -public class ComputeTaskUtils { - - /** - * - * Creates a Map that associates a uri with a live connection to the compute provider. This is - * done on-demand. - * - * @param projectProvider - * allows access to the ant project to retrieve default properties needed for compute - * providers. - */ - static LoadingCache buildComputeMap(final Provider projectProvider) { - return CacheBuilder.newBuilder().build(new CacheLoader() { - - @SuppressWarnings("unchecked") - @Override - public ComputeServiceContext load(URI from) { - Properties props = new Properties(); - props.putAll(projectProvider.get().getProperties()); - Set modules = ImmutableSet. of(new AntLoggingModule(projectProvider.get(), - ComputeServiceConstants.COMPUTE_LOGGER), new JschSshClientModule()); - // adding the properties to the factory will allow us to pass - // alternate endpoints - String provider = from.getHost(); - Credentials creds = Credentials.parse(from); - return ContextBuilder.newBuilder(provider) - .credentials(creds.identity, creds.credential) - .modules(modules) - .overrides(props).buildView(ComputeServiceContext.class); - } - - }); - - } - - static Template createTemplateFromElement(NodeElement nodeElement, ComputeService computeService) throws IOException { - TemplateBuilder templateBuilder = computeService.templateBuilder(); - if (nodeElement.getLocation() != null && !"".equals(nodeElement.getLocation())) - templateBuilder.locationId(nodeElement.getLocation()); - if (nodeElement.getImage() != null && !"".equals(nodeElement.getImage())) { - final String imageId = nodeElement.getImage(); - try { - templateBuilder.imageId(imageId); - } catch (NoSuchElementException e) { - throw new BuildException("image not found " + nodeElement.getImage()); - } - } else { - templateBuilder.osFamily(OsFamily.valueOf(nodeElement.getOs())); - } - addHardwareFromElementToTemplate(nodeElement, templateBuilder); - templateBuilder.options(getNodeOptionsFromElement(nodeElement)); - - return templateBuilder.build(); - } - - static void addHardwareFromElementToTemplate(NodeElement nodeElement, TemplateBuilder template) { - if (nodeElement.getHardware().equalsIgnoreCase("smallest")) { - template.smallest(); - } else if (nodeElement.getHardware().equalsIgnoreCase("fastest")) { - template.fastest(); - } else if (nodeElement.getHardware().equalsIgnoreCase("biggest")) { - template.biggest(); - } else { - throw new BuildException("size: " + nodeElement.getHardware() - + " not supported. valid sizes are smallest, fastest, biggest"); - } - } - - static TemplateOptions getNodeOptionsFromElement(NodeElement nodeElement) throws IOException { - TemplateOptions options = new TemplateOptions().inboundPorts(getPortsToOpenFromElement(nodeElement)); - addRunScriptToOptionsIfPresentInNodeElement(nodeElement, options); - addPrivateKeyToOptionsIfPresentInNodeElement(nodeElement, options); - addPublicKeyToOptionsIfPresentInNodeElement(nodeElement, options); - return options; - } - - static void addRunScriptToOptionsIfPresentInNodeElement(NodeElement nodeElement, TemplateOptions options) throws IOException { - if (nodeElement.getRunscript() != null) - options.runScript(Statements.exec(Files.toString(nodeElement.getRunscript(), Charsets.UTF_8))); - } - - static void addPrivateKeyToOptionsIfPresentInNodeElement(NodeElement nodeElement, TemplateOptions options) - throws IOException { - if (nodeElement.getPrivatekeyfile() != null) - options.installPrivateKey(Files.toString(nodeElement.getPrivatekeyfile(), Charsets.UTF_8)); - } - - static void addPublicKeyToOptionsIfPresentInNodeElement(NodeElement nodeElement, TemplateOptions options) throws IOException { - if (nodeElement.getPrivatekeyfile() != null) - options.authorizePublicKey(Files.toString(nodeElement.getPublickeyfile(), Charsets.UTF_8)); - } - - static String ipOrEmptyString(Set set) { - if (set.size() > 0) { - return Iterables.get(set, 0); - } else { - return ""; - } - } - - static int[] getPortsToOpenFromElement(NodeElement nodeElement) { - Iterable portStrings = Splitter.on(',').split(nodeElement.getOpenports()); - int[] ports = new int[Iterables.size(portStrings)]; - int i = 0; - for (String port : portStrings) { - ports[i++] = Integer.parseInt(port); - } - return ports; - } -} diff --git a/antcontrib/src/main/java/org/jclouds/tools/ant/taskdefs/compute/NodeElement.java b/antcontrib/src/main/java/org/jclouds/tools/ant/taskdefs/compute/NodeElement.java deleted file mode 100644 index c258c39995..0000000000 --- a/antcontrib/src/main/java/org/jclouds/tools/ant/taskdefs/compute/NodeElement.java +++ /dev/null @@ -1,181 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.tools.ant.taskdefs.compute; - -import java.io.File; - -/** - * @author Adrian Cole - * @author Ivan Meredith - */ -public class NodeElement { - private String id; - private String group; - private String hardware; - private String os; - private String image; - private int count = 1; - private String openports = "22"; - private String passwordproperty; - private File privatekeyfile; - private File publickeyfile; - private String hostproperty; - private String idproperty; - private String usernameproperty; - private String location; - private File runscript; - - public String getLocation() { - return location; - } - - public void setLocation(String location) { - this.location = location; - } - - String getUsernameproperty() { - return usernameproperty; - } - - /** - * The name of a property in which the username of the login user should be stored. - * - */ - public void setUsernameproperty(String usernameproperty) { - this.usernameproperty = usernameproperty; - } - - String getPasswordproperty() { - return passwordproperty; - } - - /** - * The name of a property in which the password of the login user should be stored. - * - */ - public void setPasswordproperty(String passwordproperty) { - this.passwordproperty = passwordproperty; - } - - /** - * The name of a property in which the hostname of the machine should be stored - * - */ - public void setHostproperty(String hostproperty) { - this.hostproperty = hostproperty; - } - - String getHostproperty() { - return hostproperty; - } - - /** - * The name of a property in which the id of the machine should be stored - * - */ - public void setIdproperty(String idproperty) { - this.idproperty = idproperty; - } - - String getIdproperty() { - return idproperty; - } - - - public void setHardware(String hardware) { - this.hardware = hardware; - } - - public String getHardware() { - return hardware; - } - - public void setOs(String os) { - this.os = os; - } - - public String getOs() { - return os; - } - - public void setRunscript(File runscript) { - this.runscript = runscript; - } - - public File getRunscript() { - return runscript; - } - - public void setOpenports(String openports) { - this.openports = openports; - } - - public String getOpenports() { - return openports; - } - - public void setImage(String image) { - this.image = image; - } - - public String getImage() { - return image; - } - - public void setCount(int count) { - this.count = count; - } - - public int getCount() { - return count; - } - - public void setGroup(String group) { - this.group = group; - } - - public String getGroup() { - return group; - } - - public void setPrivatekeyfile(File privatekeyfile) { - this.privatekeyfile = privatekeyfile; - } - - public File getPrivatekeyfile() { - return privatekeyfile; - } - - public void setPublickeyfile(File publickeyfile) { - this.publickeyfile = publickeyfile; - } - - public File getPublickeyfile() { - return publickeyfile; - } - - public void setId(String id) { - this.id = id; - } - - public String getId() { - return id; - } - -} diff --git a/antcontrib/src/main/java/org/jclouds/tools/ant/taskdefs/sshjava/SSHJava.java b/antcontrib/src/main/java/org/jclouds/tools/ant/taskdefs/sshjava/SSHJava.java deleted file mode 100644 index 54a071078b..0000000000 --- a/antcontrib/src/main/java/org/jclouds/tools/ant/taskdefs/sshjava/SSHJava.java +++ /dev/null @@ -1,587 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.tools.ant.taskdefs.sshjava; - -import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.scriptbuilder.domain.Statements.exec; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.security.SecureRandom; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.concurrent.TimeoutException; - -import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.Location; -import org.apache.tools.ant.Project; -import org.apache.tools.ant.Target; -import org.apache.tools.ant.Task; -import org.apache.tools.ant.taskdefs.Java; -import org.apache.tools.ant.taskdefs.Replace; -import org.apache.tools.ant.taskdefs.Replace.Replacefilter; -import org.apache.tools.ant.taskdefs.optional.ssh.SSHUserInfo; -import org.apache.tools.ant.taskdefs.optional.ssh.Scp; -import org.apache.tools.ant.types.CommandlineJava; -import org.apache.tools.ant.types.Environment; -import org.apache.tools.ant.types.Environment.Variable; -import org.apache.tools.ant.types.FileSet; -import org.apache.tools.ant.types.Path; -import org.jclouds.scriptbuilder.InitScript; -import org.jclouds.scriptbuilder.domain.OsFamily; -import org.jclouds.scriptbuilder.domain.ShellToken; -import org.jclouds.scriptbuilder.domain.Statement; -import org.jclouds.scriptbuilder.domain.StatementList; -import org.jclouds.scriptbuilder.domain.Statements; -import org.jclouds.tools.ant.util.SSHExecute; - -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Function; -import com.google.common.base.Joiner; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import com.jcraft.jsch.JSchException; - -/** - * Version of the Java task that executes over ssh. - * - * @author Adrian Cole - */ -public class SSHJava extends Java { - private final SSHExecute exec; - private final Scp scp; - private final SSHUserInfo userInfo; - private File localDirectory; - File remotebase; - @VisibleForTesting - File remotedir; - @VisibleForTesting - Environment env = new Environment(); - - private OsFamily osFamily = OsFamily.UNIX; - private File errorFile; - private String errorProperty; - private File outputFile; - private String outputProperty; - String id = "sshjava" + new SecureRandom().nextLong(); - private boolean append; - - @VisibleForTesting - final LinkedHashMap shiftMap = Maps.newLinkedHashMap(); - @VisibleForTesting - final LinkedHashMap replace = Maps.newLinkedHashMap(); - - public SSHJava() { - super(); - exec = new SSHExecute(); - exec.setProject(getProject()); - scp = new Scp(); - userInfo = new SSHUserInfo(); - scp.init(); - setFork(true); - setTrust(true); - } - - public SSHJava(Task owner) { - this(); - bindToOwner(owner); - } - - public void setId(String id) { - this.id = id; - } - - @Override - public int executeJava() throws BuildException { - checkNotNull(remotebase, "remotebase must be set"); - - if (localDirectory == null) { - try { - localDirectory = File.createTempFile("sshjava", "dir"); - localDirectory.delete(); - localDirectory.mkdirs(); - } catch (IOException e) { - throw new BuildException(e); - } - } - - if (remotedir == null) - remotedir = new File(remotebase, id); - - String command = createInitScript(osFamily, id, remotedir.getAbsolutePath(), env, getCommandLine()); - - try { - BufferedWriter out = new BufferedWriter(new FileWriter(new File(localDirectory, "init." - + ShellToken.SH.to(osFamily)))); - out.write(command); - out.close(); - } catch (IOException e) { - throw new BuildException(e); - } - - replaceAllTokensIn(localDirectory); - - FileSet cwd = new FileSet(); - cwd.setDir(localDirectory); - if (osFamily == OsFamily.UNIX) { - log("removing old contents: " + remotedir.getAbsolutePath(), Project.MSG_VERBOSE); - sshexec(exec("rm -rf " + remotedir.getAbsolutePath()).render(osFamily)); - } else { - // TODO need recursive remove on windows - } - mkdirAndCopyTo(remotedir.getAbsolutePath(), ImmutableList.of(cwd)); - - for (Entry entry : shiftMap.entrySet()) { - FileSet set = new FileSet(); - File source = new File(entry.getKey()); - if (source.isDirectory()) { - set.setDir(new File(entry.getKey())); - mkdirAndCopyTo(remotebase.getAbsolutePath() + ShellToken.FS.to(osFamily) + entry.getValue(), ImmutableList - .of(set)); - } else { - String destination = remotebase.getAbsolutePath() + ShellToken.FS.to(osFamily) - + new File(entry.getValue()).getParent(); - sshexec(exec("{md} " + destination).render(osFamily)); - scp.init(); - String scpDestination = getScpDir(destination); - log("staging: " + scpDestination, Project.MSG_VERBOSE); - scp.setFile(source.getAbsolutePath()); - scp.setTodir(scpDestination); - scp.execute(); - } - } - - if (getCommandLine().getClasspath() != null) { - copyPathTo(getCommandLine().getClasspath(), remotedir.getAbsolutePath() + "/classpath"); - } - - if (getCommandLine().getBootclasspath() != null) { - copyPathTo(getCommandLine().getBootclasspath(), remotedir.getAbsolutePath() + "/bootclasspath"); - } - - if (osFamily == OsFamily.UNIX) { - sshexec(exec("chmod 755 " + remotedir.getAbsolutePath() + "{fs}init.{sh}").render(osFamily)); - } - - Statement statement = new StatementList(exec("{cd} " + remotedir.getAbsolutePath()), exec(remotedir - .getAbsolutePath() - + "{fs}init.{sh} init"), exec(remotedir.getAbsolutePath() + "{fs}init.{sh} run")); - try { - return sshexecRedirectStreams(statement); - } catch (IOException e) { - throw new BuildException(e, getLocation()); - } - } - - void replaceAllTokensIn(File directory) { - Replace replacer = new Replace(); - replacer.setProject(getProject()); - replacer.setDir(directory); - - Map map = Maps.newLinkedHashMap(); - // this has to go first - map.put(directory.getAbsolutePath(), remotedir.getAbsolutePath()); - - map.putAll(Maps.transformValues(shiftMap, new Function() { - - @Override - public String apply(String in) { - return remotebase + ShellToken.FS.to(osFamily) + in; - } - - })); - map.putAll(replace); - - for (Entry entry : map.entrySet()) { - Replacefilter filter = replacer.createReplacefilter(); - filter.setToken(entry.getKey()); - filter.setValue(entry.getValue()); - } - replacer.execute(); - } - - private int sshexec(String command) { - try { - return exec.execute(command); - } catch (JSchException e) { - throw new BuildException(e, getLocation()); - } catch (IOException e) { - throw new BuildException(e, getLocation()); - } catch (TimeoutException e) { - throw new BuildException(e, getLocation()); - } - } - - private int sshexecRedirectStreams(Statement statement) throws IOException { - exec.setStreamHandler(redirector.createHandler()); - log("starting java as:\n" + statement.render(osFamily), Project.MSG_VERBOSE); - int exitStatus; - try { - exitStatus = sshexec(statement.render(osFamily)); - } finally { - redirector.complete(); - } - return exitStatus; - } - - private void mkdirAndCopyTo(String destination, Iterable sets) { - if (Iterables.size(sets) == 0) { - log("no content: " + destination, Project.MSG_DEBUG); - return; - } - if (sshexec(exec("test -d " + destination).render(osFamily)) == 0) {// TODO windows - log("already created: " + destination, Project.MSG_VERBOSE); - return; - } - sshexec(exec("{md} " + destination).render(osFamily)); - scp.init(); - String scpDestination = getScpDir(destination); - log("staging: " + scpDestination, Project.MSG_VERBOSE); - for (FileSet set : sets) - scp.addFileset(set); - scp.setTodir(scpDestination); - scp.execute(); - } - - private String getScpDir(String path) { - return String.format("%s:%s@%s:%s", userInfo.getName(), userInfo.getKeyfile() == null ? userInfo.getPassword() - : userInfo.getPassphrase(), scp.getHost(), path); - } - - void resetPathToUnderPrefixIfExistsAndIsFileIfNotExistsAddAsIs(Path path, String prefix, StringBuilder destination) { - if (path == null) - return; - String[] paths = path.list(); - if (paths != null && paths.length > 0) { - for (int i = 0; i < paths.length; i++) { - log("converting: " + paths[i], Project.MSG_DEBUG); - File file = new File(reprefix(paths[i])); - if (file.getAbsolutePath().equals(paths[i]) && file.exists() && file.isFile()) { - String newPath = prefix + "{fs}" + file.getName(); - log("adding new: " + newPath, Project.MSG_DEBUG); - destination.append("{ps}").append(prefix + "{fs}" + file.getName()); - } else { - // if the file doesn't exist, it is probably a "forward reference" to something that - // is already on the remote machine - destination.append("{ps}").append(file.getAbsolutePath()); - log("adding existing: " + file.getAbsolutePath(), Project.MSG_DEBUG); - } - } - } - } - - void copyPathTo(Path path, String destination) { - List filesets = Lists.newArrayList(); - if (path.list() != null && path.list().length > 0) { - for (String filepath : path.list()) { - if (!filepath.equals(reprefix(filepath))) - continue;// we've already copied - File file = new File(filepath); - if (file.exists()) { - FileSet fileset = new FileSet(); - if (file.isFile()) { - fileset.setFile(file); - } else { - fileset.setDir(file); - } - filesets.add(fileset); - } - } - } - mkdirAndCopyTo(destination, filesets); - } - - String reprefix(String in) { - log("comparing: " + in, Project.MSG_DEBUG); - for (Entry entry : shiftMap.entrySet()) { - if (in.startsWith(entry.getKey())) { - log("match shift map: " + entry.getKey(), Project.MSG_DEBUG); - in = remotebase + ShellToken.FS.to(osFamily) + entry.getValue() + in.substring(entry.getKey().length()); - } - } - for (Entry entry : replace.entrySet()) { - if (in.startsWith(entry.getKey())) { - log("match replaceMap: " + entry.getKey(), Project.MSG_DEBUG); - in = entry.getValue() + in.substring(entry.getKey().length()); - } - } - log("now: " + in, Project.MSG_DEBUG); - return in; - } - - String createInitScript(OsFamily osFamily, String id, String basedir, Environment env, - CommandlineJava commandLine) { - Map envVariables = Maps.newHashMap(); - String[] environment = env.getVariables(); - if (environment != null) { - for (int i = 0; i < environment.length; i++) { - log("Setting environment variable: " + environment[i], Project.MSG_DEBUG); - String[] keyValue = environment[i].split("="); - envVariables.put(keyValue[0], keyValue[1]); - } - } - StringBuilder commandBuilder = new StringBuilder(commandLine.getVmCommand().getExecutable()); - if (commandLine.getBootclasspath() != null) { - commandBuilder.append(" -Xbootclasspath:bootclasspath"); - resetPathToUnderPrefixIfExistsAndIsFileIfNotExistsAddAsIs(commandLine.getBootclasspath(), - "bootclasspath", commandBuilder); - } - - if (commandLine.getVmCommand().getArguments() != null - && commandLine.getVmCommand().getArguments().length > 0) { - commandBuilder.append(" ").append( - Joiner.on(' ').join(commandLine.getVmCommand().getArguments())); - } - commandBuilder.append(" -cp classpath"); - resetPathToUnderPrefixIfExistsAndIsFileIfNotExistsAddAsIs(commandLine.getClasspath(), - "classpath", commandBuilder); - - if (commandLine.getSystemProperties() != null - && commandLine.getSystemProperties().getVariables() != null - && commandLine.getSystemProperties().getVariables().length > 0) { - commandBuilder.append(" ").append( - Joiner.on(' ').join(commandLine.getSystemProperties().getVariables())); - } - - commandBuilder.append(" ").append(commandLine.getClassname()); - - if (commandLine.getJavaCommand().getArguments() != null - && commandLine.getJavaCommand().getArguments().length > 0) { - commandBuilder.append(" ").append( - Joiner.on(' ').join(commandLine.getJavaCommand().getArguments())); - } - - InitScript testInitBuilder = InitScript.builder().name(id).home(basedir).exportVariables(envVariables) - .run(Statements.interpret( commandBuilder.toString())).build(); - return testInitBuilder.render(osFamily); - } - - @Override - public void addEnv(Environment.Variable var) { - env.addVariable(var); - } - - /** - * Note that if the {@code dir} property is set, this will be copied recursively to the remote - * host. - */ - @Override - public void setDir(File localDir) { - this.localDirectory = checkNotNull(localDir, "dir"); - } - - /** - * All files transferred to the host will be relative to this. The java process itself will be at - * this path/{@code id}. - */ - public void setRemotebase(File remotebase) { - this.remotebase = checkNotNull(remotebase, "remotebase"); - } - - @Override - public void setFork(boolean fork) { - if (!fork) - throw new IllegalArgumentException("this only operates when fork is set"); - } - - /** - * Remote host, either DNS name or IP. - * - * @param host - * The new host value - */ - public void setHost(String host) { - exec.setHost(host); - scp.setHost(host); - } - - /** - * Username known to remote host. - * - * @param username - * The new username value - */ - public void setUsername(String username) { - exec.setUsername(username); - scp.setUsername(username); - userInfo.setName(username); - } - - /** - * Sets the password for the user. - * - * @param password - * The new password value - */ - public void setPassword(String password) { - exec.setPassword(password); - scp.setPassword(password); - userInfo.setPassword(password); - } - - /** - * Sets the keyfile for the user. - * - * @param keyfile - * The new keyfile value - */ - public void setKeyfile(String keyfile) { - exec.setKeyfile(keyfile); - scp.setKeyfile(keyfile); - userInfo.setKeyfile(keyfile); - if (userInfo.getPassphrase() == null) - userInfo.setPassphrase(""); - } - - /** - * Sets the passphrase for the users key. - * - * @param passphrase - * The new passphrase value - */ - public void setPassphrase(String passphrase) { - exec.setPassphrase(passphrase); - scp.setPassphrase(passphrase); - userInfo.setPassphrase(passphrase); - } - - /** - * Sets the path to the file that has the identities of all known hosts. This is used by SSH - * protocol to validate the identity of the host. The default is - * ${user.home}/.ssh/known_hosts. - * - * @param knownHosts - * a path to the known hosts file. - */ - public void setKnownhosts(String knownHosts) { - exec.setKnownhosts(knownHosts); - scp.setKnownhosts(knownHosts); - } - - /** - * Setting this to true trusts hosts whose identity is unknown. - * - * @param yesOrNo - * if true trust the identity of unknown hosts. - */ - public void setTrust(boolean yesOrNo) { - exec.setTrust(yesOrNo); - scp.setTrust(yesOrNo); - userInfo.setTrust(yesOrNo); - } - - /** - * Changes the port used to connect to the remote host. - * - * @param port - * port number of remote host. - */ - public void setPort(int port) { - exec.setPort(port); - scp.setPort(port); - } - - /** - * The connection can be dropped after a specified number of milliseconds. This is sometimes - * useful when a connection may be flaky. Default is 0, which means "wait forever". - * - * @param timeout - * The new timeout value in seconds - */ - public void setTimeout(long timeout) { - exec.setTimeout(timeout); - } - - @Override - public void setProject(Project project) { - super.setProject(project); - exec.setProject(project); - scp.setProject(project); - } - - @Override - public void setOwningTarget(Target target) { - super.setOwningTarget(target); - scp.setOwningTarget(target); - } - - @Override - public void setTaskName(String taskName) { - super.setTaskName(taskName); - scp.setTaskName(taskName); - } - - @Override - public void setDescription(String description) { - super.setDescription(description); - scp.setDescription(description); - } - - @Override - public void setLocation(Location location) { - super.setLocation(location); - scp.setLocation(location); - } - - @Override - public void setTaskType(String type) { - super.setTaskType(type); - scp.setTaskType(type); - } - - @Override - public String toString() { - return "SSHJava [append=" + append + ", env=" + env + ", errorFile=" + errorFile + ", errorProperty=" - + errorProperty + ", localDirectory=" + localDirectory + ", osFamily=" + osFamily + ", outputFile=" - + outputFile + ", outputProperty=" + outputProperty + ", remoteDirectory=" + remotebase + ", userInfo=" - + userInfo + "]"; - } - - @Override - public void addSysproperty(Variable sysp) { - if (sysp.getKey().startsWith("sshjava.shift.")) { - shiftMap.put(sysp.getKey().replaceFirst("sshjava.shift.", ""), sysp.getValue()); - } else if (sysp.getKey().startsWith("sshjava.replace.")) { - replace.put(sysp.getKey().replaceFirst("sshjava.replace.", ""), sysp.getValue()); - } else if (sysp.getKey().equals("sshjava.id")) { - setId(sysp.getValue()); - } else if (sysp.getKey().equals("sshjava.host")) { - setHost(sysp.getValue()); - } else if (sysp.getKey().equals("sshjava.port") && !sysp.getValue().equals("")) { - setPort(Integer.parseInt(sysp.getValue())); - } else if (sysp.getKey().equals("sshjava.username")) { - setUsername(sysp.getValue()); - } else if (sysp.getKey().equals("sshjava.password") && !sysp.getValue().equals("")) { - setPassword(sysp.getValue()); - } else if (sysp.getKey().equals("sshjava.keyfile") && !sysp.getValue().equals("")) { - setKeyfile(sysp.getValue()); - } else if (sysp.getKey().equals("sshjava.remotebase")) { - setRemotebase(new File(sysp.getValue())); - } else { - super.addSysproperty(sysp); - } - } - -} \ No newline at end of file diff --git a/antcontrib/src/main/java/org/jclouds/tools/ant/util/SSHExecute.java b/antcontrib/src/main/java/org/jclouds/tools/ant/util/SSHExecute.java deleted file mode 100644 index b469f01d2e..0000000000 --- a/antcontrib/src/main/java/org/jclouds/tools/ant/util/SSHExecute.java +++ /dev/null @@ -1,338 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.tools.ant.util; - -import java.io.IOException; -import java.util.concurrent.TimeoutException; - -import org.apache.tools.ant.BuildException; -import org.apache.tools.ant.Project; -import org.apache.tools.ant.taskdefs.ExecuteStreamHandler; -import org.apache.tools.ant.taskdefs.PumpStreamHandler; -import org.apache.tools.ant.taskdefs.optional.ssh.SSHUserInfo; -import org.apache.tools.ant.util.FileUtils; - -import com.jcraft.jsch.ChannelExec; -import com.jcraft.jsch.JSch; -import com.jcraft.jsch.JSchException; -import com.jcraft.jsch.Session; - -/** - * Executes a command on a remote machine via ssh. - * - *

- * adapted from SSHBase and SSHExec ant tasks, and Execute from the ant 1.7.1 release. - * - * @author Adrian Cole - * - */ -public class SSHExecute { - - private static final int RETRY_INTERVAL = 500; - - /** units are milliseconds, default is 0=infinite */ - private long maxwait = 0; - - private ExecuteStreamHandler streamHandler; - private String host; - private SSHUserInfo userInfo; - private int port = 22; - private Project project; - private String knownHosts = System.getProperty("user.home") + "/.ssh/known_hosts"; - - /** - * Creates a new execute object using PumpStreamHandler for stream handling. - */ - public SSHExecute() { - this(new PumpStreamHandler()); - } - - /** - * Creates a new ssh object. - * - * @param streamHandler - * the stream handler used to handle the input and output streams of the subprocess. - */ - public SSHExecute(ExecuteStreamHandler streamHandler) { - setStreamHandler(streamHandler); - userInfo = new SSHUserInfo(); - } - - /** - * Set the stream handler to use. - * - * @param streamHandler - * ExecuteStreamHandler. - */ - public void setStreamHandler(ExecuteStreamHandler streamHandler) { - this.streamHandler = streamHandler; - } - - /** - * Setting this to true trusts hosts whose identity is unknown. - * - * @param yesOrNo - * if true trust the identity of unknown hosts. - */ - public void setTrust(boolean yesOrNo) { - userInfo.setTrust(yesOrNo); - } - - /** - * Used for logging - */ - public void setProject(Project project) { - this.project = project; - } - - /** - * Username known to remote host. - * - * @param username - * The new username value - */ - public void setUsername(String username) { - userInfo.setName(username); - } - - /** - * Sets the password for the user. - * - * @param password - * The new password value - */ - public void setPassword(String password) { - userInfo.setPassword(password); - } - - /** - * Sets the keyfile for the user. - * - * @param keyfile - * The new keyfile value - */ - public void setKeyfile(String keyfile) { - userInfo.setKeyfile(keyfile); - } - - /** - * Sets the passphrase for the users key. - * - * @param passphrase - * The new passphrase value - */ - public void setPassphrase(String passphrase) { - userInfo.setPassphrase(passphrase); - } - - /** - * Remote host, either DNS name or IP. - * - * @param host - * The new host value - */ - public void setHost(String host) { - this.host = host; - } - - /** - * Changes the port used to connect to the remote host. - * - * @param port - * port number of remote host. - */ - public void setPort(int port) { - this.port = port; - } - - /** - * The connection can be dropped after a specified number of milliseconds. This is sometimes - * useful when a connection may be flaky. Default is 0, which means "wait forever". - * - * @param timeout - * The new timeout value in seconds - */ - public void setTimeout(long timeout) { - maxwait = timeout; - } - - /** - * Sets the path to the file that has the identities of all known hosts. This is used by SSH - * protocol to validate the identity of the host. The default is - * ${user.home}/.ssh/known_hosts. - * - * @param knownHosts - * a path to the known hosts file. - */ - public void setKnownhosts(String knownHosts) { - this.knownHosts = knownHosts; - } - - /** - * Execute the command on the remote host. - * - * @param command - * - what to execute on the remote host. - * - * @return return code of the process. - * @throws BuildException - * bad parameter. - * @throws JSchException - * if there's an underlying problem exposed in SSH - * @throws IOException - * if there's a problem attaching streams. - * @throws TimeoutException - * if we exceeded our timeout - */ - public int execute(String command) throws BuildException, JSchException, IOException, - TimeoutException { - if (command == null) { - throw new BuildException("Command is required."); - } - if (host == null) { - throw new BuildException("Host is required."); - } - if (userInfo.getName() == null) { - throw new BuildException("Username is required."); - } - if (userInfo.getKeyfile() == null && userInfo.getPassword() == null) { - throw new BuildException("Password or Keyfile is required."); - } - - Session session = null; - try { - session = openSession(); - return executeCommand(session, command); - } finally { - if (session != null && session.isConnected()) { - session.disconnect(); - } - } - } - - /** - * Open an ssh session. - * - * @return the opened session - * @throws JSchException - * on error - */ - protected Session openSession() throws JSchException { - JSch jsch = new JSch(); - if (null != userInfo.getKeyfile()) { - jsch.addIdentity(userInfo.getKeyfile()); - } - - if (!userInfo.getTrust() && knownHosts != null) { - project.log("Using known hosts: " + knownHosts, Project.MSG_DEBUG); - jsch.setKnownHosts(knownHosts); - } - - Session session = jsch.getSession(userInfo.getName(), host, port); - session.setUserInfo(userInfo); - project.log("Connecting to " + host + ":" + port, Project.MSG_VERBOSE); - session.connect(); - return session; - } - - /** - * - * FIXME Comment this - * - * @param session - * @param cmd - * @return return code of the process. - * @throws JSchException - * if there's an underlying problem exposed in SSH - * @throws IOException - * if there's a problem attaching streams. - * @throws TimeoutException - * if we exceeded our timeout - */ - private int executeCommand(Session session, String cmd) throws JSchException, IOException, - TimeoutException { - final ChannelExec channel; - session.setTimeout((int) maxwait); - /* execute the command */ - channel = (ChannelExec) session.openChannel("exec"); - channel.setCommand(cmd); - attachStreams(channel); - project.log("executing command: " + cmd, Project.MSG_VERBOSE); - channel.connect(); - try { - waitFor(channel); - } finally { - streamHandler.stop(); - closeStreams(channel); - } - return channel.getExitStatus(); - } - - private void attachStreams(final ChannelExec channel) throws IOException { - streamHandler.setProcessInputStream(channel.getOutputStream()); - streamHandler.setProcessOutputStream(channel.getInputStream()); - streamHandler.setProcessErrorStream(channel.getErrStream()); - streamHandler.start(); - } - - /** - * Close the streams belonging to the given Process. - * - * @param process - * the Process. - * @throws IOException - */ - public static void closeStreams(ChannelExec process) throws IOException { - FileUtils.close(process.getInputStream()); - FileUtils.close(process.getOutputStream()); - FileUtils.close(process.getErrStream()); - } - - /** - * @throws TimeoutException - */ - @SuppressWarnings("deprecation") - private void waitFor(final ChannelExec channel) throws TimeoutException { - // wait for it to finish - Thread thread = new Thread() { - public void run() { - while (!channel.isClosed()) { - try { - sleep(RETRY_INTERVAL); - } catch (InterruptedException e) { - // ignored - } - } - } - }; - - thread.start(); - try { - thread.join(maxwait); - } catch (InterruptedException e) { - // ignored - } - - if (thread.isAlive()) { - thread.destroy(); - throw new TimeoutException("command still running"); - } - } - -} diff --git a/antcontrib/src/test/java/org/jclouds/tools/ant/taskdefs/sshjava/SSHJavaTest.java b/antcontrib/src/test/java/org/jclouds/tools/ant/taskdefs/sshjava/SSHJavaTest.java deleted file mode 100644 index 4cbfe86eb8..0000000000 --- a/antcontrib/src/test/java/org/jclouds/tools/ant/taskdefs/sshjava/SSHJavaTest.java +++ /dev/null @@ -1,195 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.tools.ant.taskdefs.sshjava; - -import static org.testng.Assert.assertEquals; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.Map.Entry; - -import org.apache.tools.ant.Project; -import org.apache.tools.ant.taskdefs.Java; -import org.apache.tools.ant.types.Environment; -import org.apache.tools.ant.types.Environment.Variable; -import org.apache.tools.ant.types.Path; -import org.jclouds.scriptbuilder.domain.OsFamily; -import org.jclouds.tools.ant.TestClass; -import org.testng.annotations.Test; - -import com.google.common.base.Charsets; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Iterables; -import com.google.common.io.CharStreams; -import com.google.common.io.Files; -import com.google.common.io.Resources; - -/** - * @author Adrian Cole - */ -@Test(groups = "unit") -public class SSHJavaTest { - public static final Entry LAST_ENV = Iterables.getLast(System.getenv() - .entrySet()); - - // TODO, this test will break in windows - @Test(enabled = false, groups = { "live" }) - public void testShift() throws SecurityException, NoSuchMethodException, IOException { - SSHJava task = makeSSHJava(); - task = directoryShift(task); - assertEquals(task.shiftMap, ImmutableMap. of(System.getProperty("user.home") - + "/apache-maven-2.2.1", "maven")); - assertEquals(task.replace, ImmutableMap. of(System.getProperty("user.name"), - "root")); - new File("build").mkdirs(); - Files.write(task.createInitScript(OsFamily.UNIX, "1", "remotedir", task.env, task - .getCommandLine()), new File("build", "init.sh"), Charsets.UTF_8); - task.remotedir=new File(task.remotebase, task.id); - task.replaceAllTokensIn(new File("build")); - assertEquals(Files.toString(new File("build", "init.sh"), Charsets.UTF_8), CharStreams - .toString(Resources.newReaderSupplier(Resources.getResource("init.sh"), - Charsets.UTF_8))); - } - - private Java populateTask(Java task) { - Project p = new Project(); - task.setProject(p); - task.setClassname(TestClass.class.getName()); - task.createClasspath().add(new Path(p, "target/test-classes")); - Variable prop1 = new Environment.Variable(); - prop1.setKey("fooble"); - prop1.setValue("baz"); - task.addSysproperty(prop1); - Variable prop2 = new Environment.Variable(); - prop2.setKey("foo"); - prop2.setValue("bar"); - task.addSysproperty(prop2); - task.createJvmarg().setValue("-Xms16m"); - task.createJvmarg().setValue("-Xmx32m"); - Variable env = new Environment.Variable(); - env.setKey(LAST_ENV.getKey()); - env.setValue(LAST_ENV.getValue()); - task.addEnv(env); - task.createArg().setValue(env.getKey()); - task.createArg().setValue("hello"); - task.createArg().setValue("world"); - task.setDir(new File(System.getProperty("user.dir"))); - task.setFork(true); - task.setJvm(System.getProperty("java.home") + "/bin/java"); - task.setOutputproperty("out"); - task.setErrorProperty("err"); - task.setResultProperty("result"); - return task; - } - - @Test(enabled = false, groups = { "live" }) - public void testSsh() throws NumberFormatException, FileNotFoundException, IOException { - Java java = makeJava(); - java.execute(); - - SSHJava javaOverSsh = makeSSHJava(); - addDestinationTo(javaOverSsh); - javaOverSsh.execute(); - - assertEquals(javaOverSsh.getProject().getProperty("out"), javaOverSsh.getProject() - .getProperty("out")); - assertEquals(javaOverSsh.getProject().getProperty("err"), javaOverSsh.getProject() - .getProperty("err")); - assertEquals(javaOverSsh.getProject().getProperty("result"), javaOverSsh.getProject() - .getProperty("result")); - } - - @Test(enabled = false, groups = { "live" }) - public void testSshShift() throws NumberFormatException, FileNotFoundException, IOException { - Java java = makeJava(); - directoryShift(java); - java.execute(); - - SSHJava javaOverSsh = makeSSHJava(); - addDestinationTo(javaOverSsh); - directoryShift(javaOverSsh); - javaOverSsh.execute(); - - assertEquals(javaOverSsh.getProject().getProperty("out"), javaOverSsh.getProject() - .getProperty("out")); - assertEquals(javaOverSsh.getProject().getProperty("err"), javaOverSsh.getProject() - .getProperty("err")); - assertEquals(javaOverSsh.getProject().getProperty("result"), javaOverSsh.getProject() - .getProperty("result")); - } - - private void addDestinationTo(SSHJava javaOverSsh) throws UnknownHostException { - String sshHost = System.getProperty("test.ssh.host"); - String sshPort = System.getProperty("test.ssh.port"); - String sshUser = System.getProperty("test.ssh.username"); - String sshPass = System.getProperty("test.ssh.password"); - String sshKeyFile = System.getProperty("test.ssh.keyfile"); - - int port = (sshPort != null) ? Integer.parseInt(sshPort) : 22; - InetAddress host = (sshHost != null) ? InetAddress.getByName(sshHost) : InetAddress - .getLocalHost(); - javaOverSsh.setHost(host.getHostAddress()); - javaOverSsh.setPort(port); - javaOverSsh.setUsername(sshUser); - if (sshKeyFile != null && !sshKeyFile.trim().equals("")) { - javaOverSsh.setKeyfile(sshKeyFile); - } else { - javaOverSsh.setPassword(sshPass); - } - } - - private SSHJava makeSSHJava() { - SSHJava task = new SSHJava(); - populateTask(task); - task.setRemotebase(new File("/tmp/foo")); - task.setTrust(true); - return task; - } - - private Java makeJava() { - return populateTask(new Java()); - } - - private T directoryShift(T java) { - Variable prop1 = new Environment.Variable(); - prop1.setKey("sshjava.shift." + System.getProperty("user.home") + "/apache-maven-2.2.1"); - prop1.setValue("maven"); - java.addSysproperty(prop1); - Variable prop2 = new Environment.Variable(); - prop2.setKey("settingsfile"); - prop2.setValue(System.getProperty("user.home") + "/apache-maven-2.2.1/conf/settings.xml"); - java.addSysproperty(prop2); - Variable prop3 = new Environment.Variable(); - prop3.setKey("appHome"); - prop3.setValue(System.getProperty("user.home") + "/apache-maven-2.2.1"); - java.addSysproperty(prop3); - Variable prop4 = new Environment.Variable(); - prop4.setKey("sshjava.replace." + System.getProperty("user.name")); - prop4.setValue("root"); - java.addSysproperty(prop4); - Variable prop5 = new Environment.Variable(); - prop5.setKey("username"); - prop5.setValue(System.getProperty("user.name")); - java.addSysproperty(prop5); - return java; - } -} diff --git a/apis/atmos/pom.xml b/apis/atmos/pom.xml index 3ba1605c0f..5f864a9eed 100644 --- a/apis/atmos/pom.xml +++ b/apis/atmos/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml diff --git a/apis/atmos/src/main/java/org/jclouds/atmos/AtmosAsyncClient.java b/apis/atmos/src/main/java/org/jclouds/atmos/AtmosAsyncClient.java index 06e64fc3ed..145b9f7fcf 100644 --- a/apis/atmos/src/main/java/org/jclouds/atmos/AtmosAsyncClient.java +++ b/apis/atmos/src/main/java/org/jclouds/atmos/AtmosAsyncClient.java @@ -58,6 +58,7 @@ import org.jclouds.rest.annotations.RequestFilters; import org.jclouds.rest.annotations.ResponseParser; import org.jclouds.rest.annotations.SkipEncoding; import org.jclouds.rest.functions.ReturnFalseOnNotFoundOr404; + import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; import org.jclouds.rest.functions.ReturnVoidOnNotFoundOr404; diff --git a/apis/atmos/src/main/java/org/jclouds/atmos/handlers/AtmosClientErrorRetryHandler.java b/apis/atmos/src/main/java/org/jclouds/atmos/handlers/AtmosClientErrorRetryHandler.java index 6225524064..0eef327b1e 100644 --- a/apis/atmos/src/main/java/org/jclouds/atmos/handlers/AtmosClientErrorRetryHandler.java +++ b/apis/atmos/src/main/java/org/jclouds/atmos/handlers/AtmosClientErrorRetryHandler.java @@ -37,6 +37,7 @@ import com.google.inject.Inject; /** * Handles Retryable responses with error codes in the 4xx range * + * @see Error codes section at * @author Adrian Cole */ public class AtmosClientErrorRetryHandler implements HttpRetryHandler { @@ -62,14 +63,14 @@ public class AtmosClientErrorRetryHandler implements HttpRetryHandler { if (response.getStatusCode() == 404 && command.getCurrentRequest().getMethod().equals("DELETE")) { command.incrementFailureCount(); return true; - } else if (response.getStatusCode() == 409 || response.getStatusCode() == 400) { + } else if (response.getStatusCode() == 409) { byte[] content = HttpUtils.closeClientButKeepContentStream(response); // Content can be null in the case of HEAD requests if (content != null) { try { AtmosError error = utils.parseAtmosErrorFromContent(command, response, new String(content)); - if (error.getCode() == 1016) { + if (error.getCode() == 1006) { return backoffHandler.shouldRetryRequest(command, response); } // don't increment count before here, since backoff handler does already diff --git a/apis/atmos/src/main/java/org/jclouds/atmos/util/AtmosUtils.java b/apis/atmos/src/main/java/org/jclouds/atmos/util/AtmosUtils.java index af822753cf..91efe6bf44 100644 --- a/apis/atmos/src/main/java/org/jclouds/atmos/util/AtmosUtils.java +++ b/apis/atmos/src/main/java/org/jclouds/atmos/util/AtmosUtils.java @@ -27,9 +27,11 @@ import javax.inject.Provider; import org.jclouds.atmos.AtmosClient; import org.jclouds.atmos.blobstore.functions.BlobToObject; import org.jclouds.atmos.domain.AtmosError; +import org.jclouds.atmos.domain.AtmosObject; import org.jclouds.atmos.filters.SignRequest; import org.jclouds.atmos.options.PutOptions; import org.jclouds.atmos.xml.ErrorHandler; +import org.jclouds.blobstore.KeyAlreadyExistsException; import org.jclouds.blobstore.domain.Blob; import org.jclouds.crypto.Crypto; import org.jclouds.http.HttpCommand; @@ -70,8 +72,15 @@ public class AtmosUtils { public static String putBlob(final AtmosClient sync, Crypto crypto, BlobToObject blob2Object, String container, Blob blob, PutOptions options) { final String path = container + "/" + blob.getMetadata().getName(); - deleteAndEnsureGone(sync, path); - sync.createFile(container, blob2Object.apply(blob), options); + final AtmosObject object = blob2Object.apply(blob); + + try { + sync.createFile(container, object, options); + + } catch(KeyAlreadyExistsException e) { + deleteAndEnsureGone(sync, path); + sync.createFile(container, object, options); + } return path; } diff --git a/apis/atmos/src/test/java/org/jclouds/atmos/blobstore/integration/AtmosLiveTest.java b/apis/atmos/src/test/java/org/jclouds/atmos/blobstore/integration/AtmosLiveTest.java index d826318341..8b862d7cb8 100644 --- a/apis/atmos/src/test/java/org/jclouds/atmos/blobstore/integration/AtmosLiveTest.java +++ b/apis/atmos/src/test/java/org/jclouds/atmos/blobstore/integration/AtmosLiveTest.java @@ -32,6 +32,8 @@ public class AtmosLiveTest extends BaseBlobLiveTest { public AtmosLiveTest() { provider = "atmos"; } + + @Override protected void checkMD5(String container, String name, byte[] md5) { // atmos does not support content-md5 yet assertEquals(view.getBlobStore().blobMetadata(container, name).getContentMetadata().getContentMD5(), null); diff --git a/apis/byon/pom.xml b/apis/byon/pom.xml index 3477244f66..8a2995bf00 100644 --- a/apis/byon/pom.xml +++ b/apis/byon/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml diff --git a/apis/cloudfiles/pom.xml b/apis/cloudfiles/pom.xml index 708148679c..1c458fc4c2 100644 --- a/apis/cloudfiles/pom.xml +++ b/apis/cloudfiles/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.api @@ -34,6 +34,7 @@ bundle + 15 https://auth.api.rackspacecloud.com 1.0 @@ -112,6 +113,7 @@ + ${test.blobstore.container-count} ${jclouds.blobstore.httpstream.url} ${jclouds.blobstore.httpstream.md5} ${test.cloudfiles.endpoint} diff --git a/apis/cloudfiles/src/main/java/org/jclouds/cloudfiles/CloudFilesApiMetadata.java b/apis/cloudfiles/src/main/java/org/jclouds/cloudfiles/CloudFilesApiMetadata.java index eea9a09b28..25540f9cd1 100644 --- a/apis/cloudfiles/src/main/java/org/jclouds/cloudfiles/CloudFilesApiMetadata.java +++ b/apis/cloudfiles/src/main/java/org/jclouds/cloudfiles/CloudFilesApiMetadata.java @@ -22,30 +22,34 @@ import java.net.URI; import java.util.Properties; import org.jclouds.apis.ApiMetadata; +import org.jclouds.blobstore.BlobRequestSigner; import org.jclouds.cloudfiles.blobstore.config.CloudFilesBlobStoreContextModule; import org.jclouds.cloudfiles.config.CloudFilesRestClientModule; import org.jclouds.cloudfiles.config.CloudFilesRestClientModule.StorageAndCDNManagementEndpointModule; import org.jclouds.openstack.swift.SwiftApiMetadata; +import org.jclouds.openstack.swift.blobstore.SwiftBlobSigner; +import org.jclouds.openstack.swift.blobstore.config.TemporaryUrlExtensionModule; import org.jclouds.rest.RestContext; import com.google.common.collect.ImmutableSet; import com.google.common.reflect.TypeToken; import com.google.inject.Module; +import com.google.inject.TypeLiteral; /** * Implementation of {@link ApiMetadata} for Rackspace Cloud Files API - * + * * @author Adrian Cole */ public class CloudFilesApiMetadata extends SwiftApiMetadata { - + /** The serialVersionUID */ private static final long serialVersionUID = -1572520638079261710L; - + public static final TypeToken> CONTEXT_TOKEN = new TypeToken>() { private static final long serialVersionUID = -5070937833892503232L; }; - + private static Builder builder() { return new Builder(); } @@ -62,7 +66,7 @@ public class CloudFilesApiMetadata extends SwiftApiMetadata { protected CloudFilesApiMetadata(Builder builder) { super(builder); } - + public static Properties defaultProperties() { Properties properties = SwiftApiMetadata.defaultProperties(); return properties; @@ -78,9 +82,13 @@ public class CloudFilesApiMetadata extends SwiftApiMetadata { .documentation(URI.create("http://docs.rackspacecloud.com/files/api/v1/cfdevguide_d5/content/ch01.html")) .defaultProperties(CloudFilesApiMetadata.defaultProperties()) .context(CONTEXT_TOKEN) - .defaultModules(ImmutableSet.>of(StorageAndCDNManagementEndpointModule.class, CloudFilesRestClientModule.class, CloudFilesBlobStoreContextModule.class)); + .defaultModules(ImmutableSet.>builder() + .add(StorageAndCDNManagementEndpointModule.class) + .add(CloudFilesRestClientModule.class) + .add(CloudFilesBlobStoreContextModule.class) + .add(CloudFilesTemporaryUrlExtensionModule.class).build()); } - + @Override public CloudFilesApiMetadata build() { return new CloudFilesApiMetadata(this); @@ -93,4 +101,13 @@ public class CloudFilesApiMetadata extends SwiftApiMetadata { } } + public static class CloudFilesTemporaryUrlExtensionModule extends TemporaryUrlExtensionModule { + + @Override + protected void bindRequestSigner() { + bind(BlobRequestSigner.class).to(new TypeLiteral>() { + }); + } + + } } \ No newline at end of file diff --git a/apis/cloudfiles/src/main/java/org/jclouds/cloudfiles/CloudFilesAsyncClient.java b/apis/cloudfiles/src/main/java/org/jclouds/cloudfiles/CloudFilesAsyncClient.java index aa3c9aaf8d..6e2ca5ab5d 100644 --- a/apis/cloudfiles/src/main/java/org/jclouds/cloudfiles/CloudFilesAsyncClient.java +++ b/apis/cloudfiles/src/main/java/org/jclouds/cloudfiles/CloudFilesAsyncClient.java @@ -39,7 +39,6 @@ import org.jclouds.cloudfiles.binders.BindIterableToHeadersWithPurgeCDNObjectEma import org.jclouds.cloudfiles.domain.ContainerCDNMetadata; import org.jclouds.cloudfiles.functions.ParseCdnUriFromHeaders; import org.jclouds.cloudfiles.functions.ParseContainerCDNMetadataFromHeaders; -import org.jclouds.cloudfiles.functions.ParseTemporaryUrlKeyFromHeaders; import org.jclouds.cloudfiles.options.ListCdnContainerOptions; import org.jclouds.cloudfiles.reference.CloudFilesHeaders; import org.jclouds.openstack.filters.AuthenticateRequest; @@ -202,19 +201,4 @@ public interface CloudFilesAsyncClient extends CommonSwiftAsyncClient { @Headers(keys = CloudFilesHeaders.CDN_WEBSITE_ERROR, values = "{error}") ListenableFuture setCDNStaticWebsiteError(@PathParam("container") String container, @PathParam("error") String error); - - /** - * @see CloudFilesClient#getTemporaryUrlKey - */ - @HEAD - @Path("/") - @ResponseParser(ParseTemporaryUrlKeyFromHeaders.class) - ListenableFuture getTemporaryUrlKey(); - - /** - * @see CloudFilesClient#setTemporaryUrlKey - */ - @POST - @Path("/") - ListenableFuture setTemporaryUrlKey(@HeaderParam(CloudFilesHeaders.ACCOUNT_TEMPORARY_URL_KEY) String key); } diff --git a/apis/cloudfiles/src/main/java/org/jclouds/cloudfiles/CloudFilesClient.java b/apis/cloudfiles/src/main/java/org/jclouds/cloudfiles/CloudFilesClient.java index 23e3dd3abb..8a40c3ed23 100644 --- a/apis/cloudfiles/src/main/java/org/jclouds/cloudfiles/CloudFilesClient.java +++ b/apis/cloudfiles/src/main/java/org/jclouds/cloudfiles/CloudFilesClient.java @@ -105,25 +105,4 @@ public interface CloudFilesClient extends CommonSwiftClient { * http://docs.rackspace.com/files/api/v1/cf-devguide/content/Set_Error_Pages_for_Static_Website-dle4005.html */ boolean setCDNStaticWebsiteError(String container, String error); - - /** - * Retrieve the key used to generate Temporary object access URLs - * - * @see - * @return shared secret key - */ - String getTemporaryUrlKey(); - - /** - * To create a Temporary URL you must first set a key as account metadata. - * - * Once the key is set, you should not change it while you still want others to be - * able to access your temporary URL. If you change it, the TempURL becomes invalid - * (within 60 seconds, which is the cache time for a key) and others will not be allowed - * to access it. - * - * @see - * @param temporaryUrlKey - */ - void setTemporaryUrlKey(String temporaryUrlKey); } diff --git a/apis/cloudfiles/src/main/java/org/jclouds/cloudfiles/blobstore/config/CloudFilesBlobStoreContextModule.java b/apis/cloudfiles/src/main/java/org/jclouds/cloudfiles/blobstore/config/CloudFilesBlobStoreContextModule.java index 011a3054cf..b9282dc995 100644 --- a/apis/cloudfiles/src/main/java/org/jclouds/cloudfiles/blobstore/config/CloudFilesBlobStoreContextModule.java +++ b/apis/cloudfiles/src/main/java/org/jclouds/cloudfiles/blobstore/config/CloudFilesBlobStoreContextModule.java @@ -23,15 +23,11 @@ import java.util.concurrent.TimeUnit; import javax.inject.Singleton; -import org.jclouds.blobstore.BlobRequestSigner; import org.jclouds.cloudfiles.CloudFilesClient; -import org.jclouds.cloudfiles.TemporaryUrlKey; import org.jclouds.cloudfiles.blobstore.CloudFilesAsyncBlobStore; -import org.jclouds.cloudfiles.blobstore.CloudFilesBlobRequestSigner; import org.jclouds.cloudfiles.blobstore.CloudFilesBlobStore; import org.jclouds.cloudfiles.blobstore.functions.CloudFilesObjectToBlobMetadata; import org.jclouds.cloudfiles.domain.ContainerCDNMetadata; -import org.jclouds.date.TimeStamp; import org.jclouds.openstack.swift.blobstore.SwiftAsyncBlobStore; import org.jclouds.openstack.swift.blobstore.SwiftBlobStore; import org.jclouds.openstack.swift.blobstore.config.SwiftBlobStoreContextModule; @@ -64,18 +60,6 @@ public class CloudFilesBlobStoreContextModule extends SwiftBlobStoreContextModul }); } - @Provides - @TimeStamp - protected Long unixEpochTimestampProvider() { - return System.currentTimeMillis() / 1000; /* convert to seconds */ - } - - @Provides - @TemporaryUrlKey - protected String temporaryUrlKeyProvider(CloudFilesClient client) { - return client.getTemporaryUrlKey(); - } - @Override protected void configure() { super.configure(); @@ -83,9 +67,4 @@ public class CloudFilesBlobStoreContextModule extends SwiftBlobStoreContextModul bind(SwiftAsyncBlobStore.class).to(CloudFilesAsyncBlobStore.class); bind(ObjectToBlobMetadata.class).to(CloudFilesObjectToBlobMetadata.class); } - - @Override - protected void configureRequestSigner() { - bind(BlobRequestSigner.class).to(CloudFilesBlobRequestSigner.class); - } } diff --git a/apis/cloudfiles/src/main/java/org/jclouds/cloudfiles/config/CloudFilesRestClientModule.java b/apis/cloudfiles/src/main/java/org/jclouds/cloudfiles/config/CloudFilesRestClientModule.java index f927e9ee80..7273a4a2ec 100644 --- a/apis/cloudfiles/src/main/java/org/jclouds/cloudfiles/config/CloudFilesRestClientModule.java +++ b/apis/cloudfiles/src/main/java/org/jclouds/cloudfiles/config/CloudFilesRestClientModule.java @@ -43,7 +43,7 @@ import com.google.inject.Provides; import com.google.inject.Scopes; /** - * + * * @author Adrian Cole */ @ConfiguresRestClient @@ -53,6 +53,7 @@ public class CloudFilesRestClientModule extends SwiftRestClientModule, Class> of()); } + @Override protected void bindResolvedClientsToCommonSwift() { bind(CommonSwiftClient.class).to(CloudFilesClient.class).in(Scopes.SINGLETON); bind(CommonSwiftAsyncClient.class).to(CloudFilesAsyncClient.class).in(Scopes.SINGLETON); diff --git a/apis/cloudfiles/src/main/java/org/jclouds/cloudfiles/reference/CloudFilesHeaders.java b/apis/cloudfiles/src/main/java/org/jclouds/cloudfiles/reference/CloudFilesHeaders.java index 10547a5f06..e3fbf27ff9 100644 --- a/apis/cloudfiles/src/main/java/org/jclouds/cloudfiles/reference/CloudFilesHeaders.java +++ b/apis/cloudfiles/src/main/java/org/jclouds/cloudfiles/reference/CloudFilesHeaders.java @@ -30,8 +30,6 @@ import org.jclouds.openstack.swift.reference.SwiftHeaders; */ public interface CloudFilesHeaders extends SwiftHeaders { - public static final String ACCOUNT_TEMPORARY_URL_KEY = "X-Account-Meta-Temp-Url-Key"; - public static final String CDN_ENABLED = "X-CDN-Enabled"; public static final String CDN_LOG_RETENTION = "X-Log-Retention"; public static final String CDN_TTL = "X-TTL"; diff --git a/apis/cloudfiles/src/test/java/org/jclouds/cloudfiles/CloudFilesClientTest.java b/apis/cloudfiles/src/test/java/org/jclouds/cloudfiles/CloudFilesClientTest.java deleted file mode 100644 index f09b74dc51..0000000000 --- a/apis/cloudfiles/src/test/java/org/jclouds/cloudfiles/CloudFilesClientTest.java +++ /dev/null @@ -1,72 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.cloudfiles; - -import com.google.common.collect.ImmutableSet; -import com.google.inject.Module; -import com.google.inject.TypeLiteral; -import org.jclouds.apis.ApiMetadata; -import org.jclouds.cloudfiles.blobstore.config.CloudFilesBlobStoreContextModule; -import org.jclouds.cloudfiles.config.CloudFilesRestClientModule; -import org.jclouds.openstack.internal.TestOpenStackAuthenticationModule; -import org.jclouds.openstack.swift.CommonSwiftClientTest; -import org.jclouds.openstack.swift.SwiftApiMetadata; -import org.jclouds.openstack.swift.SwiftAsyncClient; -import org.jclouds.openstack.swift.config.SwiftRestClientModule; -import org.jclouds.rest.HttpClient; -import org.jclouds.rest.internal.RestAnnotationProcessor; -import org.testng.annotations.Test; - -import java.util.Properties; - -import static org.jclouds.Constants.PROPERTY_API_VERSION; -import static org.jclouds.Constants.PROPERTY_ENDPOINT; -import static org.jclouds.location.reference.LocationConstants.PROPERTY_REGIONS; - -/** - * @author Andrei Savu - */ -// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire -@Test(groups = "unit", testName = "CloudFilesClientTest") -public class CloudFilesClientTest extends CommonSwiftClientTest { - - public static final long UNIX_EPOCH_TIMESTAMP = 123456789L; - public static final String TEMPORARY_URL_KEY = "get-or-set-X-Account-Meta-Temp-Url-Key"; - - protected String provider = "cloudfiles"; - - public static class FixedCloudFilesBlobStoreContextModule extends CloudFilesBlobStoreContextModule { - @Override - protected Long unixEpochTimestampProvider() { - return UNIX_EPOCH_TIMESTAMP; - } - - @Override - protected String temporaryUrlKeyProvider(CloudFilesClient _) { - return TEMPORARY_URL_KEY; - } - } - - @Override - protected ApiMetadata createApiMetadata() { - return new CloudFilesApiMetadata().toBuilder().defaultModules( - ImmutableSet.>of(StorageEndpointModule.class, - CloudFilesRestClientModule.class, FixedCloudFilesBlobStoreContextModule.class)).build(); - } -} diff --git a/apis/cloudfiles/src/test/java/org/jclouds/cloudfiles/blobstore/CloudFilesBlobSignerExpectTest.java b/apis/cloudfiles/src/test/java/org/jclouds/cloudfiles/blobstore/CloudFilesBlobSignerExpectTest.java new file mode 100644 index 0000000000..8b9c2f2ae5 --- /dev/null +++ b/apis/cloudfiles/src/test/java/org/jclouds/cloudfiles/blobstore/CloudFilesBlobSignerExpectTest.java @@ -0,0 +1,145 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.cloudfiles.blobstore; + +import static org.jclouds.openstack.swift.reference.SwiftHeaders.ACCOUNT_TEMPORARY_URL_KEY; + +import java.util.Map; + +import org.jclouds.apis.ApiMetadata; +import org.jclouds.blobstore.internal.BaseBlobSignerExpectTest; +import org.jclouds.cloudfiles.CloudFilesApiMetadata; +import org.jclouds.cloudfiles.CloudFilesApiMetadata.CloudFilesTemporaryUrlExtensionModule; +import org.jclouds.cloudfiles.blobstore.config.CloudFilesBlobStoreContextModule; +import org.jclouds.cloudfiles.config.CloudFilesRestClientModule; +import org.jclouds.cloudfiles.config.CloudFilesRestClientModule.StorageAndCDNManagementEndpointModule; +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.ImmutableSet; +import com.google.common.net.HttpHeaders; +import com.google.inject.Module; + +/** + * Tests behavior of {@code SwiftBlobSigner} + * + * @author Adrian Cole + */ +// NOTE:without testName, this will not call @Before* and fail w/NPE during +// surefire +@Test(groups = "unit", testName = "CloudFilesBlobSignerExpectTest") +public class CloudFilesBlobSignerExpectTest extends BaseBlobSignerExpectTest { + + public CloudFilesBlobSignerExpectTest() { + identity = "user@jclouds.org"; + credential = "Password1234"; + } + + @Override + protected HttpRequest getBlob() { + return HttpRequest.builder().method("GET") + .endpoint("https://storage101.lon3.clouddrive.com/v1/MossoCloudFS_83a9d536-2e25-4166-bd3b-a503a934f953/container/name") + .addHeader("X-Auth-Token", authToken).build(); + } + + @Override + protected HttpRequest getBlobWithTime() { + return HttpRequest.builder().method("GET") + .endpoint("https://storage101.lon3.clouddrive.com/v1/MossoCloudFS_83a9d536-2e25-4166-bd3b-a503a934f953/container/name?temp_url_sig=9d62a4a15076699b3f7c60c2d021609990f24115&temp_url_expires=123456792").build(); + } + + @Override + protected HttpRequest getBlobWithOptions() { + return HttpRequest.builder().method("GET") + .endpoint("https://storage101.lon3.clouddrive.com/v1/MossoCloudFS_83a9d536-2e25-4166-bd3b-a503a934f953/container/name") + .addHeader("X-Auth-Token", authToken) + .addHeader("Range", "bytes=0-1").build(); + } + + @Override + protected HttpRequest putBlob() { + return HttpRequest.builder().method("PUT") + .endpoint("https://storage101.lon3.clouddrive.com/v1/MossoCloudFS_83a9d536-2e25-4166-bd3b-a503a934f953/container/name") + .addHeader("X-Auth-Token", authToken).build(); + } + + @Override + protected HttpRequest putBlobWithTime() { + return HttpRequest.builder().method("PUT") + .endpoint("https://storage101.lon3.clouddrive.com/v1/MossoCloudFS_83a9d536-2e25-4166-bd3b-a503a934f953/container/name?temp_url_sig=f83fa711f353f6f0bab3a66c56e35a972b9b3922&temp_url_expires=123456792").build(); + } + + @Override + protected HttpRequest removeBlob() { + return HttpRequest.builder().method("DELETE") + .endpoint("https://storage101.lon3.clouddrive.com/v1/MossoCloudFS_83a9d536-2e25-4166-bd3b-a503a934f953/container/name") + .addHeader("X-Auth-Token", authToken).build(); + } + + protected String authToken = "118fb907-0786-4799-88f0-9a5b7963d1ab"; + + @Override + protected Map init() { + + HttpRequest authRequest = HttpRequest.builder().method("POST") + .endpoint("https://auth.api.rackspacecloud.com/v1.1/auth") + .addHeader(HttpHeaders.ACCEPT, "application/json") + .payload( + payloadFromStringWithContentType( + "{\"credentials\":{\"username\":\"user@jclouds.org\",\"key\":\"Password1234\"}}", + "application/json")).build(); + + HttpResponse authResponse = HttpResponse.builder().statusCode(200).message("HTTP/1.1 200") + .payload(payloadFromResourceWithContentType("/auth1_1.json", "application/json")).build(); + + HttpRequest temporaryKeyRequest = HttpRequest.builder().method("HEAD") + .endpoint("https://storage101.lon3.clouddrive.com/v1/MossoCloudFS_83a9d536-2e25-4166-bd3b-a503a934f953/") + .addHeader("X-Auth-Token", authToken).build(); + + HttpResponse temporaryKeyResponse = HttpResponse.builder().statusCode(200) + .addHeader(ACCOUNT_TEMPORARY_URL_KEY, "TEMPORARY_KEY").build(); + + return ImmutableMap. builder() + .put(authRequest, authResponse) + .put(temporaryKeyRequest, temporaryKeyResponse).build(); + } + + public static class StaticTimeAndTemporaryUrlKeyModule extends CloudFilesTemporaryUrlExtensionModule { + + @Override + protected Long unixEpochTimestampProvider() { + return 123456789L; + } + } + + @Override + protected ApiMetadata createApiMetadata() { + return new CloudFilesApiMetadata() + .toBuilder() + .defaultEndpoint("https://auth.api.rackspacecloud.com") + .defaultModules( + ImmutableSet.> builder() + .add(StorageAndCDNManagementEndpointModule.class) + .add(CloudFilesRestClientModule.class) + .add(CloudFilesBlobStoreContextModule.class) + .add(StaticTimeAndTemporaryUrlKeyModule.class).build()).build(); + } +} diff --git a/apis/cloudfiles/src/test/java/org/jclouds/cloudfiles/blobstore/CloudFilesBlobSignerTest.java b/apis/cloudfiles/src/test/java/org/jclouds/cloudfiles/blobstore/CloudFilesBlobSignerTest.java deleted file mode 100644 index 7bdcdaefc4..0000000000 --- a/apis/cloudfiles/src/test/java/org/jclouds/cloudfiles/blobstore/CloudFilesBlobSignerTest.java +++ /dev/null @@ -1,83 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.jclouds.cloudfiles.blobstore; - -import org.jclouds.blobstore.BlobRequestSigner; -import org.jclouds.blobstore.domain.Blob; -import org.jclouds.cloudfiles.CloudFilesClientTest; -import org.jclouds.http.HttpRequest; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -import java.io.IOException; -import java.util.Date; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; - -/** - * @author Andrei Savu - */ -// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire -@Test(groups = "unit", testName = "CloudFilesBlobSignerTest") -public class CloudFilesBlobSignerTest extends CloudFilesClientTest { - - private BlobRequestSigner signer; - private Blob.Factory blobFactory; - - public void testSignGetBlobWithTime() { - HttpRequest request = signer.signGetBlob("container", "name", 120); - - assertRequestLineEquals(request, "GET http://storage/container/name?" + - "temp_url_sig=4759d99d13c826bba0af2c9f0c526ca53c95abaf&temp_url_expires=123456909 HTTP/1.1"); - assertFalse(request.getHeaders().containsKey("X-Auth-Token")); - assertPayloadEquals(request, null, null, false); - - assertEquals(request.getFilters().size(), 0); - } - - public void testSignPutBlobWithTime() throws Exception { - Blob blob = blobFactory.create(null); - - blob.getMetadata().setName("name"); - blob.setPayload(""); - blob.getPayload().getContentMetadata().setContentLength(2l); - blob.getPayload().getContentMetadata().setContentMD5(new byte[]{0, 2, 4, 8}); - blob.getPayload().getContentMetadata().setContentType("text/plain"); - blob.getPayload().getContentMetadata().setExpires(new Date(1000)); - - HttpRequest request = signer.signPutBlob("container", blob, 120 /* seconds */); - - assertRequestLineEquals(request, "PUT http://storage/container/name?" + - "temp_url_sig=490690286130adac9e7144d85b320a00b1bf9e2b&temp_url_expires=123456909 HTTP/1.1"); - - assertFalse(request.getHeaders().containsKey("X-Auth-Token")); - assertContentHeadersEqual(request, "text/plain", null, null, null, (long) 2l, new byte[]{0, 2, 4, 8}, new Date(1000)); - - assertEquals(request.getFilters().size(), 0); - } - - @BeforeClass - protected void setupFactory() throws IOException { - super.setupFactory(); - this.blobFactory = injector.getInstance(Blob.Factory.class); - this.signer = injector.getInstance(BlobRequestSigner.class); - } -} diff --git a/apis/cloudfiles/src/test/java/org/jclouds/cloudfiles/blobstore/integration/CloudFilesBlobLiveTest.java b/apis/cloudfiles/src/test/java/org/jclouds/cloudfiles/blobstore/integration/CloudFilesBlobLiveTest.java index 14de7f6200..360c307c4e 100644 --- a/apis/cloudfiles/src/test/java/org/jclouds/cloudfiles/blobstore/integration/CloudFilesBlobLiveTest.java +++ b/apis/cloudfiles/src/test/java/org/jclouds/cloudfiles/blobstore/integration/CloudFilesBlobLiveTest.java @@ -18,9 +18,8 @@ */ package org.jclouds.cloudfiles.blobstore.integration; -import org.jclouds.cloudfiles.CloudFilesApiMetadata; -import org.jclouds.cloudfiles.CloudFilesClient; import org.jclouds.openstack.swift.blobstore.integration.SwiftBlobLiveTest; +import org.jclouds.openstack.swift.extensions.TemporaryUrlKeyApi; import org.testng.annotations.Test; import java.util.UUID; @@ -33,12 +32,13 @@ import static org.testng.Assert.assertNotNull; */ @Test(groups = {"live"}) public class CloudFilesBlobLiveTest extends SwiftBlobLiveTest { + public CloudFilesBlobLiveTest() { provider = "cloudfiles"; } public void testGetAndSetTemporaryUrlKey() { - CloudFilesClient client = view.unwrap(CloudFilesApiMetadata.CONTEXT_TOKEN).getApi(); + TemporaryUrlKeyApi client = view.utils().injector().getInstance(TemporaryUrlKeyApi.class); String currentSecretKey = client.getTemporaryUrlKey(); assertNotNull(currentSecretKey); diff --git a/apis/cloudfiles/src/test/java/org/jclouds/cloudfiles/blobstore/integration/CloudFilesBlobSignerLiveTest.java b/apis/cloudfiles/src/test/java/org/jclouds/cloudfiles/blobstore/integration/CloudFilesBlobSignerLiveTest.java index 9ced14fa93..d67142e575 100644 --- a/apis/cloudfiles/src/test/java/org/jclouds/cloudfiles/blobstore/integration/CloudFilesBlobSignerLiveTest.java +++ b/apis/cloudfiles/src/test/java/org/jclouds/cloudfiles/blobstore/integration/CloudFilesBlobSignerLiveTest.java @@ -18,19 +18,9 @@ */ package org.jclouds.cloudfiles.blobstore.integration; -import org.jclouds.blobstore.domain.Blob; -import org.jclouds.http.HttpRequest; import org.jclouds.openstack.swift.blobstore.integration.SwiftBlobSignerLiveTest; -import org.jclouds.rest.AuthorizationException; -import org.jclouds.util.Strings2; import org.testng.annotations.Test; -import java.io.IOException; -import java.util.concurrent.TimeUnit; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.fail; - /** * @author Adrian Cole */ @@ -39,58 +29,4 @@ public class CloudFilesBlobSignerLiveTest extends SwiftBlobSignerLiveTest { public CloudFilesBlobSignerLiveTest() { provider = "cloudfiles"; } - - @Test - public void testSignGetUrlWithTime() throws InterruptedException, IOException { - String name = "hello"; - String text = "fooooooooooooooooooooooo"; - - Blob blob = view.getBlobStore().blobBuilder(name).payload(text).contentType("text/plain").build(); - String container = getContainerName(); - try { - view.getBlobStore().putBlob(container, blob); - assertConsistencyAwareContainerSize(container, 1); - HttpRequest request = view.getSigner().signGetBlob(container, name, 3 /* seconds */); - - assertEquals(request.getFilters().size(), 0); - assertEquals(Strings2.toString(view.utils().http().invoke(request).getPayload()), text); - - TimeUnit.SECONDS.sleep(4); - try { - Strings2.toString(view.utils().http().invoke(request).getPayload()); - fail("Temporary URL did not expire as expected"); - } catch (AuthorizationException expected) { - } - } finally { - returnContainer(container); - } - } - - @Test - public void testSignPutUrlWithTime() throws Exception { - String name = "hello"; - String text = "fooooooooooooooooooooooo"; - - Blob blob = view.getBlobStore().blobBuilder(name).payload(text).contentType("text/plain").build(); - String container = getContainerName(); - try { - HttpRequest request = view.getSigner().signPutBlob(container, blob, 3 /* seconds */); - assertEquals(request.getFilters().size(), 0); - - Strings2.toString(view.utils().http().invoke(request).getPayload()); - assertConsistencyAwareContainerSize(container, 1); - - view.getBlobStore().removeBlob(container, name); - assertConsistencyAwareContainerSize(container, 0); - - TimeUnit.SECONDS.sleep(4); - try { - Strings2.toString(view.utils().http().invoke(request).getPayload()); - fail("Temporary URL did not expire as expected"); - } catch (AuthorizationException expected) { - } - } finally { - returnContainer(container); - } - } } diff --git a/apis/cloudloadbalancers/pom.xml b/apis/cloudloadbalancers/pom.xml index 48fcd6eda1..aced7205cd 100644 --- a/apis/cloudloadbalancers/pom.xml +++ b/apis/cloudloadbalancers/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.api diff --git a/apis/cloudloadbalancers/src/test/java/org/jclouds/cloudloadbalancers/features/NodeAsyncClientTest.java b/apis/cloudloadbalancers/src/test/java/org/jclouds/cloudloadbalancers/features/NodeAsyncClientTest.java index fb09722a1b..061d810973 100644 --- a/apis/cloudloadbalancers/src/test/java/org/jclouds/cloudloadbalancers/features/NodeAsyncClientTest.java +++ b/apis/cloudloadbalancers/src/test/java/org/jclouds/cloudloadbalancers/features/NodeAsyncClientTest.java @@ -20,7 +20,6 @@ package org.jclouds.cloudloadbalancers.features; import java.io.IOException; import java.lang.reflect.Method; -import java.util.Collections; import java.util.Set; import org.jclouds.cloudloadbalancers.domain.NodeAttributes; @@ -38,6 +37,7 @@ import org.jclouds.rest.functions.ReturnVoidOnNotFoundOr404; import org.jclouds.rest.internal.RestAnnotationProcessor; import org.testng.annotations.Test; +import com.google.common.collect.ImmutableList; import com.google.inject.TypeLiteral; /** @@ -85,7 +85,7 @@ public class NodeAsyncClientTest extends BaseCloudLoadBalancersAsyncClientTestsingleton(NodeRequest.builder(). + HttpRequest httpRequest = processor.createRequest(method, ImmutableList.of(NodeRequest.builder(). address("192.168.1.1").port(8080).build()), 3); assertRequestLineEquals(httpRequest, diff --git a/apis/cloudloadbalancers/src/test/java/org/jclouds/cloudloadbalancers/features/NodeClientLiveTest.java b/apis/cloudloadbalancers/src/test/java/org/jclouds/cloudloadbalancers/features/NodeClientLiveTest.java index 64bfa9611e..f3ddef1ba9 100644 --- a/apis/cloudloadbalancers/src/test/java/org/jclouds/cloudloadbalancers/features/NodeClientLiveTest.java +++ b/apis/cloudloadbalancers/src/test/java/org/jclouds/cloudloadbalancers/features/NodeClientLiveTest.java @@ -22,7 +22,6 @@ import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import java.util.Arrays; -import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; @@ -30,6 +29,8 @@ import java.util.Set; import java.util.Map.Entry; import java.util.logging.Logger; +import com.google.common.collect.ImmutableSet; + import org.jclouds.cloudloadbalancers.domain.LoadBalancer; import org.jclouds.cloudloadbalancers.domain.LoadBalancerRequest; import org.jclouds.cloudloadbalancers.domain.Node; @@ -71,7 +72,7 @@ public class NodeClientLiveTest extends BaseCloudLoadBalancersClientLiveTest { String region = lb.getRegion(); Logger.getAnonymousLogger().info("starting node on loadbalancer " + lb.getId() + " in region " + region); Set newNodes = client.getNodeClient(region).createNodesInLoadBalancer( - Collections. singleton(NodeRequest.builder().address("192.168.1.2").port(8080).build()), + ImmutableSet. of(NodeRequest.builder().address("192.168.1.2").port(8080).build()), lb.getId()); for (Node n : newNodes) { diff --git a/apis/cloudservers/pom.xml b/apis/cloudservers/pom.xml index 41a3c0acfe..a9f3749c4c 100644 --- a/apis/cloudservers/pom.xml +++ b/apis/cloudservers/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml diff --git a/apis/cloudsigma/pom.xml b/apis/cloudsigma/pom.xml index d36ea17daa..b946d7412b 100644 --- a/apis/cloudsigma/pom.xml +++ b/apis/cloudsigma/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.api diff --git a/apis/cloudsigma/src/test/java/org/jclouds/cloudsigma/compute/CloudSigmaComputeServiceLiveTest.java b/apis/cloudsigma/src/test/java/org/jclouds/cloudsigma/compute/CloudSigmaComputeServiceLiveTest.java index bbedf65bdc..5a882ff28f 100644 --- a/apis/cloudsigma/src/test/java/org/jclouds/cloudsigma/compute/CloudSigmaComputeServiceLiveTest.java +++ b/apis/cloudsigma/src/test/java/org/jclouds/cloudsigma/compute/CloudSigmaComputeServiceLiveTest.java @@ -25,12 +25,13 @@ import org.jclouds.sshj.config.SshjSshClientModule; import org.testng.annotations.Test; import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; import com.google.inject.Module; /** * @author Adrian Cole */ -@Test(groups = "live") +@Test(groups = "live", testName = "CloudSigmaComputeServiceLiveTest") public class CloudSigmaComputeServiceLiveTest extends BaseComputeServiceLiveTest { public CloudSigmaComputeServiceLiveTest() { @@ -46,14 +47,21 @@ public class CloudSigmaComputeServiceLiveTest extends BaseComputeServiceLiveTest @Override protected void checkUserMetadataInNodeEquals(NodeMetadata node, ImmutableMap userMetadata) { assert node.getUserMetadata().equals(ImmutableMap. of()) : String.format( - "node userMetadata did not match %s %s", userMetadata, node); + "node userMetadata did not match %s %s", userMetadata, node); } - + + // cloudsigma does not support tags + @Override + protected void checkTagsInNodeEquals(final NodeMetadata node, final ImmutableSet tags) { + assert node.getTags().equals(ImmutableSet. of()) : String.format("node tags did not match %s %s", tags, + node); + } + protected void checkResponseEqualsHostname(ExecResponse execResponse, NodeMetadata node1) { // hostname is not predictable based on node metadata assert execResponse.getOutput().trim().equals("ubuntu"); } - + @Override public void testOptionToNotBlock() { // start call has to block until we have a pool of reserved pre-cloned drives. diff --git a/apis/cloudstack/pom.xml b/apis/cloudstack/pom.xml index c711e8d8fa..c294366cdd 100644 --- a/apis/cloudstack/pom.xml +++ b/apis/cloudstack/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.api diff --git a/apis/cloudstack/src/main/java/org/jclouds/cloudstack/CloudStackApiMetadata.java b/apis/cloudstack/src/main/java/org/jclouds/cloudstack/CloudStackApiMetadata.java index cdb671f895..d0bf37c0b0 100644 --- a/apis/cloudstack/src/main/java/org/jclouds/cloudstack/CloudStackApiMetadata.java +++ b/apis/cloudstack/src/main/java/org/jclouds/cloudstack/CloudStackApiMetadata.java @@ -23,6 +23,7 @@ import java.util.Properties; import org.jclouds.apis.ApiMetadata; import org.jclouds.cloudstack.compute.config.CloudStackComputeServiceContextModule; +import org.jclouds.cloudstack.config.CloudStackParserModule; import org.jclouds.cloudstack.config.CloudStackRestClientModule; import org.jclouds.rest.RestContext; import org.jclouds.rest.internal.BaseRestApiMetadata; @@ -91,7 +92,10 @@ public class CloudStackApiMetadata extends BaseRestApiMetadata { .version("2.2") .view(TypeToken.of(CloudStackContext.class)) .defaultProperties(CloudStackApiMetadata.defaultProperties()) - .defaultModules(ImmutableSet.>of(CloudStackRestClientModule.class, CloudStackComputeServiceContextModule.class)); + .defaultModules(ImmutableSet.> builder() + .add(CloudStackParserModule.class) + .add(CloudStackRestClientModule.class) + .add(CloudStackComputeServiceContextModule.class).build()); } @Override diff --git a/apis/cloudstack/src/main/java/org/jclouds/cloudstack/config/CloudStackDateAdapter.java b/apis/cloudstack/src/main/java/org/jclouds/cloudstack/config/CloudStackDateAdapter.java deleted file mode 100644 index e0bc79b1d9..0000000000 --- a/apis/cloudstack/src/main/java/org/jclouds/cloudstack/config/CloudStackDateAdapter.java +++ /dev/null @@ -1,51 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.cloudstack.config; - -import java.io.IOException; -import java.util.Date; - -import javax.inject.Inject; - -import org.jclouds.date.DateService; -import org.jclouds.json.config.GsonModule.Iso8601DateAdapter; - -import com.google.gson.stream.JsonReader; - -/** - * Data adapter for the date formats used by CloudStack. - * - * Essentially this is a workaround for the CloudStack getUsage() API call returning a - * corrupted form of ISO-8601 dates, which have an unexpected pair of apostrophes, like - * 2011-12-12'T'00:00:00+00:00 - * - * @author Richard Downer - */ -public class CloudStackDateAdapter extends Iso8601DateAdapter { - - @Inject - private CloudStackDateAdapter(DateService dateService) { - super(dateService); - } - - public Date read(JsonReader reader) throws IOException { - return parseDate(reader.nextString().replaceAll("'T'", "T")); - } - -} diff --git a/apis/cloudstack/src/main/java/org/jclouds/cloudstack/config/CloudStackParserModule.java b/apis/cloudstack/src/main/java/org/jclouds/cloudstack/config/CloudStackParserModule.java new file mode 100644 index 0000000000..086529fc30 --- /dev/null +++ b/apis/cloudstack/src/main/java/org/jclouds/cloudstack/config/CloudStackParserModule.java @@ -0,0 +1,115 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.cloudstack.config; + +import java.io.IOException; +import java.util.Date; + +import javax.inject.Inject; + +import org.jclouds.date.DateService; +import org.jclouds.json.config.GsonModule.DateAdapter; +import org.jclouds.json.config.GsonModule.Iso8601DateAdapter; +import org.jclouds.json.internal.IgnoreNullIterableTypeAdapterFactory; + +import com.google.common.base.Splitter; +import com.google.common.base.Strings; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableList.Builder; +import com.google.common.collect.ImmutableSet; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonToken; +import com.google.gson.stream.JsonWriter; +import com.google.inject.AbstractModule; + +/** + * @author Adrian Cole + */ +public class CloudStackParserModule extends AbstractModule { + + @Override + protected void configure() { + bind(DateAdapter.class).to(CloudStackDateAdapter.class); + bind(IgnoreNullIterableTypeAdapterFactory.class).to(CommaDelimitedOKIgnoreNullIterableTypeAdapterFactory.class); + } + + /** + * Data adapter for the date formats used by CloudStack. + * + * Essentially this is a workaround for the CloudStack getUsage() API call returning a corrupted + * form of ISO-8601 dates, which have an unexpected pair of apostrophes, like + * 2011-12-12'T'00:00:00+00:00 + * + * @author Richard Downer + */ + public static class CloudStackDateAdapter extends Iso8601DateAdapter { + + @Inject + private CloudStackDateAdapter(DateService dateService) { + super(dateService); + } + + public Date read(JsonReader reader) throws IOException { + return parseDate(reader.nextString().replaceAll("'T'", "T")); + } + + } + + /** + * Handles types that were previously strings and now arrays (ex. tags) + * + * @author Adrian Cole + */ + public static class CommaDelimitedOKIgnoreNullIterableTypeAdapterFactory extends IgnoreNullIterableTypeAdapterFactory { + + @Override + protected TypeAdapter> newIterableAdapter(final TypeAdapter elementAdapter) { + return new TypeAdapter>() { + public void write(JsonWriter out, Iterable value) throws IOException { + out.beginArray(); + for (E element : value) { + elementAdapter.write(out, element); + } + out.endArray(); + } + + @SuppressWarnings("unchecked") + public Iterable read(JsonReader in) throws IOException { + // HACK as cloudstack changed a field from String to Set! + if (in.peek() == JsonToken.STRING) { + String val = Strings.emptyToNull(in.nextString()); + return (Iterable) (val != null ? Splitter.on(',').split(val) : ImmutableSet.of()); + } else { + Builder builder = ImmutableList. builder(); + in.beginArray(); + while (in.hasNext()) { + E element = elementAdapter.read(in); + if (element != null) + builder.add(element); + } + in.endArray(); + return builder.build(); + } + } + }.nullSafe(); + } + } + +} diff --git a/apis/cloudstack/src/main/java/org/jclouds/cloudstack/config/CloudStackRestClientModule.java b/apis/cloudstack/src/main/java/org/jclouds/cloudstack/config/CloudStackRestClientModule.java index 695d72864c..cbdb216c61 100644 --- a/apis/cloudstack/src/main/java/org/jclouds/cloudstack/config/CloudStackRestClientModule.java +++ b/apis/cloudstack/src/main/java/org/jclouds/cloudstack/config/CloudStackRestClientModule.java @@ -33,7 +33,86 @@ import org.jclouds.cloudstack.CloudStackDomainClient; import org.jclouds.cloudstack.CloudStackGlobalAsyncClient; import org.jclouds.cloudstack.CloudStackGlobalClient; import org.jclouds.cloudstack.domain.LoginResponse; -import org.jclouds.cloudstack.features.*; +import org.jclouds.cloudstack.features.AccountAsyncClient; +import org.jclouds.cloudstack.features.AccountClient; +import org.jclouds.cloudstack.features.AddressAsyncClient; +import org.jclouds.cloudstack.features.AddressClient; +import org.jclouds.cloudstack.features.AsyncJobAsyncClient; +import org.jclouds.cloudstack.features.AsyncJobClient; +import org.jclouds.cloudstack.features.ConfigurationAsyncClient; +import org.jclouds.cloudstack.features.ConfigurationClient; +import org.jclouds.cloudstack.features.DomainAccountAsyncClient; +import org.jclouds.cloudstack.features.DomainAccountClient; +import org.jclouds.cloudstack.features.DomainDomainAsyncClient; +import org.jclouds.cloudstack.features.DomainDomainClient; +import org.jclouds.cloudstack.features.DomainLimitAsyncClient; +import org.jclouds.cloudstack.features.DomainLimitClient; +import org.jclouds.cloudstack.features.DomainUserAsyncClient; +import org.jclouds.cloudstack.features.DomainUserClient; +import org.jclouds.cloudstack.features.EventAsyncClient; +import org.jclouds.cloudstack.features.EventClient; +import org.jclouds.cloudstack.features.FirewallAsyncClient; +import org.jclouds.cloudstack.features.FirewallClient; +import org.jclouds.cloudstack.features.GlobalAccountAsyncClient; +import org.jclouds.cloudstack.features.GlobalAccountClient; +import org.jclouds.cloudstack.features.GlobalAlertAsyncClient; +import org.jclouds.cloudstack.features.GlobalAlertClient; +import org.jclouds.cloudstack.features.GlobalCapacityAsyncClient; +import org.jclouds.cloudstack.features.GlobalCapacityClient; +import org.jclouds.cloudstack.features.GlobalConfigurationAsyncClient; +import org.jclouds.cloudstack.features.GlobalConfigurationClient; +import org.jclouds.cloudstack.features.GlobalDomainAsyncClient; +import org.jclouds.cloudstack.features.GlobalDomainClient; +import org.jclouds.cloudstack.features.GlobalHostAsyncClient; +import org.jclouds.cloudstack.features.GlobalHostClient; +import org.jclouds.cloudstack.features.GlobalOfferingAsyncClient; +import org.jclouds.cloudstack.features.GlobalOfferingClient; +import org.jclouds.cloudstack.features.GlobalPodAsyncClient; +import org.jclouds.cloudstack.features.GlobalPodClient; +import org.jclouds.cloudstack.features.GlobalStoragePoolAsyncClient; +import org.jclouds.cloudstack.features.GlobalStoragePoolClient; +import org.jclouds.cloudstack.features.GlobalUsageAsyncClient; +import org.jclouds.cloudstack.features.GlobalUsageClient; +import org.jclouds.cloudstack.features.GlobalUserAsyncClient; +import org.jclouds.cloudstack.features.GlobalUserClient; +import org.jclouds.cloudstack.features.GlobalVlanAsyncClient; +import org.jclouds.cloudstack.features.GlobalVlanClient; +import org.jclouds.cloudstack.features.GlobalZoneAsyncClient; +import org.jclouds.cloudstack.features.GlobalZoneClient; +import org.jclouds.cloudstack.features.GuestOSAsyncClient; +import org.jclouds.cloudstack.features.GuestOSClient; +import org.jclouds.cloudstack.features.HypervisorAsyncClient; +import org.jclouds.cloudstack.features.HypervisorClient; +import org.jclouds.cloudstack.features.ISOAsyncClient; +import org.jclouds.cloudstack.features.ISOClient; +import org.jclouds.cloudstack.features.LimitAsyncClient; +import org.jclouds.cloudstack.features.LimitClient; +import org.jclouds.cloudstack.features.LoadBalancerAsyncClient; +import org.jclouds.cloudstack.features.LoadBalancerClient; +import org.jclouds.cloudstack.features.NATAsyncClient; +import org.jclouds.cloudstack.features.NATClient; +import org.jclouds.cloudstack.features.NetworkAsyncClient; +import org.jclouds.cloudstack.features.NetworkClient; +import org.jclouds.cloudstack.features.OfferingAsyncClient; +import org.jclouds.cloudstack.features.OfferingClient; +import org.jclouds.cloudstack.features.SSHKeyPairAsyncClient; +import org.jclouds.cloudstack.features.SSHKeyPairClient; +import org.jclouds.cloudstack.features.SecurityGroupAsyncClient; +import org.jclouds.cloudstack.features.SecurityGroupClient; +import org.jclouds.cloudstack.features.SessionAsyncClient; +import org.jclouds.cloudstack.features.SessionClient; +import org.jclouds.cloudstack.features.SnapshotAsyncClient; +import org.jclouds.cloudstack.features.SnapshotClient; +import org.jclouds.cloudstack.features.TemplateAsyncClient; +import org.jclouds.cloudstack.features.TemplateClient; +import org.jclouds.cloudstack.features.VMGroupAsyncClient; +import org.jclouds.cloudstack.features.VMGroupClient; +import org.jclouds.cloudstack.features.VirtualMachineAsyncClient; +import org.jclouds.cloudstack.features.VirtualMachineClient; +import org.jclouds.cloudstack.features.VolumeAsyncClient; +import org.jclouds.cloudstack.features.VolumeClient; +import org.jclouds.cloudstack.features.ZoneAsyncClient; +import org.jclouds.cloudstack.features.ZoneClient; import org.jclouds.cloudstack.filters.AddSessionKeyAndJSessionIdToRequest; import org.jclouds.cloudstack.filters.AuthenticationFilter; import org.jclouds.cloudstack.filters.QuerySigner; @@ -47,7 +126,6 @@ import org.jclouds.http.HttpRetryHandler; 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.location.Provider; import org.jclouds.location.suppliers.ImplicitLocationSupplier; import org.jclouds.location.suppliers.implicit.OnlyLocationOrFirstZone; @@ -147,7 +225,6 @@ public class CloudStackRestClientModule extends RestClientModule>() { }).to(new TypeLiteral>() { }); diff --git a/apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/DiskOffering.java b/apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/DiskOffering.java index ba0a5874ed..97632e4e6e 100644 --- a/apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/DiskOffering.java +++ b/apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/DiskOffering.java @@ -22,11 +22,13 @@ import static com.google.common.base.Preconditions.checkNotNull; import java.beans.ConstructorProperties; import java.util.Date; +import java.util.Set; 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 DiskOffering @@ -54,7 +56,7 @@ public class DiskOffering implements Comparable { protected String domainId; protected int diskSize; protected boolean customized; - protected String tags; + protected ImmutableSet.Builder tags = ImmutableSet.builder(); /** * @see DiskOffering#getId() @@ -123,13 +125,21 @@ public class DiskOffering implements Comparable { /** * @see DiskOffering#getTags() */ - public T tags(String tags) { - this.tags = tags; + public T tags(Iterable tags) { + this.tags = ImmutableSet.builder().addAll(tags); return self(); } - + + /** + * @see DiskOffering#getTags() + */ + public T tag(String tag) { + this.tags.add(tag); + return self(); + } + public DiskOffering build() { - return new DiskOffering(id, name, displayText, created, domain, domainId, diskSize, customized, tags); + return new DiskOffering(id, name, displayText, created, domain, domainId, diskSize, customized, tags.build()); } public T fromDiskOffering(DiskOffering in) { @@ -161,14 +171,14 @@ public class DiskOffering implements Comparable { private final String domainId; private final int diskSize; private final boolean customized; - private final String tags; + private final Set tags; @ConstructorProperties({ "id", "name", "displaytext", "created", "domain", "domainid", "disksize", "iscustomized", "tags" }) protected DiskOffering(String id, @Nullable String name, @Nullable String displayText, @Nullable Date created, @Nullable String domain, @Nullable String domainId, int diskSize, boolean customized, - @Nullable String tags) { + @Nullable Iterable tags) { this.id = checkNotNull(id, "id"); this.name = name; this.displayText = displayText; @@ -177,7 +187,7 @@ public class DiskOffering implements Comparable { this.domainId = domainId; this.diskSize = diskSize; this.customized = customized; - this.tags = tags; + this.tags = tags != null ? ImmutableSet.copyOf(tags) : ImmutableSet. of(); } /** @@ -244,8 +254,7 @@ public class DiskOffering implements Comparable { /** * @return the tags for the disk offering */ - @Nullable - public String getTags() { + public Set getTags() { return this.tags; } diff --git a/apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/Host.java b/apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/Host.java index 7d9ea4a982..1cd4c6e15b 100644 --- a/apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/Host.java +++ b/apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/Host.java @@ -24,11 +24,13 @@ import static com.google.common.base.Preconditions.checkNotNull; import java.beans.ConstructorProperties; import java.util.Date; +import java.util.Set; 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; /** * Represents a host issued by Cloudstack @@ -149,7 +151,7 @@ public class Host implements Comparable { protected long diskSizeTotal; protected String events; protected boolean hasEnoughCapacity; - protected String hostTags; + protected ImmutableSet.Builder tags = ImmutableSet.builder(); protected String hypervisor; protected String ipAddress; protected boolean localStorageActive; @@ -319,13 +321,21 @@ public class Host implements Comparable { } /** - * @see Host#getHostTags() + * @see Host#getTags() */ - public T hostTags(String hostTags) { - this.hostTags = hostTags; + public T tags(Iterable tags) { + this.tags = ImmutableSet.builder().addAll(tags); return self(); } - + + /** + * @see Host#getTags() + */ + public T tag(String tag) { + this.tags.add(tag); + return self(); + } + /** * @see Host#getHypervisor() */ @@ -512,7 +522,7 @@ public class Host implements Comparable { public Host build() { - return new Host(id, allocationState, averageLoad, capabilities, clusterId, clusterName, clusterType, cpuAllocated, cpuNumber, cpuSpeed, cpuUsed, cpuWithOverProvisioning, created, disconnected, diskSizeAllocated, diskSizeTotal, events, hasEnoughCapacity, hostTags, hypervisor, ipAddress, localStorageActive, jobId, jobStatus, lastPinged, managementServerId, memoryAllocated, memoryTotal, memoryUsed, name, networkKbsRead, networkKbsWrite, osCategoryId, osCategoryName, podId, podName, removed, state, type, version, zoneId, zoneName); + return new Host(id, allocationState, averageLoad, capabilities, clusterId, clusterName, clusterType, cpuAllocated, cpuNumber, cpuSpeed, cpuUsed, cpuWithOverProvisioning, created, disconnected, diskSizeAllocated, diskSizeTotal, events, hasEnoughCapacity, tags.build(), hypervisor, ipAddress, localStorageActive, jobId, jobStatus, lastPinged, managementServerId, memoryAllocated, memoryTotal, memoryUsed, name, networkKbsRead, networkKbsWrite, osCategoryId, osCategoryName, podId, podName, removed, state, type, version, zoneId, zoneName); } public T fromHost(Host in) { @@ -535,7 +545,7 @@ public class Host implements Comparable { .diskSizeTotal(in.getDiskSizeTotal()) .events(in.getEvents()) .hasEnoughCapacity(in.isHasEnoughCapacity()) - .hostTags(in.getHostTags()) + .tags(in.getTags()) .hypervisor(in.getHypervisor()) .ipAddress(in.getIpAddress()) .localStorageActive(in.isLocalStorageActive()) @@ -587,7 +597,7 @@ public class Host implements Comparable { private final long diskSizeTotal; private final String events; private final boolean hasEnoughCapacity; - private final String hostTags; + private final Set tags; private final String hypervisor; private final String ipAddress; private final boolean localStorageActive; @@ -619,7 +629,7 @@ public class Host implements Comparable { @Nullable String clusterId, @Nullable String clusterName, @Nullable Host.ClusterType clusterType, @Nullable String cpuAllocated, int cpuNumber, int cpuSpeed, @Nullable String cpuUsed, float cpuWithOverProvisioning, @Nullable Date created, @Nullable Date disconnected, long diskSizeAllocated, - long diskSizeTotal, @Nullable String events, boolean hasEnoughCapacity, @Nullable String hostTags, + long diskSizeTotal, @Nullable String events, boolean hasEnoughCapacity, @Nullable Iterable tags, @Nullable String hypervisor, @Nullable String ipAddress, boolean localStorageActive, @Nullable String jobId, @Nullable AsyncJob.Status jobStatus, @Nullable Date lastPinged, @Nullable String managementServerId, long memoryAllocated, long memoryTotal, long memoryUsed, @Nullable String name, long networkKbsRead, long networkKbsWrite, @@ -644,7 +654,7 @@ public class Host implements Comparable { this.diskSizeTotal = diskSizeTotal; this.events = events; this.hasEnoughCapacity = hasEnoughCapacity; - this.hostTags = hostTags; + this.tags = tags != null ? ImmutableSet.copyOf(tags) : ImmutableSet. of(); this.hypervisor = hypervisor; this.ipAddress = ipAddress; this.localStorageActive = localStorageActive; @@ -752,11 +762,14 @@ public class Host implements Comparable { return this.hasEnoughCapacity; } - @Nullable - public String getHostTags() { - return this.hostTags; + /** + * @return the tags for the host + */ + public Set getTags() { + return this.tags; } + @Nullable public String getHypervisor() { return this.hypervisor; @@ -868,7 +881,7 @@ public class Host implements Comparable { @Override public int hashCode() { - return Objects.hashCode(id, allocationState, averageLoad, capabilities, clusterId, clusterName, clusterType, cpuAllocated, cpuNumber, cpuSpeed, cpuUsed, cpuWithOverProvisioning, created, disconnected, diskSizeAllocated, diskSizeTotal, events, hasEnoughCapacity, hostTags, hypervisor, ipAddress, localStorageActive, jobId, jobStatus, lastPinged, managementServerId, memoryAllocated, memoryTotal, memoryUsed, name, networkKbsRead, networkKbsWrite, osCategoryId, osCategoryName, podId, podName, removed, state, type, version, zoneId, zoneName); + return Objects.hashCode(id, allocationState, averageLoad, capabilities, clusterId, clusterName, clusterType, cpuAllocated, cpuNumber, cpuSpeed, cpuUsed, cpuWithOverProvisioning, created, disconnected, diskSizeAllocated, diskSizeTotal, events, hasEnoughCapacity, tags, hypervisor, ipAddress, localStorageActive, jobId, jobStatus, lastPinged, managementServerId, memoryAllocated, memoryTotal, memoryUsed, name, networkKbsRead, networkKbsWrite, osCategoryId, osCategoryName, podId, podName, removed, state, type, version, zoneId, zoneName); } @Override @@ -894,7 +907,7 @@ public class Host implements Comparable { && Objects.equal(this.diskSizeTotal, that.diskSizeTotal) && Objects.equal(this.events, that.events) && Objects.equal(this.hasEnoughCapacity, that.hasEnoughCapacity) - && Objects.equal(this.hostTags, that.hostTags) + && Objects.equal(this.tags, that.tags) && Objects.equal(this.hypervisor, that.hypervisor) && Objects.equal(this.ipAddress, that.ipAddress) && Objects.equal(this.localStorageActive, that.localStorageActive) @@ -928,7 +941,7 @@ public class Host implements Comparable { .add("cpuSpeed", cpuSpeed).add("cpuUsed", cpuUsed).add("cpuWithOverProvisioning", cpuWithOverProvisioning) .add("created", created).add("disconnected", disconnected).add("diskSizeAllocated", diskSizeAllocated) .add("diskSizeTotal", diskSizeTotal).add("events", events).add("hasEnoughCapacity", hasEnoughCapacity) - .add("hostTags", hostTags).add("hypervisor", hypervisor).add("ipAddress", ipAddress) + .add("tags", tags).add("hypervisor", hypervisor).add("ipAddress", ipAddress) .add("localStorageActive", localStorageActive).add("jobId", jobId).add("jobStatus", jobStatus) .add("lastPinged", lastPinged).add("managementServerId", managementServerId).add("memoryAllocated", memoryAllocated) .add("memoryTotal", memoryTotal).add("memoryUsed", memoryUsed).add("name", name).add("networkKbsRead", networkKbsRead) diff --git a/apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/Network.java b/apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/Network.java index 457edd049c..08dd4501d9 100644 --- a/apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/Network.java +++ b/apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/Network.java @@ -30,6 +30,7 @@ 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; +import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; /** @@ -78,7 +79,7 @@ public class Network { protected String VLAN; protected TrafficType trafficType; protected String zoneId; - protected String tags; + protected ImmutableSet.Builder tags = ImmutableSet.builder(); protected boolean securityGroupEnabled; protected Set services = ImmutableSortedSet.of(); @@ -302,10 +303,19 @@ public class Network { /** * @see Network#getTags() */ - public T tags(String tags) { - this.tags = tags; + public T tags(Iterable tags) { + this.tags = ImmutableSet.builder().addAll(tags); return self(); } + + /** + * @see Network#getTags() + */ + public T tag(String tag) { + this.tags.add(tag); + return self(); + } + /** * @see Network#isSecurityGroupEnabled() @@ -324,7 +334,7 @@ public class Network { } public Network build() { - return new Network(id, account, broadcastDomainType, broadcastURI, displayText, DNS1, DNS2, domain, domainId, endIP, gateway, isDefault, isShared, isSystem, netmask, networkDomain, networkOfferingAvailability, networkOfferingDisplayText, networkOfferingId, networkOfferingName, related, startIP, name, state, guestIPType, VLAN, trafficType, zoneId, tags, securityGroupEnabled, services); + return new Network(id, account, broadcastDomainType, broadcastURI, displayText, DNS1, DNS2, domain, domainId, endIP, gateway, isDefault, isShared, isSystem, netmask, networkDomain, networkOfferingAvailability, networkOfferingDisplayText, networkOfferingId, networkOfferingName, related, startIP, name, state, guestIPType, VLAN, trafficType, zoneId, tags.build(), securityGroupEnabled, services); } public T fromNetwork(Network in) { @@ -397,7 +407,7 @@ public class Network { private final String VLAN; private final TrafficType trafficType; private final String zoneId; - private final String tags; + private final Set tags; private final boolean securityGroupEnabled; private final Set services; @@ -411,7 +421,7 @@ public class Network { @Nullable String networkOfferingDisplayText, @Nullable String networkOfferingId, @Nullable String networkOfferingName, @Nullable String related, @Nullable String startIP, @Nullable String name, @Nullable String state, @Nullable GuestIPType guestIPType, @Nullable String VLAN, @Nullable TrafficType trafficType, - @Nullable String zoneId, @Nullable String tags, boolean securityGroupEnabled, Set services) { + @Nullable String zoneId, @Nullable Iterable tags, boolean securityGroupEnabled, Set services) { this.id = checkNotNull(id, "id"); this.account = account; this.broadcastDomainType = broadcastDomainType; @@ -440,7 +450,7 @@ public class Network { this.VLAN = VLAN; this.trafficType = trafficType; this.zoneId = zoneId; - this.tags = tags; + this.tags = tags != null ? ImmutableSet.copyOf(tags) : ImmutableSet. of(); this.securityGroupEnabled = securityGroupEnabled; this.services = ImmutableSortedSet.copyOf(services); } @@ -660,8 +670,7 @@ public class Network { /** * @return the tags for the Network */ - @Nullable - public String getTags() { + public Set getTags() { return this.tags; } diff --git a/apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/NetworkOffering.java b/apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/NetworkOffering.java index 876b5245d6..1ec0a857a9 100644 --- a/apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/NetworkOffering.java +++ b/apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/NetworkOffering.java @@ -22,11 +22,13 @@ import static com.google.common.base.Preconditions.checkNotNull; import java.beans.ConstructorProperties; import java.util.Date; +import java.util.Set; 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 NetworkOffering @@ -57,7 +59,7 @@ public class NetworkOffering implements Comparable { protected TrafficType trafficType; protected GuestIPType guestIPType; protected int networkRate; - protected String tags; + protected ImmutableSet.Builder tags = ImmutableSet.builder(); /** * @see NetworkOffering#getId() @@ -146,17 +148,26 @@ public class NetworkOffering implements Comparable { this.networkRate = networkRate; return self(); } - + /** * @see NetworkOffering#getTags() */ - public T tags(String tags) { - this.tags = tags; + public T tags(Iterable tags) { + this.tags = ImmutableSet.builder().addAll(tags); return self(); } + + /** + * @see NetworkOffering#getTags() + */ + public T tag(String tag) { + this.tags.add(tag); + return self(); + } + public NetworkOffering build() { - return new NetworkOffering(id, name, displayText, created, availability, maxConnections, isDefault, supportsVLAN, trafficType, guestIPType, networkRate, tags); + return new NetworkOffering(id, name, displayText, created, availability, maxConnections, isDefault, supportsVLAN, trafficType, guestIPType, networkRate, tags.build()); } public T fromNetworkOffering(NetworkOffering in) { @@ -194,12 +205,12 @@ public class NetworkOffering implements Comparable { private final TrafficType trafficType; private final GuestIPType guestIPType; private final int networkRate; - private final String tags; + private final Set tags; @ConstructorProperties({ "id", "name", "displaytext", "created", "availability", "maxconnections", "isdefault", "specifyvlan", "traffictype", "guestiptype", "networkrate", "tags" }) - protected NetworkOffering(String id, @Nullable String name, @Nullable String displayText, @Nullable Date created, @Nullable NetworkOfferingAvailabilityType availability, @Nullable Integer maxConnections, boolean isDefault, boolean supportsVLAN, @Nullable TrafficType trafficType, @Nullable GuestIPType guestIPType, int networkRate, @Nullable String tags) { + protected NetworkOffering(String id, @Nullable String name, @Nullable String displayText, @Nullable Date created, @Nullable NetworkOfferingAvailabilityType availability, @Nullable Integer maxConnections, boolean isDefault, boolean supportsVLAN, @Nullable TrafficType trafficType, @Nullable GuestIPType guestIPType, int networkRate, @Nullable Iterable tags) { this.id = checkNotNull(id, "id"); this.name = name; this.displayText = displayText; @@ -211,7 +222,7 @@ public class NetworkOffering implements Comparable { this.trafficType = trafficType; this.guestIPType = guestIPType; this.networkRate = networkRate; - this.tags = tags; + this.tags = tags != null ? ImmutableSet.copyOf(tags) : ImmutableSet. of(); } /** @@ -302,8 +313,7 @@ public class NetworkOffering implements Comparable { /** * @return the tags for the network offering */ - @Nullable - public String getTags() { + public Set getTags() { return this.tags; } diff --git a/apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/ServiceOffering.java b/apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/ServiceOffering.java index b5bd47f365..e472da73c3 100644 --- a/apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/ServiceOffering.java +++ b/apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/ServiceOffering.java @@ -26,11 +26,8 @@ import java.util.Set; import org.jclouds.javax.annotation.Nullable; -import com.google.common.base.Joiner; import com.google.common.base.Objects; import com.google.common.base.Objects.ToStringHelper; -import com.google.common.base.Splitter; -import com.google.common.base.Strings; import com.google.common.collect.ImmutableSet; /** @@ -63,12 +60,11 @@ public class ServiceOffering implements Comparable { protected boolean haSupport; protected StorageType storageType; protected boolean defaultUse; - protected String hostTags; protected boolean systemOffering; protected boolean cpuUseLimited; protected long networkRate; protected boolean systemVmType; - private Set tags = ImmutableSet.of(); + protected ImmutableSet.Builder tags = ImmutableSet.builder(); /** * @see ServiceOffering#getId() @@ -161,11 +157,19 @@ public class ServiceOffering implements Comparable { /** * @see ServiceOffering#getTags() */ - public T tags(Set tags) { - this.tags = ImmutableSet.copyOf(checkNotNull(tags, "tags")); + public T tags(Iterable tags) { + this.tags = ImmutableSet.builder().addAll(tags); return self(); } - + + /** + * @see ServiceOffering#getTags() + */ + public T tag(String tag) { + this.tags.add(tag); + return self(); + } + /** * @see ServiceOffering#isDefaultUse() */ @@ -174,14 +178,6 @@ public class ServiceOffering implements Comparable { return self(); } - /** - * @see ServiceOffering#getHostTags() - */ - public T hostTags(String hostTags) { - this.hostTags = hostTags; - return self(); - } - /** * @see ServiceOffering#isSystemOffering() */ @@ -216,7 +212,7 @@ public class ServiceOffering implements Comparable { public ServiceOffering build() { return new ServiceOffering(id, name, displayText, created, domain, domainId, cpuNumber, cpuSpeed, memory, haSupport, storageType, - Joiner.on(",").join(tags), defaultUse, hostTags, systemOffering, cpuUseLimited, networkRate, systemVmType); + tags.build(), defaultUse, systemOffering, cpuUseLimited, networkRate, systemVmType); } public T fromServiceOffering(ServiceOffering in) { @@ -234,7 +230,6 @@ public class ServiceOffering implements Comparable { .storageType(in.getStorageType()) .tags(in.getTags()) .defaultUse(in.isDefaultUse()) - .hostTags(in.getHostTags()) .systemOffering(in.isSystemOffering()) .cpuUseLimited(in.isCpuUseLimited()) .networkRate(in.getNetworkRate()) @@ -262,19 +257,18 @@ public class ServiceOffering implements Comparable { private final StorageType storageType; private final Set tags; private final boolean defaultUse; - private final String hostTags; private final boolean systemOffering; private final boolean cpuUseLimited; private final long networkRate; private final boolean systemVmType; @ConstructorProperties({ - "id", "name", "displaytext", "created", "domain", "domainid", "cpunumber", "cpuspeed", "memory", "offerha", "storagetype", "tags", "defaultuse", "hosttags", "issystem", "limitcpuuse", "networkrate", "systemvmtype" + "id", "name", "displaytext", "created", "domain", "domainid", "cpunumber", "cpuspeed", "memory", "offerha", "storagetype", "tags", "defaultuse", "issystem", "limitcpuuse", "networkrate", "systemvmtype" }) protected ServiceOffering(String id, @Nullable String name, @Nullable String displayText, @Nullable Date created, @Nullable String domain, @Nullable String domainId, int cpuNumber, int cpuSpeed, int memory, - boolean haSupport, @Nullable StorageType storageType, @Nullable String tags, boolean defaultUse, - @Nullable String hostTags, boolean systemOffering, boolean cpuUseLimited, long networkRate, boolean systemVmType) { + boolean haSupport, @Nullable StorageType storageType, @Nullable Iterable tags, boolean defaultUse, + boolean systemOffering, boolean cpuUseLimited, long networkRate, boolean systemVmType) { this.id = checkNotNull(id, "id"); this.name = name; this.displayText = displayText; @@ -286,10 +280,8 @@ public class ServiceOffering implements Comparable { this.memory = memory; this.haSupport = haSupport; this.storageType = storageType; - this.tags = !(Strings.emptyToNull(tags) == null) ? ImmutableSet.copyOf(Splitter.on(',').split(tags)) - : ImmutableSet. of(); + this.tags = tags != null ? ImmutableSet.copyOf(tags) : ImmutableSet. of(); this.defaultUse = defaultUse; - this.hostTags = hostTags; this.systemOffering = systemOffering; this.cpuUseLimited = cpuUseLimited; this.networkRate = networkRate; @@ -389,14 +381,6 @@ public class ServiceOffering implements Comparable { return this.defaultUse; } - /** - * @return the host tag for the service offering - */ - @Nullable - public String getHostTags() { - return this.hostTags; - } - /** * @return whether this is a system vm offering */ @@ -427,7 +411,7 @@ public class ServiceOffering implements Comparable { @Override public int hashCode() { - return Objects.hashCode(id, name, displayText, created, domain, domainId, cpuNumber, cpuSpeed, memory, haSupport, storageType, tags, defaultUse, hostTags, systemOffering, cpuUseLimited, networkRate, systemVmType); + return Objects.hashCode(id, name, displayText, created, domain, domainId, cpuNumber, cpuSpeed, memory, haSupport, storageType, tags, defaultUse, systemOffering, cpuUseLimited, networkRate, systemVmType); } @Override @@ -448,7 +432,6 @@ public class ServiceOffering implements Comparable { && Objects.equal(this.storageType, that.storageType) && Objects.equal(this.getTags(), that.getTags()) && Objects.equal(this.defaultUse, that.defaultUse) - && Objects.equal(this.hostTags, that.hostTags) && Objects.equal(this.systemOffering, that.systemOffering) && Objects.equal(this.cpuUseLimited, that.cpuUseLimited) && Objects.equal(this.networkRate, that.networkRate) @@ -460,7 +443,7 @@ public class ServiceOffering implements Comparable { .add("id", id).add("name", name).add("displayText", displayText).add("created", created).add("domain", domain) .add("domainId", domainId).add("cpuNumber", cpuNumber).add("cpuSpeed", cpuSpeed).add("memory", memory) .add("haSupport", haSupport).add("storageType", storageType).add("tags", getTags()).add("defaultUse", defaultUse) - .add("hostTags", hostTags).add("systemOffering", systemOffering).add("cpuUseLimited", cpuUseLimited) + .add("systemOffering", systemOffering).add("cpuUseLimited", cpuUseLimited) .add("networkRate", networkRate).add("systemVmType", systemVmType); } diff --git a/apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/StoragePool.java b/apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/StoragePool.java index 5416c07c24..5c9a32775b 100644 --- a/apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/StoragePool.java +++ b/apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/StoragePool.java @@ -22,12 +22,14 @@ import static com.google.common.base.Preconditions.checkNotNull; import java.beans.ConstructorProperties; import java.util.Date; +import java.util.Set; import org.jclouds.javax.annotation.Nullable; import com.google.common.base.CaseFormat; import com.google.common.base.Objects; import com.google.common.base.Objects.ToStringHelper; +import com.google.common.collect.ImmutableSet; /** * Represents a storage pool in CloudStack @@ -102,7 +104,7 @@ public class StoragePool implements Comparable { protected String id; protected String name; protected String path; - protected String tags; + protected ImmutableSet.Builder tags = ImmutableSet.builder(); protected StoragePool.State state; protected StoragePool.Type type; protected String zoneId; @@ -143,10 +145,18 @@ public class StoragePool implements Comparable { } /** - * @see StoragePool#getTags() + * @see DiskOffering#getTags() */ - public T tags(String tags) { - this.tags = tags; + public T tags(Iterable tags) { + this.tags = ImmutableSet.builder().addAll(tags); + return self(); + } + + /** + * @see DiskOffering#getTags() + */ + public T tag(String tag) { + this.tags.add(tag); return self(); } @@ -263,7 +273,7 @@ public class StoragePool implements Comparable { } public StoragePool build() { - return new StoragePool(id, name, path, tags, state, type, zoneId, zoneName, podId, podName, clusterId, clusterName, created, diskSizeAllocated, diskSizeTotal, ipAddress, jobId, jobStatus); + return new StoragePool(id, name, path, tags.build(), state, type, zoneId, zoneName, podId, podName, clusterId, clusterName, created, diskSizeAllocated, diskSizeTotal, ipAddress, jobId, jobStatus); } public T fromStoragePool(StoragePool in) { @@ -299,7 +309,7 @@ public class StoragePool implements Comparable { private final String id; private final String name; private final String path; - private final String tags; + private final Set tags; private final StoragePool.State state; private final StoragePool.Type type; private final String zoneId; @@ -318,11 +328,15 @@ public class StoragePool implements Comparable { @ConstructorProperties({ "id", "name", "path", "tags", "state", "type", "zoneid", "zonename", "podid", "podname", "clusterid", "clustername", "created", "disksizeallocated", "disksizetotal", "ipaddress", "jobid", "jobstatus" }) - protected StoragePool(String id, @Nullable String name, @Nullable String path, @Nullable String tags, @Nullable StoragePool.State state, @Nullable StoragePool.Type type, @Nullable String zoneId, @Nullable String zoneName, @Nullable String podId, @Nullable String podName, @Nullable String clusterId, @Nullable String clusterName, @Nullable Date created, long diskSizeAllocated, long diskSizeTotal, @Nullable String ipAddress, @Nullable String jobId, @Nullable String jobStatus) { + protected StoragePool(String id, @Nullable String name, @Nullable String path, @Nullable Iterable tags, + @Nullable StoragePool.State state, @Nullable StoragePool.Type type, @Nullable String zoneId, + @Nullable String zoneName, @Nullable String podId, @Nullable String podName, @Nullable String clusterId, + @Nullable String clusterName, @Nullable Date created, long diskSizeAllocated, long diskSizeTotal, + @Nullable String ipAddress, @Nullable String jobId, @Nullable String jobStatus) { this.id = checkNotNull(id, "id"); this.name = name; this.path = path; - this.tags = tags; + this.tags = tags != null ? ImmutableSet.copyOf(tags) : ImmutableSet. of(); this.state = state; this.type = type; this.zoneId = zoneId; @@ -353,8 +367,7 @@ public class StoragePool implements Comparable { return this.path; } - @Nullable - public String getTags() { + public Set getTags() { return this.tags; } diff --git a/apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/TemplateFilter.java b/apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/TemplateFilter.java index ecd39c6e92..bd578010d2 100644 --- a/apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/TemplateFilter.java +++ b/apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/TemplateFilter.java @@ -40,6 +40,15 @@ public enum TemplateFilter { * to deploy a new VM */ SELF_EXECUTABLE, + /** + * templates that have been registered/created by the owner that can be used + * to deploy a new VM - 3.x filter value. + */ + SELFEXECUTABLE, + /** + * templates that have been granted to the calling user by another user + */ + SHAREDEXECUTABLE, /** * all templates that can be used to deploy a new VM */ @@ -47,7 +56,11 @@ public enum TemplateFilter { /** * templates that are public */ - COMMUNITY; + COMMUNITY, + /** + * All templates + */ + ALL; @Override public String toString() { diff --git a/apis/cloudstack/src/main/java/org/jclouds/cloudstack/functions/WindowsLoginCredentialsFromEncryptedData.java b/apis/cloudstack/src/main/java/org/jclouds/cloudstack/functions/WindowsLoginCredentialsFromEncryptedData.java index 732a74c507..95807433c3 100644 --- a/apis/cloudstack/src/main/java/org/jclouds/cloudstack/functions/WindowsLoginCredentialsFromEncryptedData.java +++ b/apis/cloudstack/src/main/java/org/jclouds/cloudstack/functions/WindowsLoginCredentialsFromEncryptedData.java @@ -1,6 +1,5 @@ package org.jclouds.cloudstack.functions; -import java.nio.charset.Charset; import java.security.KeyFactory; import java.security.PrivateKey; import java.security.spec.KeySpec; @@ -14,6 +13,7 @@ import org.jclouds.domain.LoginCredentials; import org.jclouds.encryption.internal.Base64; import org.jclouds.javax.annotation.Nullable; +import com.google.common.base.Charsets; import com.google.common.base.Function; import com.google.common.base.Throwables; import com.google.inject.Inject; @@ -48,7 +48,7 @@ public class WindowsLoginCredentialsFromEncryptedData implements Function EMPTY_NETWORKS_MAP = Collections.emptyMap(); + private static final Map EMPTY_NETWORKS_MAP = ImmutableMap.of(); private static final String ZONE_ID = "2"; private final NetworkService firewallServiceWithStaticNat = NetworkService.builder().name("Firewall").capabilities(ImmutableMap.of("StaticNat", "true")).build(); diff --git a/apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/GlobalHostClientExpectTest.java b/apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/GlobalHostClientExpectTest.java index 26c96b0ac6..c7f4502381 100644 --- a/apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/GlobalHostClientExpectTest.java +++ b/apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/GlobalHostClientExpectTest.java @@ -21,7 +21,6 @@ package org.jclouds.cloudstack.features; import static org.testng.Assert.assertEquals; import java.util.Calendar; -import java.util.Collections; import java.util.Date; import java.util.Set; import java.util.TimeZone; @@ -65,7 +64,7 @@ public class GlobalHostClientExpectTest extends BaseCloudStackRestClientExpectTe Date lastPinged = makeDate(1970, Calendar.JANUARY, 16, 0, 54, 43, "GMT+02:00"); Date created = makeDate(2011, Calendar.NOVEMBER, 26, 23, 28, 36, "GMT+02:00"); - Host host1 = Host.builder().id("1").name("cs2-xevsrv.alucloud.local").state(Host.State.UP).type(Host.Type.ROUTING).ipAddress("10.26.26.107").zoneId("1").zoneName("Dev Zone 1").podId("1").podName("Dev Pod 1").version("2.2.12.20110928142833").hypervisor("XenServer").cpuNumber(24).cpuSpeed(2266).cpuAllocated("2.76%").cpuUsed("0.1%").cpuWithOverProvisioning(54384.0F).networkKbsRead(4443).networkKbsWrite(15048).memoryTotal(100549733760L).memoryAllocated(3623878656L).memoryUsed(3623878656L).capabilities("xen-3.0-x86_64 , xen-3.0-x86_32p , hvm-3.0-x86_32 , hvm-3.0-x86_32p , hvm-3.0-x86_64").lastPinged(lastPinged).managementServerId("223098941760041").clusterId("1").clusterName("Xen Clust 1").clusterType(Host.ClusterType.CLOUD_MANAGED).localStorageActive(false).created(created).events("PrepareUnmanaged; HypervisorVersionChanged; ManagementServerDown; PingTimeout; AgentDisconnected; MaintenanceRequested; HostDown; AgentConnected; StartAgentRebalance; ShutdownRequested; Ping").hostTags("").hasEnoughCapacity(false).allocationState(AllocationState.ENABLED).build(); + Host host1 = Host.builder().id("1").name("cs2-xevsrv.alucloud.local").state(Host.State.UP).type(Host.Type.ROUTING).ipAddress("10.26.26.107").zoneId("1").zoneName("Dev Zone 1").podId("1").podName("Dev Pod 1").version("2.2.12.20110928142833").hypervisor("XenServer").cpuNumber(24).cpuSpeed(2266).cpuAllocated("2.76%").cpuUsed("0.1%").cpuWithOverProvisioning(54384.0F).networkKbsRead(4443).networkKbsWrite(15048).memoryTotal(100549733760L).memoryAllocated(3623878656L).memoryUsed(3623878656L).capabilities("xen-3.0-x86_64 , xen-3.0-x86_32p , hvm-3.0-x86_32 , hvm-3.0-x86_32p , hvm-3.0-x86_64").lastPinged(lastPinged).managementServerId("223098941760041").clusterId("1").clusterName("Xen Clust 1").clusterType(Host.ClusterType.CLOUD_MANAGED).localStorageActive(false).created(created).events("PrepareUnmanaged; HypervisorVersionChanged; ManagementServerDown; PingTimeout; AgentDisconnected; MaintenanceRequested; HostDown; AgentConnected; StartAgentRebalance; ShutdownRequested; Ping").hasEnoughCapacity(false).allocationState(AllocationState.ENABLED).build(); Date disconnected = makeDate(2011, Calendar.NOVEMBER, 26, 23, 33, 38, "GMT+02:00"); lastPinged = makeDate(1970, Calendar.JANUARY, 16, 0, 42, 30, "GMT+02:00"); @@ -109,10 +108,10 @@ public class GlobalHostClientExpectTest extends BaseCloudStackRestClientExpectTe Date lastPinged = makeDate(1970, Calendar.JANUARY, 16, 0, 54, 43, "GMT+02:00"); Date created = makeDate(2011, Calendar.NOVEMBER, 26, 23, 28, 36, "GMT+02:00"); - Host expected = Host.builder().id("1").name("cs2-xevsrv.alucloud.local").state(Host.State.UP).type(Host.Type.ROUTING).ipAddress("10.26.26.107").zoneId("1").zoneName("Dev Zone 1").podId("1").podName("Dev Pod 1").version("2.2.12.20110928142833").hypervisor("XenServer").cpuNumber(24).cpuSpeed(2266).cpuAllocated("2.76%").cpuUsed("0.1%").cpuWithOverProvisioning(54384.0F).networkKbsRead(4443).networkKbsWrite(15048).memoryTotal(100549733760L).memoryAllocated(3623878656L).memoryUsed(3623878656L).capabilities("xen-3.0-x86_64 , xen-3.0-x86_32p , hvm-3.0-x86_32 , hvm-3.0-x86_32p , hvm-3.0-x86_64").lastPinged(lastPinged).managementServerId("223098941760041").clusterId("1").clusterName("Xen Clust 1").clusterType(Host.ClusterType.CLOUD_MANAGED).localStorageActive(false).created(created).events("PrepareUnmanaged; HypervisorVersionChanged; ManagementServerDown; PingTimeout; AgentDisconnected; MaintenanceRequested; HostDown; AgentConnected; StartAgentRebalance; ShutdownRequested; Ping").hostTags("").hasEnoughCapacity(false).allocationState(AllocationState.ENABLED).build(); + Host expected = Host.builder().id("1").name("cs2-xevsrv.alucloud.local").state(Host.State.UP).type(Host.Type.ROUTING).ipAddress("10.26.26.107").zoneId("1").zoneName("Dev Zone 1").podId("1").podName("Dev Pod 1").version("2.2.12.20110928142833").hypervisor("XenServer").cpuNumber(24).cpuSpeed(2266).cpuAllocated("2.76%").cpuUsed("0.1%").cpuWithOverProvisioning(54384.0F).networkKbsRead(4443).networkKbsWrite(15048).memoryTotal(100549733760L).memoryAllocated(3623878656L).memoryUsed(3623878656L).capabilities("xen-3.0-x86_64 , xen-3.0-x86_32p , hvm-3.0-x86_32 , hvm-3.0-x86_32p , hvm-3.0-x86_64").lastPinged(lastPinged).managementServerId("223098941760041").clusterId("1").clusterName("Xen Clust 1").clusterType(Host.ClusterType.CLOUD_MANAGED).localStorageActive(false).created(created).events("PrepareUnmanaged; HypervisorVersionChanged; ManagementServerDown; PingTimeout; AgentDisconnected; MaintenanceRequested; HostDown; AgentConnected; StartAgentRebalance; ShutdownRequested; Ping").hasEnoughCapacity(false).allocationState(AllocationState.ENABLED).build(); Host actual = requestSendsResponse(request, response).addHost("1", "http://example.com", "XenServer", "fred", "sekrit", - AddHostOptions.Builder.hostTags(Collections.emptySet()).allocationState(AllocationState.ENABLED).clusterId("1").clusterName("Xen Clust 1").podId("1")); + AddHostOptions.Builder.hostTags(ImmutableSet.of()).allocationState(AllocationState.ENABLED).clusterId("1").clusterName("Xen Clust 1").podId("1")); assertEquals(actual, expected); } @@ -129,9 +128,9 @@ public class GlobalHostClientExpectTest extends BaseCloudStackRestClientExpectTe Date lastPinged = makeDate(1970, Calendar.JANUARY, 16, 0, 54, 43, "GMT+02:00"); Date created = makeDate(2011, Calendar.NOVEMBER, 26, 23, 28, 36, "GMT+02:00"); - Host expected = Host.builder().id("1").name("cs2-xevsrv.alucloud.local").state(Host.State.UP).type(Host.Type.ROUTING).ipAddress("10.26.26.107").zoneId("1").zoneName("Dev Zone 1").podId("1").podName("Dev Pod 1").version("2.2.12.20110928142833").hypervisor("XenServer").cpuNumber(24).cpuSpeed(2266).cpuAllocated("2.76%").cpuUsed("0.1%").cpuWithOverProvisioning(54384.0F).networkKbsRead(4443).networkKbsWrite(15048).memoryTotal(100549733760L).memoryAllocated(3623878656L).memoryUsed(3623878656L).capabilities("xen-3.0-x86_64 , xen-3.0-x86_32p , hvm-3.0-x86_32 , hvm-3.0-x86_32p , hvm-3.0-x86_64").lastPinged(lastPinged).managementServerId("223098941760041").clusterId("1").clusterName("Xen Clust 1").clusterType(Host.ClusterType.CLOUD_MANAGED).localStorageActive(false).created(created).events("PrepareUnmanaged; HypervisorVersionChanged; ManagementServerDown; PingTimeout; AgentDisconnected; MaintenanceRequested; HostDown; AgentConnected; StartAgentRebalance; ShutdownRequested; Ping").hostTags("").hasEnoughCapacity(false).allocationState(AllocationState.ENABLED).build(); + Host expected = Host.builder().id("1").name("cs2-xevsrv.alucloud.local").state(Host.State.UP).type(Host.Type.ROUTING).ipAddress("10.26.26.107").zoneId("1").zoneName("Dev Zone 1").podId("1").podName("Dev Pod 1").version("2.2.12.20110928142833").hypervisor("XenServer").cpuNumber(24).cpuSpeed(2266).cpuAllocated("2.76%").cpuUsed("0.1%").cpuWithOverProvisioning(54384.0F).networkKbsRead(4443).networkKbsWrite(15048).memoryTotal(100549733760L).memoryAllocated(3623878656L).memoryUsed(3623878656L).capabilities("xen-3.0-x86_64 , xen-3.0-x86_32p , hvm-3.0-x86_32 , hvm-3.0-x86_32p , hvm-3.0-x86_64").lastPinged(lastPinged).managementServerId("223098941760041").clusterId("1").clusterName("Xen Clust 1").clusterType(Host.ClusterType.CLOUD_MANAGED).localStorageActive(false).created(created).events("PrepareUnmanaged; HypervisorVersionChanged; ManagementServerDown; PingTimeout; AgentDisconnected; MaintenanceRequested; HostDown; AgentConnected; StartAgentRebalance; ShutdownRequested; Ping").hasEnoughCapacity(false).allocationState(AllocationState.ENABLED).build(); - Host actual = requestSendsResponse(request, response).updateHost("1", UpdateHostOptions.Builder.allocationState(AllocationState.ENABLED).hostTags(Collections.emptySet()).osCategoryId("5")); + Host actual = requestSendsResponse(request, response).updateHost("1", UpdateHostOptions.Builder.allocationState(AllocationState.ENABLED).hostTags(ImmutableSet.of()).osCategoryId("5")); assertEquals(actual, expected); } diff --git a/apis/cloudstack/src/test/java/org/jclouds/cloudstack/parse/ListHostsResponseTest.java b/apis/cloudstack/src/test/java/org/jclouds/cloudstack/parse/ListHostsResponseTest.java index b857fd6e83..60f909659e 100644 --- a/apis/cloudstack/src/test/java/org/jclouds/cloudstack/parse/ListHostsResponseTest.java +++ b/apis/cloudstack/src/test/java/org/jclouds/cloudstack/parse/ListHostsResponseTest.java @@ -22,17 +22,16 @@ import static org.testng.Assert.assertEquals; import java.util.Set; +import org.jclouds.cloudstack.config.CloudStackParserModule; import org.jclouds.cloudstack.domain.AllocationState; import org.jclouds.cloudstack.domain.Host; import org.jclouds.date.internal.SimpleDateFormatDateService; import org.jclouds.json.BaseParserTest; -import org.jclouds.json.BaseSetParserTest; import org.jclouds.json.config.GsonModule; import org.jclouds.rest.annotations.SelectJson; import org.testng.annotations.Test; import com.google.common.collect.ImmutableSet; -import com.google.common.collect.ImmutableSortedSet; import com.google.inject.Guice; import com.google.inject.Injector; @@ -48,16 +47,7 @@ public class ListHostsResponseTest extends BaseParserTest, Set> @Override protected Injector injector() { - return Guice.createInjector(new GsonModule() { - - @Override - protected void configure() { - bind(DateAdapter.class).to(Iso8601DateAdapter.class); - super.configure(); - } - - }); - + return Guice.createInjector(new GsonModule(), new CloudStackParserModule()); } @Override @@ -102,7 +92,6 @@ public class ListHostsResponseTest extends BaseParserTest, Set> .created(new SimpleDateFormatDateService().iso8601SecondsDateParse("2011-11-26T23:28:36+0200")) .events("PrepareUnmanaged; HypervisorVersionChanged; ManagementServerDown; PingTimeout; " + "AgentDisconnected; MaintenanceRequested; HostDown; AgentConnected; StartAgentRebalance; ShutdownRequested; Ping") - .hostTags("") .hasEnoughCapacity(false) .allocationState(AllocationState.ENABLED).build(), diff --git a/apis/cloudstack/src/test/java/org/jclouds/cloudstack/parse/ListStoragePoolsResponseTest.java b/apis/cloudstack/src/test/java/org/jclouds/cloudstack/parse/ListStoragePoolsResponseTest.java index 2c4f85dcd4..661afca398 100644 --- a/apis/cloudstack/src/test/java/org/jclouds/cloudstack/parse/ListStoragePoolsResponseTest.java +++ b/apis/cloudstack/src/test/java/org/jclouds/cloudstack/parse/ListStoragePoolsResponseTest.java @@ -23,18 +23,22 @@ import java.util.Date; import java.util.Set; import java.util.TimeZone; +import org.jclouds.cloudstack.config.CloudStackParserModule; import org.jclouds.cloudstack.domain.StoragePool; import org.jclouds.json.BaseItemParserTest; +import org.jclouds.json.config.GsonModule; import org.jclouds.rest.annotations.SelectJson; import org.testng.annotations.Test; import com.google.common.collect.ImmutableSet; +import com.google.inject.Guice; +import com.google.inject.Injector; /** * * @author Richard Downer */ -@Test(groups = "unit") +@Test(groups = "unit", testName = "ListStoragePoolsResponseTest") public class ListStoragePoolsResponseTest extends BaseItemParserTest> { @Override @@ -54,7 +58,16 @@ public class ListStoragePoolsResponseTest extends BaseItemParserTest .templateId("0").id("203").startDate(start).endDate(end).build()); } - + @Override protected Injector injector() { - return Guice.createInjector(new GsonModule() { - - @Override - protected void configure() { - bind(DateAdapter.class).to(CloudStackDateAdapter.class); - super.configure(); - } - - }); + return Guice.createInjector(new GsonModule(), new CloudStackParserModule()); } + } diff --git a/apis/cloudstack/src/test/resources/liststoragepoolsresponse.json b/apis/cloudstack/src/test/resources/liststoragepoolsresponse.json index deca7a28c7..dc3ae46444 100644 --- a/apis/cloudstack/src/test/resources/liststoragepoolsresponse.json +++ b/apis/cloudstack/src/test/resources/liststoragepoolsresponse.json @@ -1 +1 @@ -{ "liststoragepoolsresponse" : { "count":1 ,"storagepool" : [ {"id":201,"zoneid":1,"zonename":"Dev Zone 1","podid":1,"podname":"Dev Pod 1","name":"NFS Pri 1","ipaddress":"10.26.26.165","path":"/mnt/nfs/cs_pri","created":"2011-11-26T23:33:06+0200","type":"NetworkFilesystem","clusterid":1,"clustername":"Xen Clust 1","disksizetotal":898356445184,"disksizeallocated":18276679680,"tags":"","state":"Up"} ] } } \ No newline at end of file +{ "liststoragepoolsresponse" : { "count":1 ,"storagepool" : [ {"id":201,"zoneid":1,"zonename":"Dev Zone 1","podid":1,"podname":"Dev Pod 1","name":"NFS Pri 1","ipaddress":"10.26.26.165","path":"/mnt/nfs/cs_pri","created":"2011-11-26T23:33:06+0200","type":"NetworkFilesystem","clusterid":1,"clustername":"Xen Clust 1","disksizetotal":898356445184,"disksizeallocated":18276679680,"tags":"tag1","state":"Up"} ] } } \ No newline at end of file diff --git a/apis/cloudwatch/pom.xml b/apis/cloudwatch/pom.xml index 7628283e0a..16fb1c5003 100644 --- a/apis/cloudwatch/pom.xml +++ b/apis/cloudwatch/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.api diff --git a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/binders/MetricDataBinder.java b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/binders/MetricDataBinder.java index 997f437b2f..38524189f2 100644 --- a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/binders/MetricDataBinder.java +++ b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/binders/MetricDataBinder.java @@ -93,8 +93,10 @@ public class MetricDataBinder implements org.jclouds.rest.Binder { formParameters.put("MetricData.member." + metricDatumIndex + ".Unit", String.valueOf(metricDatum.getUnit())); - formParameters.put("MetricData.member." + metricDatumIndex + ".Value", - String.valueOf(metricDatum.getValue())); + if (metricDatum.getValue().isPresent()) { + formParameters.put("MetricData.member." + metricDatumIndex + ".Value", + String.valueOf(metricDatum.getValue().get())); + } metricDatumIndex++; } diff --git a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/GetMetricStatisticsResponse.java b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/GetMetricStatisticsResponse.java index 146de9c569..d455908f39 100644 --- a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/GetMetricStatisticsResponse.java +++ b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/GetMetricStatisticsResponse.java @@ -18,12 +18,12 @@ */ package org.jclouds.cloudwatch.domain; -import java.util.Set; +import java.util.Iterator; import org.jclouds.javax.annotation.Nullable; import com.google.common.base.Objects; -import com.google.common.collect.ForwardingSet; +import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableSet; /** @@ -33,12 +33,12 @@ import com.google.common.collect.ImmutableSet; * * @author Jeremy Whitlock */ -public class GetMetricStatisticsResponse extends ForwardingSet { +public class GetMetricStatisticsResponse extends FluentIterable { - private final Set datapoints; + private final Iterable datapoints; private final String label; - public GetMetricStatisticsResponse(@Nullable Set datapoints, String label) { + public GetMetricStatisticsResponse(@Nullable Iterable datapoints, String label) { // Default to an empty set if (datapoints == null) { this.datapoints = ImmutableSet.of(); @@ -90,8 +90,8 @@ public class GetMetricStatisticsResponse extends ForwardingSet { } @Override - protected Set delegate() { - return datapoints; + public Iterator iterator() { + return datapoints.iterator(); } } diff --git a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/MetricDatum.java b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/MetricDatum.java index 2bd2d1385e..23745a9eb4 100644 --- a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/MetricDatum.java +++ b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/domain/MetricDatum.java @@ -25,14 +25,16 @@ import java.util.Date; import java.util.Set; import com.google.common.base.Objects; -import com.google.common.base.Optional; import com.google.common.base.Objects.ToStringHelper; +import com.google.common.base.Optional; +import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Sets; /** - * @see - * + * @see + * * @author Jeremy Whitlock */ public class MetricDatum { @@ -42,17 +44,17 @@ public class MetricDatum { private final Optional statisticValues; private final Optional timestamp; private final Unit unit; - private final double value; + private final Optional value; /** * Private constructor to enforce using {@link Builder}. */ - protected MetricDatum(Set dimensions, String metricName, StatisticValues statisticValues, Date timestamp, - Unit unit, double value) { - this.dimensions = ImmutableSet.copyOf(checkNotNull(dimensions, "dimensions")); + protected MetricDatum(Iterable dimensions, String metricName, Optional statisticValues, + Optional timestamp, Unit unit, Optional value) { + this.dimensions = ImmutableSet. copyOf(checkNotNull(dimensions, "dimensions")); this.metricName = checkNotNull(metricName, "metricName"); - this.statisticValues = Optional.fromNullable(statisticValues); - this.timestamp = Optional.fromNullable(timestamp); + this.statisticValues = checkNotNull(statisticValues, "statisticValues"); + this.timestamp = checkNotNull(timestamp, "timestamp"); this.unit = checkNotNull(unit, "unit"); this.value = checkNotNull(value, "value"); } @@ -95,13 +97,13 @@ public class MetricDatum { /** * return the actual value of the metric */ - public double getValue() { + public Optional getValue() { return value; } /** - * Returns a new builder. The generated builder is equivalent to the builder - * created by the {@link Builder} constructor. + * Returns a new builder. The generated builder is equivalent to the builder created by the + * {@link Builder} constructor. */ public static Builder builder() { return new Builder(); @@ -110,36 +112,39 @@ public class MetricDatum { public static class Builder { // this builder is set to be additive on dimension calls, so make this mutable - private Set dimensions = Sets.newLinkedHashSet(); + private ImmutableList.Builder dimensions = ImmutableList. builder(); private String metricName; - private StatisticValues statisticValues; - private Date timestamp; + private Optional statisticValues = Optional.absent(); + private Optional timestamp = Optional.absent(); private Unit unit = Unit.NONE; - private double value; + private Optional value = Optional.absent(); /** - * Creates a new builder. The returned builder is equivalent to the builder - * generated by {@link org.jclouds.cloudwatch.domain.MetricDatum#builder}. + * Creates a new builder. The returned builder is equivalent to the builder generated by + * {@link org.jclouds.cloudwatch.domain.MetricDatum#builder}. */ - public Builder() {} + public Builder() { + } /** * A list of dimensions describing qualities of the metric. - * - * @param dimensions the dimensions describing the qualities of the metric - * + * + * @param dimensions + * the dimensions describing the qualities of the metric + * * @return this {@code Builder} object */ - public Builder dimensions(Set dimensions) { + public Builder dimensions(Iterable dimensions) { this.dimensions.addAll(checkNotNull(dimensions, "dimensions")); return this; } /** * A dimension describing qualities of the metric. - * - * @param dimension the dimension describing the qualities of the metric - * + * + * @param dimension + * the dimension describing the qualities of the metric + * * @return this {@code Builder} object */ public Builder dimension(Dimension dimension) { @@ -149,9 +154,10 @@ public class MetricDatum { /** * The name of the metric. - * - * @param metricName the metric name - * + * + * @param metricName + * the metric name + * * @return this {@code Builder} object */ public Builder metricName(String metricName) { @@ -161,34 +167,37 @@ public class MetricDatum { /** * The object describing the set of statistical values describing the metric. - * - * @param statisticValues the object describing the set of statistical values for the metric - * + * + * @param statisticValues + * the object describing the set of statistical values for the metric + * * @return this {@code Builder} object */ public Builder statisticValues(StatisticValues statisticValues) { - this.statisticValues = statisticValues; + this.statisticValues = Optional.fromNullable(statisticValues); return this; } /** - * The time stamp used for the metric. If not specified, the default value is set to the time the metric data was - * received. - * - * @param timestamp the time stamp used for the metric - * + * The time stamp used for the metric. If not specified, the default value is set to the time + * the metric data was received. + * + * @param timestamp + * the time stamp used for the metric + * * @return this {@code Builder} object */ public Builder timestamp(Date timestamp) { - this.timestamp = timestamp; + this.timestamp = Optional.fromNullable(timestamp); return this; } /** * The unit for the metric. - * - * @param unit the unit for the metric - * + * + * @param unit + * the unit for the metric + * * @return this {@code Builder} object */ public Builder unit(Unit unit) { @@ -198,13 +207,14 @@ public class MetricDatum { /** * The value for the metric. - * - * @param value the value for the metric - * + * + * @param value + * the value for the metric + * * @return this {@code Builder} object */ - public Builder value(double value) { - this.value = value; + public Builder value(Double value) { + this.value = Optional.fromNullable(value); return this; } @@ -212,7 +222,7 @@ public class MetricDatum { * Returns a newly-created {@code MetricDatum} based on the contents of the {@code Builder}. */ public MetricDatum build() { - return new MetricDatum(dimensions, metricName, statisticValues, timestamp, unit, value); + return new MetricDatum(dimensions.build(), metricName, statisticValues, timestamp, unit, value); } } @@ -240,7 +250,8 @@ public class MetricDatum { } protected ToStringHelper string() { - return Objects.toStringHelper("").add("dimensions", dimensions).add("metricName", metricName).add( - "statisticValues", statisticValues).add("timestamp", timestamp).add("unit", unit).add("value", value); + return Objects.toStringHelper("").omitNullValues().add("dimensions", dimensions).add("metricName", metricName) + .add("statisticValues", statisticValues.orNull()).add("timestamp", timestamp.orNull()).add("unit", unit) + .add("value", value.orNull()); } } diff --git a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/features/MetricApi.java b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/features/MetricApi.java index 9e5deabc37..a573656440 100644 --- a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/features/MetricApi.java +++ b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/features/MetricApi.java @@ -34,6 +34,7 @@ import org.jclouds.concurrent.Timeout; * Provides access to Amazon CloudWatch via the Query API *

* + * @see MetricAsyncApi * @see * @author Jeremy Whitlock */ diff --git a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/features/MetricAsyncApi.java b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/features/MetricAsyncApi.java index 3e739b5234..3e813809db 100644 --- a/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/features/MetricAsyncApi.java +++ b/apis/cloudwatch/src/main/java/org/jclouds/cloudwatch/features/MetricAsyncApi.java @@ -37,11 +37,14 @@ import org.jclouds.cloudwatch.xml.ListMetricsResponseHandler; import org.jclouds.collect.IterableWithMarker; import org.jclouds.collect.PagedIterable; import org.jclouds.rest.annotations.BinderParam; +import org.jclouds.rest.annotations.ExceptionParser; import org.jclouds.rest.annotations.FormParams; import org.jclouds.rest.annotations.RequestFilters; import org.jclouds.rest.annotations.Transform; import org.jclouds.rest.annotations.VirtualHost; import org.jclouds.rest.annotations.XMLResponseParser; +import org.jclouds.rest.functions.ReturnEmptyIterableWithMarkerOnNotFoundOr404; +import org.jclouds.rest.functions.ReturnEmptyPagedIterableOnNotFoundOr404; import com.google.common.util.concurrent.ListenableFuture; @@ -64,6 +67,7 @@ public interface MetricAsyncApi { @XMLResponseParser(ListMetricsResponseHandler.class) @Transform(MetricsToPagedIterable.class) @FormParams(keys = "Action", values = "ListMetrics") + @ExceptionParser(ReturnEmptyPagedIterableOnNotFoundOr404.class) ListenableFuture> list(); /** @@ -73,6 +77,7 @@ public interface MetricAsyncApi { @Path("/") @XMLResponseParser(ListMetricsResponseHandler.class) @FormParams(keys = "Action", values = "ListMetrics") + @ExceptionParser(ReturnEmptyIterableWithMarkerOnNotFoundOr404.class) ListenableFuture> list(ListMetricsOptions options); /** diff --git a/apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/binders/MetricDataBinderTest.java b/apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/binders/MetricDataBinderTest.java index 94dcac48f6..003fb90274 100644 --- a/apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/binders/MetricDataBinderTest.java +++ b/apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/binders/MetricDataBinderTest.java @@ -60,7 +60,6 @@ public class MetricDataBinderTest { .statisticValues(ss) .dimension(new Dimension("TestDimension", "FAKE")) .unit(Unit.COUNT) - .value(2) .build(); HttpRequest request = binder.bindToRequest(request(), ImmutableSet.of(metricDatum)); @@ -73,8 +72,7 @@ public class MetricDataBinderTest { "&MetricData.member.1.StatisticValues.Minimum=1.0" + "&MetricData.member.1.StatisticValues.SampleCount=4.0" + "&MetricData.member.1.StatisticValues.Sum=10.0" + - "&MetricData.member.1.Unit=" + Unit.COUNT.toString() + - "&MetricData.member.1.Value=2.0"); + "&MetricData.member.1.Unit=" + Unit.COUNT.toString()); } public void testMetricWithMultipleDimensions() throws Exception { diff --git a/apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/features/MetricApiExpectTest.java b/apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/features/MetricApiExpectTest.java index 25cae952fe..90ff95865c 100644 --- a/apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/features/MetricApiExpectTest.java +++ b/apis/cloudwatch/src/test/java/org/jclouds/cloudwatch/features/MetricApiExpectTest.java @@ -33,6 +33,7 @@ import org.jclouds.cloudwatch.domain.Unit; import org.jclouds.cloudwatch.internal.BaseCloudWatchApiExpectTest; import org.jclouds.cloudwatch.options.GetMetricStatisticsOptions; import org.jclouds.cloudwatch.options.ListMetricsOptions; +import org.jclouds.collect.IterableWithMarkers; import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpResponse; import org.jclouds.rest.ResourceNotFoundException; @@ -76,8 +77,6 @@ public class MetricApiExpectTest extends BaseCloudWatchApiExpectTest { "[Metric{namespace=AWS/EC2, metricName=CPUUtilization, dimension=[Dimension{name=InstanceId, value=i-689fcf0f}]}]"); } - // TODO: this should really be an empty set - @Test(expectedExceptions = ResourceNotFoundException.class) public void testListMetricsWhenResponseIs404() throws Exception { HttpResponse listMetricsResponse = HttpResponse.builder().statusCode(404).build(); @@ -85,7 +84,7 @@ public class MetricApiExpectTest extends BaseCloudWatchApiExpectTest { CloudWatchApi apiWhenMetricsDontExist = requestSendsResponse( listMetrics, listMetricsResponse); - apiWhenMetricsDontExist.getMetricApiForRegion(null).list().get(0); + assertEquals(apiWhenMetricsDontExist.getMetricApiForRegion(null).list().get(0), IterableWithMarkers.EMPTY); } public void testListMetrics2PagesWhenResponseIs2xx() throws Exception { diff --git a/apis/deltacloud/pom.xml b/apis/deltacloud/pom.xml index bfef9b8b6b..9470789a81 100644 --- a/apis/deltacloud/pom.xml +++ b/apis/deltacloud/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.api diff --git a/apis/deltacloud/src/test/java/org/jclouds/deltacloud/options/CreateInstanceOptionsTest.java b/apis/deltacloud/src/test/java/org/jclouds/deltacloud/options/CreateInstanceOptionsTest.java index dc8402ca28..3f6c359ac8 100644 --- a/apis/deltacloud/src/test/java/org/jclouds/deltacloud/options/CreateInstanceOptionsTest.java +++ b/apis/deltacloud/src/test/java/org/jclouds/deltacloud/options/CreateInstanceOptionsTest.java @@ -21,7 +21,7 @@ package org.jclouds.deltacloud.options; import static org.jclouds.deltacloud.options.CreateInstanceOptions.Builder.named; import static org.testng.Assert.assertEquals; -import java.util.Collections; +import com.google.common.collect.ImmutableList; import org.jclouds.http.options.HttpRequestOptions; import org.testng.annotations.Test; @@ -43,19 +43,19 @@ public class CreateInstanceOptionsTest { public void testWithNamed() { CreateInstanceOptions options = new CreateInstanceOptions(); options.named("test"); - assertEquals(options.buildFormParameters().get("name"), Collections.singletonList("test")); + assertEquals(options.buildFormParameters().get("name"), ImmutableList.of("test")); } @Test public void testNullWithNamed() { CreateInstanceOptions options = new CreateInstanceOptions(); - assertEquals(options.buildFormParameters().get("name"), Collections.EMPTY_LIST); + assertEquals(options.buildFormParameters().get("name"), ImmutableList.of()); } @Test public void testWithNamedStatic() { CreateInstanceOptions options = named("test"); - assertEquals(options.buildFormParameters().get("name"), Collections.singletonList("test")); + assertEquals(options.buildFormParameters().get("name"), ImmutableList.of("test")); } @Test(expectedExceptions = NullPointerException.class) diff --git a/apis/ec2/pom.xml b/apis/ec2/pom.xml index 4b8eb5bfa1..8e9463c262 100644 --- a/apis/ec2/pom.xml +++ b/apis/ec2/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.api diff --git a/apis/ec2/src/main/java/org/jclouds/ec2/compute/functions/RunningInstanceToNodeMetadata.java b/apis/ec2/src/main/java/org/jclouds/ec2/compute/functions/RunningInstanceToNodeMetadata.java index 731999357f..a134ec036e 100644 --- a/apis/ec2/src/main/java/org/jclouds/ec2/compute/functions/RunningInstanceToNodeMetadata.java +++ b/apis/ec2/src/main/java/org/jclouds/ec2/compute/functions/RunningInstanceToNodeMetadata.java @@ -196,7 +196,7 @@ public class RunningInstanceToNodeMetadata implements Function> { public Set get() { if (amiOwners.length == 0) { logger.debug(">> no owners specified, skipping image parsing"); - return Collections.emptySet(); + return ImmutableSet.of(); } else { logger.debug(">> providing images"); diff --git a/apis/ec2/src/main/java/org/jclouds/ec2/domain/Attachment.java b/apis/ec2/src/main/java/org/jclouds/ec2/domain/Attachment.java index 0f1e79bc89..73a6fee3b4 100644 --- a/apis/ec2/src/main/java/org/jclouds/ec2/domain/Attachment.java +++ b/apis/ec2/src/main/java/org/jclouds/ec2/domain/Attachment.java @@ -114,8 +114,12 @@ public class Attachment implements Comparable { } /** - * Snapshots are tied to Regions and can only be used for volumes within the same Region. + * To be removed in jclouds 1.6

Warning

+ * + * Especially on EC2 clones that may not support regions, this value is fragile. Consider + * alternate means to determine context. */ + @Deprecated public String getRegion() { return region; } diff --git a/apis/ec2/src/main/java/org/jclouds/ec2/domain/BundleTask.java b/apis/ec2/src/main/java/org/jclouds/ec2/domain/BundleTask.java index 235004493d..9ec3bbd2e5 100644 --- a/apis/ec2/src/main/java/org/jclouds/ec2/domain/BundleTask.java +++ b/apis/ec2/src/main/java/org/jclouds/ec2/domain/BundleTask.java @@ -209,9 +209,12 @@ public class BundleTask implements Comparable { } /** + * To be removed in jclouds 1.6

Warning

* - * @return region of the bundle task + * Especially on EC2 clones that may not support regions, this value is fragile. Consider + * alternate means to determine context. */ + @Deprecated public String getRegion() { return region; } diff --git a/apis/ec2/src/main/java/org/jclouds/ec2/domain/Image.java b/apis/ec2/src/main/java/org/jclouds/ec2/domain/Image.java index 99bb4ae5e6..1c50e637e1 100644 --- a/apis/ec2/src/main/java/org/jclouds/ec2/domain/Image.java +++ b/apis/ec2/src/main/java/org/jclouds/ec2/domain/Image.java @@ -219,9 +219,12 @@ public class Image implements Comparable { } /** - * AMIs are tied to the Region where its files are located within Amazon S3. + * To be removed in jclouds 1.6

Warning

* + * Especially on EC2 clones that may not support regions, this value is fragile. Consider + * alternate means to determine context. */ + @Deprecated public String getRegion() { return region; } diff --git a/apis/ec2/src/main/java/org/jclouds/ec2/domain/InstanceStateChange.java b/apis/ec2/src/main/java/org/jclouds/ec2/domain/InstanceStateChange.java index 3f0518769a..ab38a4b5f1 100644 --- a/apis/ec2/src/main/java/org/jclouds/ec2/domain/InstanceStateChange.java +++ b/apis/ec2/src/main/java/org/jclouds/ec2/domain/InstanceStateChange.java @@ -47,8 +47,12 @@ public class InstanceStateChange implements Comparable { } /** - * Instances are tied to Availability Zones. However, the instance ID is tied to the Region. + * To be removed in jclouds 1.6

Warning

+ * + * Especially on EC2 clones that may not support regions, this value is fragile. Consider + * alternate means to determine context. */ + @Deprecated public String getRegion() { return region; } diff --git a/apis/ec2/src/main/java/org/jclouds/ec2/domain/IpPermission.java b/apis/ec2/src/main/java/org/jclouds/ec2/domain/IpPermission.java index 722313161c..69bb6a7ad3 100644 --- a/apis/ec2/src/main/java/org/jclouds/ec2/domain/IpPermission.java +++ b/apis/ec2/src/main/java/org/jclouds/ec2/domain/IpPermission.java @@ -18,49 +18,174 @@ */ package org.jclouds.ec2.domain; +import static com.google.common.base.Preconditions.checkNotNull; + import java.util.Set; +import com.google.common.base.Objects; +import com.google.common.collect.ImmutableMultimap; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Iterables; +import com.google.common.collect.LinkedHashMultimap; import com.google.common.collect.Multimap; +import com.google.common.collect.Sets; /** - * + * * @see
* @author Adrian Cole */ -public interface IpPermission extends Comparable { +public class IpPermission { + public static Builder builder() { + return new Builder(); + } + + public static class Builder { + private int fromPort; + private int toPort; + private IpProtocol ipProtocol; + private Multimap userIdGroupPairs = LinkedHashMultimap.create(); + private Set groupIds = Sets.newLinkedHashSet(); + private Set ipRanges = Sets.newLinkedHashSet(); + + public Builder fromPort(int fromPort) { + this.fromPort = fromPort; + return this; + } + + public Builder toPort(int toPort) { + this.toPort = toPort; + return this; + } + + public Builder ipProtocol(IpProtocol ipProtocol) { + this.ipProtocol = checkNotNull(ipProtocol, "ipProtocol"); + return this; + } + + public Builder userIdGroupPair(String userId, String groupNameOrId) { + this.userIdGroupPairs.put(checkNotNull(userId, "userId"), checkNotNull(groupNameOrId, "groupNameOrId of %s", userId)); + return this; + } + + public Builder userIdGroupPairs(Multimap userIdGroupPairs) { + this.userIdGroupPairs.putAll(checkNotNull(userIdGroupPairs, "userIdGroupPairs")); + return this; + } + + public Builder ipRange(String ipRange) { + this.ipRanges.add(ipRange); + return this; + } + + public Builder ipRanges(Iterable ipRanges) { + Iterables.addAll(this.ipRanges, checkNotNull(ipRanges, "ipRanges")); + return this; + } + + public Builder groupId(String groupId) { + this.groupIds.add(checkNotNull(groupId, "groupId")); + return this; + } + + public Builder groupIds(Iterable groupIds) { + Iterables.addAll(this.groupIds, checkNotNull(groupIds, "groupIds")); + return this; + } + + public IpPermission build() { + return new IpPermission(ipProtocol, fromPort, toPort, userIdGroupPairs, groupIds, ipRanges); + } + } + + private final int fromPort; + private final int toPort; + private final Multimap userIdGroupPairs; + private final Set groupIds; + private final IpProtocol ipProtocol; + private final Set ipRanges; + + public IpPermission(IpProtocol ipProtocol, int fromPort, int toPort, Multimap userIdGroupPairs, + Iterable groupIds, Iterable ipRanges) { + this.fromPort = fromPort; + this.toPort = toPort; + this.userIdGroupPairs = ImmutableMultimap.copyOf(checkNotNull(userIdGroupPairs, "userIdGroupPairs")); + this.ipProtocol = checkNotNull(ipProtocol, "ipProtocol"); + this.groupIds = ImmutableSet.copyOf(checkNotNull(groupIds, "groupIds")); + this.ipRanges = ImmutableSet.copyOf(checkNotNull(ipRanges, "ipRanges")); + } /** * Start of port range for the TCP and UDP protocols, or an ICMP type number. * An ICMP type number of -1 indicates a wildcard (i.e., any ICMP type * number). */ - int getFromPort(); + public int getFromPort() { + return fromPort; + } /** * End of port range for the TCP and UDP protocols, or an ICMP code. An ICMP * code of -1 indicates a wildcard (i.e., any ICMP code). */ - int getToPort(); + public int getToPort() { + return toPort; + } /** * List of security group and user ID pairs. */ - Multimap getUserIdGroupPairs(); + public Multimap getUserIdGroupPairs() { + return userIdGroupPairs; + } /** * List of security group Ids */ - Set getGroupIds(); + public Set getGroupIds() { + return groupIds; + } /** * IP protocol */ - IpProtocol getIpProtocol(); + public IpProtocol getIpProtocol() { + return ipProtocol; + } /** * IP ranges. */ - Set getIpRanges(); + public Set getIpRanges() { + return ipRanges; + } + + @Override + public int hashCode() { + return Objects.hashCode(fromPort, toPort, groupIds, ipProtocol, ipRanges, userIdGroupPairs); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null || getClass() != obj.getClass()) + return false; + IpPermission that = IpPermission.class.cast(obj); + return Objects.equal(this.fromPort, that.fromPort) && Objects.equal(this.toPort, that.toPort) + && Objects.equal(this.groupIds, that.groupIds) && Objects.equal(this.ipProtocol, that.ipProtocol) + && Objects.equal(this.ipRanges, that.ipRanges) + && Objects.equal(this.userIdGroupPairs, that.userIdGroupPairs); + } + + @Override + public String toString() { + return Objects.toStringHelper(this).omitNullValues().add("fromPort", fromPort == -1 ? null : fromPort) + .add("toPort", toPort == -1 ? null : toPort).add("groupIds", groupIds.size() == 0 ? null : groupIds) + .add("ipProtocol", ipProtocol).add("ipRanges", ipRanges.size() == 0 ? null : ipRanges) + .add("userIdGroupPairs", userIdGroupPairs.size() == 0 ? null : userIdGroupPairs).toString(); + } + } \ No newline at end of file diff --git a/apis/ec2/src/main/java/org/jclouds/ec2/domain/IpPermissionImpl.java b/apis/ec2/src/main/java/org/jclouds/ec2/domain/IpPermissionImpl.java deleted file mode 100644 index fe801981ee..0000000000 --- a/apis/ec2/src/main/java/org/jclouds/ec2/domain/IpPermissionImpl.java +++ /dev/null @@ -1,226 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.ec2.domain; - -import static com.google.common.base.Preconditions.checkNotNull; - -import java.util.Set; - -import com.google.common.collect.ImmutableMultimap; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Iterables; -import com.google.common.collect.LinkedHashMultimap; -import com.google.common.collect.Multimap; -import com.google.common.collect.Sets; - -/** - * - * @see - * @author Adrian Cole - */ -public class IpPermissionImpl implements IpPermission { - public static Builder builder() { - return new Builder(); - } - - public static class Builder { - private int fromPort; - private int toPort; - private IpProtocol ipProtocol; - private Multimap userIdGroupPairs = LinkedHashMultimap.create(); - private Set groupIds = Sets.newLinkedHashSet(); - private Set ipRanges = Sets.newLinkedHashSet(); - - public Builder fromPort(int fromPort) { - this.fromPort = fromPort; - return this; - } - - public Builder toPort(int toPort) { - this.fromPort = toPort; - return this; - } - - public Builder ipProtocol(IpProtocol ipProtocol) { - this.ipProtocol = ipProtocol; - return this; - } - - public Builder userIdGroupPair(String userId, String groupNameOrId) { - this.userIdGroupPairs.put(userId, groupNameOrId); - return this; - } - - public Builder userIdGroupPairs(Multimap userIdGroupPairs) { - this.userIdGroupPairs.putAll(userIdGroupPairs); - return this; - } - - public Builder ipRange(String ipRange) { - this.ipRanges.add(ipRange); - return this; - } - - public Builder ipRanges(Iterable ipRanges) { - Iterables.addAll(this.ipRanges, ipRanges); - return this; - } - - public Builder groupId(String groupId) { - this.groupIds.add(groupId); - return this; - } - - public Builder groupIds(Iterable groupIds) { - Iterables.addAll(this.groupIds, groupIds); - return this; - } - - public IpPermission build() { - return new IpPermissionImpl(ipProtocol, fromPort, toPort, userIdGroupPairs, groupIds, ipRanges); - } - } - - private final int fromPort; - private final int toPort; - private final Multimap userIdGroupPairs; - private final Set groupIds; - private final IpProtocol ipProtocol; - private final Set ipRanges; - - public IpPermissionImpl(IpProtocol ipProtocol, int fromPort, int toPort, - Multimap userIdGroupPairs, Iterable groupIds, Iterable ipRanges) { - this.fromPort = fromPort; - this.toPort = toPort; - this.userIdGroupPairs = ImmutableMultimap.copyOf(checkNotNull(userIdGroupPairs, "userIdGroupPairs")); - this.ipProtocol = checkNotNull(ipProtocol, "ipProtocol"); - this.groupIds = ImmutableSet.copyOf(checkNotNull(groupIds, "groupIds")); - this.ipRanges = ImmutableSet.copyOf(checkNotNull(ipRanges, "ipRanges")); - } - - /** - * {@inheritDoc} - */ - public int compareTo(IpPermission o) { - return (this == o) ? 0 : getIpProtocol().compareTo(o.getIpProtocol()); - } - - /** - * {@inheritDoc} - */ - @Override - public int getFromPort() { - return fromPort; - } - - /** - * {@inheritDoc} - */ - @Override - public int getToPort() { - return toPort; - } - - /** - * {@inheritDoc} - */ - @Override - public Multimap getUserIdGroupPairs() { - return userIdGroupPairs; - } - - /** - * {@inheritDoc} - */ - @Override - public Set getGroupIds() { - return groupIds; - } - - /** - * {@inheritDoc} - */ - @Override - public IpProtocol getIpProtocol() { - return ipProtocol; - } - - /** - * {@inheritDoc} - */ - @Override - public Set getIpRanges() { - return ipRanges; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + fromPort; - result = prime * result + ((groupIds == null) ? 0 : groupIds.hashCode()); - result = prime * result + ((ipProtocol == null) ? 0 : ipProtocol.hashCode()); - result = prime * result + ((ipRanges == null) ? 0 : ipRanges.hashCode()); - result = prime * result + toPort; - result = prime * result + ((userIdGroupPairs == null) ? 0 : userIdGroupPairs.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - IpPermissionImpl other = (IpPermissionImpl) obj; - if (fromPort != other.fromPort) - return false; - if (groupIds == null) { - if (other.groupIds != null) - return false; - } else if (!groupIds.equals(other.groupIds)) - return false; - if (ipProtocol != other.ipProtocol) - return false; - if (ipRanges == null) { - if (other.ipRanges != null) - return false; - } else if (!ipRanges.equals(other.ipRanges)) - return false; - if (toPort != other.toPort) - return false; - if (userIdGroupPairs == null) { - if (other.userIdGroupPairs != null) - return false; - } else if (!userIdGroupPairs.equals(other.userIdGroupPairs)) - return false; - return true; - } - - @Override - public String toString() { - return "[fromPort=" + fromPort + ", toPort=" + toPort + ", userIdGroupPairs=" + userIdGroupPairs + ", groupIds=" - + groupIds + ", ipProtocol=" + ipProtocol + ", ipRanges=" + ipRanges + "]"; - } - -} diff --git a/apis/ec2/src/main/java/org/jclouds/ec2/domain/KeyPair.java b/apis/ec2/src/main/java/org/jclouds/ec2/domain/KeyPair.java index ead73cb9e3..bd927a3893 100644 --- a/apis/ec2/src/main/java/org/jclouds/ec2/domain/KeyPair.java +++ b/apis/ec2/src/main/java/org/jclouds/ec2/domain/KeyPair.java @@ -103,8 +103,12 @@ public class KeyPair implements Comparable { } /** - * Key pairs (to connect to instances) are Region-specific. + * To be removed in jclouds 1.6

Warning

+ * + * Especially on EC2 clones that may not support regions, this value is fragile. Consider + * alternate means to determine context. */ + @Deprecated public String getRegion() { return region; } diff --git a/apis/ec2/src/main/java/org/jclouds/ec2/domain/PublicIpInstanceIdPair.java b/apis/ec2/src/main/java/org/jclouds/ec2/domain/PublicIpInstanceIdPair.java index 8f03cab684..189fe7c92f 100644 --- a/apis/ec2/src/main/java/org/jclouds/ec2/domain/PublicIpInstanceIdPair.java +++ b/apis/ec2/src/main/java/org/jclouds/ec2/domain/PublicIpInstanceIdPair.java @@ -42,8 +42,12 @@ public class PublicIpInstanceIdPair implements ComparableWarning + * + * Especially on EC2 clones that may not support regions, this value is fragile. Consider + * alternate means to determine context. */ + @Deprecated public String getRegion() { return region; } diff --git a/apis/ec2/src/main/java/org/jclouds/ec2/domain/Reservation.java b/apis/ec2/src/main/java/org/jclouds/ec2/domain/Reservation.java index 48f6d06190..5a621b290d 100644 --- a/apis/ec2/src/main/java/org/jclouds/ec2/domain/Reservation.java +++ b/apis/ec2/src/main/java/org/jclouds/ec2/domain/Reservation.java @@ -20,27 +20,119 @@ package org.jclouds.ec2.domain; import static com.google.common.base.Preconditions.checkNotNull; -import java.util.LinkedHashSet; import java.util.Set; import org.jclouds.javax.annotation.Nullable; -import com.google.common.collect.Iterables; -import com.google.common.collect.Sets; +import com.google.common.base.Objects; +import com.google.common.collect.ComparisonChain; +import com.google.common.collect.ForwardingSet; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Ordering; /** * - * @see
* @author Adrian Cole */ -public class Reservation extends LinkedHashSet implements Comparable>, - Set { +public class Reservation extends ForwardingSet implements Comparable>{ + + public static Builder builder() { + return new Builder(); + } + + public Builder toBuilder() { + return Reservation. builder().fromReservation(this); + } + + public static class Builder { + private String region; + private String ownerId; + private String requesterId; + private String reservationId; + + private ImmutableSet.Builder instances = ImmutableSet. builder(); + private ImmutableSet.Builder groupNames = ImmutableSet. builder(); + + /** + * @see Reservation#getRegion() + */ + public Builder region(String region) { + this.region = region; + return this; + } + + /** + * @see Reservation#getOwnerId() + */ + public Builder ownerId(String ownerId) { + this.ownerId = ownerId; + return this; + } + + /** + * @see Reservation#getRequesterId() + */ + public Builder requesterId(String requesterId) { + this.requesterId = requesterId; + return this; + } + + /** + * @see Reservation#getReservationId() + */ + public Builder reservationId(String reservationId) { + this.reservationId = reservationId; + return this; + } + + /** + * @see Reservation#iterator + */ + public Builder instance(T instance) { + this.instances.add(checkNotNull(instance, "instance")); + return this; + } + + /** + * @see Reservation#iterator + */ + public Builder instances(Set instances) { + this.instances.addAll(checkNotNull(instances, "instances")); + return this; + } + + /** + * @see Reservation#getGroupNames() + */ + public Builder groupName(String groupName) { + this.groupNames.add(checkNotNull(groupName, "groupName")); + return this; + } + + /** + * @see Reservation#getGroupNames() + */ + public Builder groupNames(Iterable groupNames) { + this.groupNames = ImmutableSet. builder().addAll(checkNotNull(groupNames, "groupNames")); + return this; + } + + public Reservation build() { + return new Reservation(region, groupNames.build(), instances.build(), ownerId, requesterId, reservationId); + } + + public Builder fromReservation(Reservation in) { + return region(in.region).ownerId(in.ownerId).requesterId(in.requesterId).reservationId(in.reservationId) + .instances(in).groupNames(in.groupNames); + } + } - /** The serialVersionUID */ - private static final long serialVersionUID = -9051777593518861395L; private final String region; - private final Set groupIds = Sets.newLinkedHashSet(); + private final ImmutableSet groupNames; + private final ImmutableSet instances; @Nullable private final String ownerId; @Nullable @@ -48,32 +140,45 @@ public class Reservation extends LinkedHashSet imp @Nullable private final String reservationId; - public Reservation(String region, Iterable groupIds, Iterable instances, @Nullable String ownerId, + public Reservation(String region, Iterable groupNames, Iterable instances, @Nullable String ownerId, @Nullable String requesterId, @Nullable String reservationId) { this.region = checkNotNull(region, "region"); - Iterables.addAll(this.groupIds, checkNotNull(groupIds, "groupIds")); - Iterables.addAll(this, checkNotNull(instances, "instances")); + this.groupNames = ImmutableSet.copyOf(checkNotNull(groupNames, "groupNames")); + this.instances = ImmutableSet.copyOf(checkNotNull(instances, "instances")); this.ownerId = ownerId; this.requesterId = requesterId; this.reservationId = reservationId; } + @Override + protected Set delegate() { + return instances; + } + /** - * Instances are tied to Availability Zones. However, the instance ID is tied to the Region. + * To be removed in jclouds 1.6

Warning

+ * + * Especially on EC2 clones that may not support regions, this value is fragile. Consider + * alternate means to determine context. */ + @Deprecated public String getRegion() { return region; } - public int compareTo(Reservation o) { - return (this == o) ? 0 : getReservationId().compareTo(o.getReservationId()); + /** + * @see #getGroupNames() + */ + @Deprecated + public Set getGroupIds() { + return groupNames; } - + /** * Names of the security groups. */ - public Set getGroupIds() { - return groupIds; + public Set getGroupNames() { + return groupNames; } /** @@ -84,7 +189,8 @@ public class Reservation extends LinkedHashSet imp } /** - * ID of the requester. + * The ID of the requester that launched the instances on your behalf (for example, AWS + * Management Console or Auto Scaling). */ public String getRequesterId() { return requesterId; @@ -99,51 +205,34 @@ public class Reservation extends LinkedHashSet imp @Override public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + ((groupIds == null) ? 0 : groupIds.hashCode()); - result = prime * result + ((ownerId == null) ? 0 : ownerId.hashCode()); - result = prime * result + ((region == null) ? 0 : region.hashCode()); - result = prime * result + ((requesterId == null) ? 0 : requesterId.hashCode()); - result = prime * result + ((reservationId == null) ? 0 : reservationId.hashCode()); - return result; + return Objects.hashCode(region, reservationId, super.hashCode()); } @Override public boolean equals(Object obj) { if (this == obj) return true; - if (!super.equals(obj)) + if (obj == null || getClass() != obj.getClass()) return false; - if (getClass() != obj.getClass()) - return false; - Reservation other = (Reservation) obj; - if (groupIds == null) { - if (other.groupIds != null) - return false; - } else if (!groupIds.equals(other.groupIds)) - return false; - if (ownerId == null) { - if (other.ownerId != null) - return false; - } else if (!ownerId.equals(other.ownerId)) - return false; - if (region == null) { - if (other.region != null) - return false; - } else if (!region.equals(other.region)) - return false; - if (requesterId == null) { - if (other.requesterId != null) - return false; - } else if (!requesterId.equals(other.requesterId)) - return false; - if (reservationId == null) { - if (other.reservationId != null) - return false; - } else if (!reservationId.equals(other.reservationId)) - return false; - return true; + @SuppressWarnings("unchecked") + Reservation that = Reservation.class.cast(obj); + return super.equals(that) && Objects.equal(this.region, that.region) + && Objects.equal(this.reservationId, that.reservationId); + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return Objects.toStringHelper(this).omitNullValues().add("region", region).add("reservationId", reservationId) + .add("requesterId", requesterId).add("instances", instances).add("groupNames", groupNames).toString(); + } + + @Override + public int compareTo(Reservation other) { + return ComparisonChain.start().compare(region, other.region) + .compare(reservationId, other.reservationId, Ordering.natural().nullsLast()).result(); } } diff --git a/apis/ec2/src/main/java/org/jclouds/ec2/domain/ReservedInstancesOffering.java b/apis/ec2/src/main/java/org/jclouds/ec2/domain/ReservedInstancesOffering.java index f7987de2b1..a1f78e6337 100644 --- a/apis/ec2/src/main/java/org/jclouds/ec2/domain/ReservedInstancesOffering.java +++ b/apis/ec2/src/main/java/org/jclouds/ec2/domain/ReservedInstancesOffering.java @@ -46,10 +46,17 @@ public class ReservedInstancesOffering implements ComparableWarning + * + * Especially on EC2 clones that may not support regions, this value is fragile. Consider + * alternate means to determine context. + */ + @Deprecated public String getRegion() { return region; } - + /** * @return The Availability Zone in which the Reserved Instance can be used. */ diff --git a/apis/ec2/src/main/java/org/jclouds/ec2/domain/RunningInstance.java b/apis/ec2/src/main/java/org/jclouds/ec2/domain/RunningInstance.java index 0a11cb68ba..bb4613bff2 100644 --- a/apis/ec2/src/main/java/org/jclouds/ec2/domain/RunningInstance.java +++ b/apis/ec2/src/main/java/org/jclouds/ec2/domain/RunningInstance.java @@ -26,9 +26,13 @@ import java.util.Set; import org.jclouds.javax.annotation.Nullable; +import com.google.common.base.Objects; +import com.google.common.base.Objects.ToStringHelper; +import com.google.common.collect.ComparisonChain; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; +import com.google.common.collect.Ordering; import com.google.common.collect.Sets; /** @@ -44,7 +48,7 @@ public class RunningInstance implements Comparable { public static class Builder { protected String region; - protected Set groupIds = Sets.newLinkedHashSet(); + protected Set groupNames = Sets.newLinkedHashSet(); protected String amiLaunchIndex; protected String dnsName; protected String imageId; @@ -72,14 +76,14 @@ public class RunningInstance implements Comparable { return this; } - public Builder groupIds(Iterable groupIds) { - this.groupIds = ImmutableSet.copyOf(checkNotNull(groupIds, "groupIds")); + public Builder groupNames(Iterable groupNames) { + this.groupNames = ImmutableSet.copyOf(checkNotNull(groupNames, "groupNames")); return this; } - public Builder groupId(String groupId) { - if (groupId != null) - this.groupIds.add(groupId); + public Builder groupName(String groupName) { + if (groupName != null) + this.groupNames.add(groupName); return this; } @@ -195,7 +199,7 @@ public class RunningInstance implements Comparable { } public RunningInstance build() { - return new RunningInstance(region, groupIds, amiLaunchIndex, dnsName, imageId, instanceId, instanceState, + return new RunningInstance(region, groupNames, amiLaunchIndex, dnsName, imageId, instanceId, instanceState, rawState, instanceType, ipAddress, kernelId, keyName, launchTime, availabilityZone, virtualizationType, platform, privateDnsName, privateIpAddress, ramdiskId, reason, rootDeviceType, rootDeviceName, ebsBlockDevices); @@ -220,7 +224,7 @@ public class RunningInstance implements Comparable { } protected final String region; - protected final Set groupIds; + protected final Set groupNames; protected final String amiLaunchIndex; @Nullable protected final String dnsName; @@ -253,11 +257,7 @@ public class RunningInstance implements Comparable { protected final String rootDeviceName; protected final Map ebsBlockDevices; - public int compareTo(RunningInstance o) { - return (this == o) ? 0 : getId().compareTo(o.getId()); - } - - protected RunningInstance(String region, Iterable groupIds, @Nullable String amiLaunchIndex, + protected RunningInstance(String region, Iterable groupNames, @Nullable String amiLaunchIndex, @Nullable String dnsName, String imageId, String instanceId, InstanceState instanceState, String rawState, String instanceType, @Nullable String ipAddress, @Nullable String kernelId, @Nullable String keyName, Date launchTime, String availabilityZone, String virtualizationType, @Nullable String platform, @@ -286,12 +286,16 @@ public class RunningInstance implements Comparable { this.rootDeviceType = checkNotNull(rootDeviceType, "rootDeviceType for %s/%s", region, instanceId); this.rootDeviceName = rootDeviceName; this.ebsBlockDevices = ImmutableMap.copyOf(checkNotNull(ebsBlockDevices, "ebsBlockDevices for %s/%s", region, instanceId)); - this.groupIds = ImmutableSet.copyOf(checkNotNull(groupIds, "groupIds for %s/%s", region, instanceId)); + this.groupNames = ImmutableSet.copyOf(checkNotNull(groupNames, "groupNames for %s/%s", region, instanceId)); } /** - * Instance Ids are scoped to the region. + * To be removed in jclouds 1.6

Warning

+ * + * Especially on EC2 clones that may not support regions, this value is fragile. Consider + * alternate means to determine context. */ + @Deprecated public String getRegion() { return region; } @@ -443,160 +447,55 @@ public class RunningInstance implements Comparable { return ebsBlockDevices; } + /** + * @see #getGroupNames() + */ + @Deprecated + public Set getGroupIds() { + return getGroupNames(); + } + /** * Names of the security groups. */ - public Set getGroupIds() { - return groupIds; + public Set getGroupNames() { + return groupNames; } + @Override + public int compareTo(RunningInstance other) { + return ComparisonChain.start().compare(region, other.region).compare(instanceId, other.instanceId, Ordering.natural().nullsLast()).result(); + } + @Override public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((amiLaunchIndex == null) ? 0 : amiLaunchIndex.hashCode()); - result = prime * result + ((availabilityZone == null) ? 0 : availabilityZone.hashCode()); - result = prime * result + ((dnsName == null) ? 0 : dnsName.hashCode()); - result = prime * result + ((ebsBlockDevices == null) ? 0 : ebsBlockDevices.hashCode()); - result = prime * result + ((groupIds == null) ? 0 : groupIds.hashCode()); - result = prime * result + ((imageId == null) ? 0 : imageId.hashCode()); - result = prime * result + ((instanceId == null) ? 0 : instanceId.hashCode()); - result = prime * result + ((instanceType == null) ? 0 : instanceType.hashCode()); - result = prime * result + ((ipAddress == null) ? 0 : ipAddress.hashCode()); - result = prime * result + ((kernelId == null) ? 0 : kernelId.hashCode()); - result = prime * result + ((keyName == null) ? 0 : keyName.hashCode()); - result = prime * result + ((launchTime == null) ? 0 : launchTime.hashCode()); - result = prime * result + ((platform == null) ? 0 : platform.hashCode()); - result = prime * result + ((privateDnsName == null) ? 0 : privateDnsName.hashCode()); - result = prime * result + ((privateIpAddress == null) ? 0 : privateIpAddress.hashCode()); - result = prime * result + ((ramdiskId == null) ? 0 : ramdiskId.hashCode()); - result = prime * result + ((region == null) ? 0 : region.hashCode()); - result = prime * result + ((rootDeviceName == null) ? 0 : rootDeviceName.hashCode()); - result = prime * result + ((rootDeviceType == null) ? 0 : rootDeviceType.hashCode()); - result = prime * result + ((virtualizationType == null) ? 0 : virtualizationType.hashCode()); - return result; + return Objects.hashCode(region, instanceId); } @Override public boolean equals(Object obj) { if (this == obj) return true; - if (obj == null) + if (obj == null || getClass() != obj.getClass()) return false; - if (getClass() != obj.getClass()) - return false; - RunningInstance other = (RunningInstance) obj; - if (amiLaunchIndex == null) { - if (other.amiLaunchIndex != null) - return false; - } else if (!amiLaunchIndex.equals(other.amiLaunchIndex)) - return false; - if (availabilityZone == null) { - if (other.availabilityZone != null) - return false; - } else if (!availabilityZone.equals(other.availabilityZone)) - return false; - if (dnsName == null) { - if (other.dnsName != null) - return false; - } else if (!dnsName.equals(other.dnsName)) - return false; - if (ebsBlockDevices == null) { - if (other.ebsBlockDevices != null) - return false; - } else if (!ebsBlockDevices.equals(other.ebsBlockDevices)) - return false; - if (groupIds == null) { - if (other.groupIds != null) - return false; - } else if (!groupIds.equals(other.groupIds)) - return false; - if (imageId == null) { - if (other.imageId != null) - return false; - } else if (!imageId.equals(other.imageId)) - return false; - if (instanceId == null) { - if (other.instanceId != null) - return false; - } else if (!instanceId.equals(other.instanceId)) - return false; - if (instanceType == null) { - if (other.instanceType != null) - return false; - } else if (!instanceType.equals(other.instanceType)) - return false; - if (ipAddress == null) { - if (other.ipAddress != null) - return false; - } else if (!ipAddress.equals(other.ipAddress)) - return false; - if (kernelId == null) { - if (other.kernelId != null) - return false; - } else if (!kernelId.equals(other.kernelId)) - return false; - if (keyName == null) { - if (other.keyName != null) - return false; - } else if (!keyName.equals(other.keyName)) - return false; - if (launchTime == null) { - if (other.launchTime != null) - return false; - } else if (!launchTime.equals(other.launchTime)) - return false; - if (platform == null) { - if (other.platform != null) - return false; - } else if (!platform.equals(other.platform)) - return false; - if (privateDnsName == null) { - if (other.privateDnsName != null) - return false; - } else if (!privateDnsName.equals(other.privateDnsName)) - return false; - if (privateIpAddress == null) { - if (other.privateIpAddress != null) - return false; - } else if (!privateIpAddress.equals(other.privateIpAddress)) - return false; - if (ramdiskId == null) { - if (other.ramdiskId != null) - return false; - } else if (!ramdiskId.equals(other.ramdiskId)) - return false; - if (region == null) { - if (other.region != null) - return false; - } else if (!region.equals(other.region)) - return false; - if (rootDeviceName == null) { - if (other.rootDeviceName != null) - return false; - } else if (!rootDeviceName.equals(other.rootDeviceName)) - return false; - if (rootDeviceType == null) { - if (other.rootDeviceType != null) - return false; - } else if (!rootDeviceType.equals(other.rootDeviceType)) - return false; - if (virtualizationType == null) { - if (other.virtualizationType != null) - return false; - } else if (!virtualizationType.equals(other.virtualizationType)) - return false; - return true; + RunningInstance that = RunningInstance.class.cast(obj); + return Objects.equal(this.region, that.region) && Objects.equal(this.instanceId, that.instanceId); + } + + protected ToStringHelper string() { + return Objects.toStringHelper(this).omitNullValues().add("region", region) + .add("availabilityZone", availabilityZone).add("id", instanceId).add("state", rawState) + .add("type", instanceType).add("virtualizationType", virtualizationType).add("imageId", imageId) + .add("ipAddress", ipAddress).add("dnsName", dnsName).add("privateIpAddress", privateIpAddress) + .add("privateDnsName", privateDnsName).add("keyName", keyName).add("groupNames", groupNames) + .add("platform", platform).add("launchTime", launchTime).add("rootDeviceName", rootDeviceName) + .add("rootDeviceType", rootDeviceType).add("ebsBlockDevices", ebsBlockDevices); } @Override public String toString() { - return "[region=" + region + ", availabilityZone=" + availabilityZone + ", instanceId=" + instanceId - + ", instanceState=" + rawState + ", instanceType=" + instanceType + ", virtualizationType=" - + virtualizationType + ", imageId=" + imageId + ", ipAddress=" + ipAddress + ", dnsName=" + dnsName - + ", privateIpAddress=" + privateIpAddress + ", privateDnsName=" + privateDnsName + ", keyName=" - + keyName + ", groupIds=" + groupIds + ", platform=" + platform + ", launchTime=" + launchTime + ", rootDeviceName=" - + rootDeviceName + ", rootDeviceType=" + rootDeviceType + ", ebsBlockDevices=" + ebsBlockDevices + "]"; + return string().toString(); } + } diff --git a/apis/ec2/src/main/java/org/jclouds/ec2/domain/SecurityGroup.java b/apis/ec2/src/main/java/org/jclouds/ec2/domain/SecurityGroup.java index ebf1f6d5da..f13d1e583a 100644 --- a/apis/ec2/src/main/java/org/jclouds/ec2/domain/SecurityGroup.java +++ b/apis/ec2/src/main/java/org/jclouds/ec2/domain/SecurityGroup.java @@ -24,49 +24,147 @@ import java.util.Set; import org.jclouds.javax.annotation.Nullable; +import com.google.common.base.Objects; +import com.google.common.base.Objects.ToStringHelper; +import com.google.common.collect.ForwardingSet; +import com.google.common.collect.ImmutableSet; + /** - * + * * @see
* @author Adrian Cole */ -public class SecurityGroup implements Comparable { +public class SecurityGroup extends ForwardingSet { + + public static Builder builder() { + return new ConcreteBuilder(); + } + + public Builder toBuilder() { + return new ConcreteBuilder().fromSecurityGroup(this); + } + + public static abstract class Builder> { + protected abstract T self(); + + protected String region; + protected String id; + protected String name; + protected String ownerId; + protected String description; + protected ImmutableSet.Builder ipPermissions = ImmutableSet. builder(); + + /** + * @see SecurityGroup#getRegion() + */ + public T region(String region) { + this.region = region; + return self(); + } + + /** + * @see SecurityGroup#getId() + */ + public T id(String id) { + this.id = id; + return self(); + } + + /** + * @see SecurityGroup#getName() + */ + public T name(String name) { + this.name = name; + return self(); + } + + /** + * @see SecurityGroup#getOwnerId() + */ + public T ownerId(String ownerId) { + this.ownerId = ownerId; + return self(); + } + + /** + * @see SecurityGroup#getDescription() + */ + public T description(String description) { + this.description = description; + return self(); + } + + /** + * @see SecurityGroup#delegate() + */ + public T role(IpPermission role) { + this.ipPermissions.add(role); + return self(); + } + + /** + * @see SecurityGroup#delegate() + */ + public T ipPermissions(Iterable ipPermissions) { + this.ipPermissions.addAll(checkNotNull(ipPermissions, "ipPermissions")); + return self(); + } + + /** + * @see SecurityGroup#delegate() + */ + public T ipPermission(IpPermission ipPermission) { + this.ipPermissions.add(checkNotNull(ipPermission, "ipPermission")); + return self(); + } + + public SecurityGroup build() { + return new SecurityGroup(region, id, name, ownerId, description, ipPermissions.build()); + } + + public T fromSecurityGroup(SecurityGroup in) { + return region(in.region).id(in.id).name(in.name).ownerId(in.ownerId).description(in.description) + .ipPermissions(in); + } + } + + private static class ConcreteBuilder extends Builder { + @Override + protected ConcreteBuilder self() { + return this; + } + } private final String region; private final String id; private final String name; private final String ownerId; private final String description; - private final Set ipPermissions; + private final Set ipPermissions; public SecurityGroup(String region, String id, String name, String ownerId, String description, - Set ipPermissions) { + Iterable ipPermissions) { this.region = checkNotNull(region, "region"); this.id = id; this.name = name; this.ownerId = ownerId; this.description = description; - this.ipPermissions = ipPermissions; + this.ipPermissions = ImmutableSet.copyOf(checkNotNull(ipPermissions, "ipPermissions")); } /** - * Security groups are not copied across Regions. Instances within the Region - * cannot communicate with instances outside the Region using group-based - * firewall rules. Traffic from instances in another Region is seen as WAN - * bandwidth. + * To be removed in jclouds 1.6

Warning

+ * + * Especially on EC2 clones that may not support regions, this value is + * fragile. Consider alternate means to determine context. */ + @Deprecated public String getRegion() { return region; } - /** - * {@inheritDoc} - */ - public int compareTo(SecurityGroup o) { - return (this == o) ? 0 : getName().compareTo(o.getName()); - } - /** * id of the security group. Not in all EC2 impls */ @@ -97,70 +195,46 @@ public class SecurityGroup implements Comparable { } /** - * Set of IP permissions associated with the security group. + * Please use this class as a collection */ - public Set getIpPermissions() { + @Deprecated + public Set getIpPermissions() { return ipPermissions; } @Override public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((description == null) ? 0 : description.hashCode()); - result = prime * result + ((id == null) ? 0 : id.hashCode()); - result = prime * result + ((ipPermissions == null) ? 0 : ipPermissions.hashCode()); - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + ((ownerId == null) ? 0 : ownerId.hashCode()); - result = prime * result + ((region == null) ? 0 : region.hashCode()); - return result; + return Objects.hashCode(region, id, name, ownerId, description, ipPermissions); } @Override public boolean equals(Object obj) { if (this == obj) return true; - if (obj == null) + if (obj == null || getClass() != obj.getClass()) return false; - if (getClass() != obj.getClass()) - return false; - SecurityGroup other = (SecurityGroup) obj; - if (description == null) { - if (other.description != null) - return false; - } else if (!description.equals(other.description)) - return false; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - if (ipPermissions == null) { - if (other.ipPermissions != null) - return false; - } else if (!ipPermissions.equals(other.ipPermissions)) - return false; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - if (ownerId == null) { - if (other.ownerId != null) - return false; - } else if (!ownerId.equals(other.ownerId)) - return false; - if (region == null) { - if (other.region != null) - return false; - } else if (!region.equals(other.region)) - return false; - return true; + SecurityGroup that = SecurityGroup.class.cast(obj); + return Objects.equal(this.region, that.region) + && Objects.equal(this.id, that.id) + && Objects.equal(this.name, that.name) + && Objects.equal(this.ownerId, that.ownerId) + && Objects.equal(this.description, that.description) + && Objects.equal(this.ipPermissions, that.ipPermissions); + } + + protected ToStringHelper string() { + return Objects.toStringHelper(this).omitNullValues().add("region", region).add("id", id).add("name", name) + .add("ownerId", ownerId).add("description", description) + .add("ipPermissions", ipPermissions.size() == 0 ? null : ipPermissions); } @Override public String toString() { - return "[region=" + region + ", id=" + id + ", name=" + name + ", ownerId=" + ownerId + ", description=" - + description + ", ipPermissions=" + ipPermissions + "]"; + return string().toString(); + } + + @Override + protected Set delegate() { + return ipPermissions; } } diff --git a/apis/ec2/src/main/java/org/jclouds/ec2/domain/Snapshot.java b/apis/ec2/src/main/java/org/jclouds/ec2/domain/Snapshot.java index f01d01a40e..8acfbff519 100644 --- a/apis/ec2/src/main/java/org/jclouds/ec2/domain/Snapshot.java +++ b/apis/ec2/src/main/java/org/jclouds/ec2/domain/Snapshot.java @@ -75,12 +75,16 @@ public class Snapshot implements Comparable { } /** - * Snapshots are tied to Regions and can only be used for volumes within the same Region. + * To be removed in jclouds 1.6

Warning

+ * + * Especially on EC2 clones that may not support regions, this value is fragile. Consider + * alternate means to determine context. */ + @Deprecated public String getRegion() { return region; } - + /** * The ID of the snapshot. */ diff --git a/apis/ec2/src/main/java/org/jclouds/ec2/domain/Volume.java b/apis/ec2/src/main/java/org/jclouds/ec2/domain/Volume.java index 427560be3f..966a6ae440 100644 --- a/apis/ec2/src/main/java/org/jclouds/ec2/domain/Volume.java +++ b/apis/ec2/src/main/java/org/jclouds/ec2/domain/Volume.java @@ -38,6 +38,10 @@ import com.google.common.collect.ImmutableSet; */ public class Volume implements Comparable { + public Builder toBuilder() { + return builder().fromVolume(this); + } + /** * Specifies whether the instance's Amazon EBS volumes are stopped or terminated when the * instance is shut down. @@ -146,7 +150,13 @@ public class Volume implements Comparable { public Volume build() { return new Volume(region, id, size, snapshotId, availabilityZone, status, createTime, attachments); - } + } + + public Builder fromVolume(Volume in) { + return region(in.region).id(in.id).size(in.size).snapshotId(in.snapshotId) + .availabilityZone(in.availabilityZone).status(in.status).createTime(in.createTime) + .attachments(in.attachments); + } } private final String region; @@ -172,9 +182,12 @@ public class Volume implements Comparable { } /** - * An Amazon EBS volume must be located within the same Availability Zone as the instance to - * which it attaches. + * To be removed in jclouds 1.6

Warning

+ * + * Especially on EC2 clones that may not support regions, this value is fragile. Consider + * alternate means to determine context. */ + @Deprecated public String getRegion() { return region; } diff --git a/apis/ec2/src/main/java/org/jclouds/ec2/util/IpPermissions.java b/apis/ec2/src/main/java/org/jclouds/ec2/util/IpPermissions.java index 88cef2089b..1dad22db5f 100644 --- a/apis/ec2/src/main/java/org/jclouds/ec2/util/IpPermissions.java +++ b/apis/ec2/src/main/java/org/jclouds/ec2/util/IpPermissions.java @@ -24,7 +24,6 @@ import java.util.Map; import java.util.Map.Entry; import org.jclouds.ec2.domain.IpPermission; -import org.jclouds.ec2.domain.IpPermissionImpl; import org.jclouds.ec2.domain.IpProtocol; import org.jclouds.util.Maps2; @@ -37,12 +36,12 @@ import com.google.common.collect.Multimap; import com.google.common.collect.Multimaps; /** - * + * * Shortcut to create ingress rules - * + * * @author Adrian Cole */ -public class IpPermissions extends IpPermissionImpl { +public class IpPermissions extends IpPermission { protected IpPermissions(IpProtocol ipProtocol, int fromPort, int toPort, Multimap userIdGroupPairs, Iterable groupIds, Iterable ipRanges) { @@ -139,7 +138,7 @@ public class IpPermissions extends IpPermissionImpl { public ToPortSelection fromPort(int port) { return new ToPortSelection(getIpProtocol(), port); } - + public ToSourceSelection port(int port) { return new ToSourceSelection(getIpProtocol(), port, port); } diff --git a/apis/ec2/src/main/java/org/jclouds/ec2/xml/BaseReservationHandler.java b/apis/ec2/src/main/java/org/jclouds/ec2/xml/BaseReservationHandler.java index 33cb755acd..56ef8201a5 100644 --- a/apis/ec2/src/main/java/org/jclouds/ec2/xml/BaseReservationHandler.java +++ b/apis/ec2/src/main/java/org/jclouds/ec2/xml/BaseReservationHandler.java @@ -80,7 +80,7 @@ public abstract class BaseReservationHandler extends HandlerForGeneratedReque private String deviceName; // reservation stuff - private Set groupIds = Sets.newLinkedHashSet(); + private Set groupNames = Sets.newLinkedHashSet(); private String ownerId; private String requesterId; private String reservationId; @@ -111,7 +111,7 @@ public abstract class BaseReservationHandler extends HandlerForGeneratedReque } else if (equalsOrSuffix(qName, "groupSet")) { inGroupSet = false; } else if (equalsOrSuffix(qName, "groupId")) { - groupIds.add(currentOrNull(currentText)); + groupNames.add(currentOrNull(currentText)); } else if (equalsOrSuffix(qName, "ownerId")) { ownerId = currentOrNull(currentText); } else if (equalsOrSuffix(qName, "requesterId")) { @@ -210,7 +210,7 @@ public abstract class BaseReservationHandler extends HandlerForGeneratedReque } builder.region((region == null) ? defaultRegion.get() : region); - builder.groupIds(groupIds); + builder.groupNames(groupNames); } protected Builder builder() { @@ -229,9 +229,9 @@ public abstract class BaseReservationHandler extends HandlerForGeneratedReque String region = getRequest() != null ? AWSUtils.findRegionInArgsOrNull(getRequest()) : null; if (region == null) region = defaultRegion.get(); - Reservation info = new Reservation(region, groupIds, instances, + Reservation info = new Reservation(region, groupNames, instances, ownerId, requesterId, reservationId); - this.groupIds = Sets.newLinkedHashSet(); + this.groupNames = Sets.newLinkedHashSet(); this.instances = Sets.newLinkedHashSet(); this.ownerId = null; this.requesterId = null; diff --git a/apis/ec2/src/main/java/org/jclouds/ec2/xml/DescribeSecurityGroupsResponseHandler.java b/apis/ec2/src/main/java/org/jclouds/ec2/xml/DescribeSecurityGroupsResponseHandler.java index 9b1b53ddf9..3db80b9471 100644 --- a/apis/ec2/src/main/java/org/jclouds/ec2/xml/DescribeSecurityGroupsResponseHandler.java +++ b/apis/ec2/src/main/java/org/jclouds/ec2/xml/DescribeSecurityGroupsResponseHandler.java @@ -18,138 +18,111 @@ */ package org.jclouds.ec2.xml; -import static org.jclouds.util.SaxUtils.currentOrNegative; -import static org.jclouds.util.SaxUtils.currentOrNull; import static org.jclouds.util.SaxUtils.equalsOrSuffix; import java.util.Set; import javax.inject.Inject; -import org.jclouds.aws.util.AWSUtils; -import org.jclouds.ec2.domain.IpPermissionImpl; -import org.jclouds.ec2.domain.IpProtocol; import org.jclouds.ec2.domain.SecurityGroup; +import org.jclouds.http.HttpRequest; import org.jclouds.http.functions.ParseSax; -import org.jclouds.location.Region; +import org.jclouds.http.functions.ParseSax.HandlerForGeneratedRequestWithResult; import org.xml.sax.Attributes; +import org.xml.sax.SAXException; -import com.google.common.base.Supplier; import com.google.common.collect.ImmutableSet; -import com.google.common.collect.LinkedHashMultimap; -import com.google.common.collect.Multimap; -import com.google.common.collect.Sets; +import com.google.common.collect.ImmutableSet.Builder; /** * Parses: DescribeSecurityGroupsResponse * xmlns="http://ec2.amazonaws.com/doc/2010-06-15/" - * + * * @see
* @author Adrian Cole */ public class DescribeSecurityGroupsResponseHandler extends ParseSax.HandlerForGeneratedRequestWithResult> { - @Inject - @Region - Supplier defaultRegion; + + private final SecurityGroupHandler securityGroupHandler; private StringBuilder currentText = new StringBuilder(); - private Set securtyGroups = Sets.newLinkedHashSet(); - private String groupId; - private String groupName; - private String ownerId; - private String groupDescription; - private Set ipPermissions = Sets.newLinkedHashSet(); - private int fromPort; - private int toPort; - private Multimap groups = LinkedHashMultimap.create(); - private String userId; - private String userIdGroupName; - private IpProtocol ipProtocol; - private Set ipRanges = Sets.newLinkedHashSet(); + private Builder securityGroups = ImmutableSet. builder(); + private boolean inSecurityGroupInfo; - private boolean inIpPermissions; - private boolean inIpRanges; - private boolean inGroups; + protected int itemDepth; + @Inject + public DescribeSecurityGroupsResponseHandler(SecurityGroupHandler securityGroupHandler) { + this.securityGroupHandler = securityGroupHandler; + } + + @Override + public HandlerForGeneratedRequestWithResult> setContext(HttpRequest request) { + securityGroupHandler.setContext(request); + return super.setContext(request); + } + + /** + * {@inheritDoc} + */ + @Override public Set getResult() { - return securtyGroups; + return securityGroups.build(); } - public void startElement(String uri, String name, String qName, Attributes attrs) { - if (equalsOrSuffix(qName, "ipPermissions")) { - inIpPermissions = true; - } else if (equalsOrSuffix(qName, "ipRanges")) { - inIpRanges = true; - } else if (equalsOrSuffix(qName, "groups")) { - inGroups = true; + /** + * {@inheritDoc} + */ + @Override + public void startElement(String url, String name, String qName, Attributes attributes) throws SAXException { + if (equalsOrSuffix(qName, "item")) { + itemDepth++; + } else if (equalsOrSuffix(qName, "securityGroupInfo")) { + inSecurityGroupInfo = true; + } + if (inSecurityGroupInfo) { + securityGroupHandler.startElement(url, name, qName, attributes); } } - public void endElement(String uri, String name, String qName) { - if (equalsOrSuffix(qName, "groupName")) { - if (!inGroups) - this.groupName = currentOrNull(currentText); - else - this.userIdGroupName = currentOrNull(currentText); - } else if (equalsOrSuffix(qName, "groupId")) { - this.groupId = currentOrNull(currentText); - } else if (equalsOrSuffix(qName, "ownerId")) { - this.ownerId = currentOrNull(currentText); - } else if (equalsOrSuffix(qName, "userId")) { - this.userId = currentOrNull(currentText); - } else if (equalsOrSuffix(qName, "groupDescription")) { - this.groupDescription = currentOrNull(currentText); - } else if (equalsOrSuffix(qName, "ipProtocol")) { - // Algorete: ipProtocol can be an empty tag on EC2 clone (e.g. OpenStack EC2) - this.ipProtocol = IpProtocol.fromValue(currentOrNegative(currentText)); - } else if (equalsOrSuffix(qName, "fromPort")) { - // Algorete: fromPort can be an empty tag on EC2 clone (e.g. OpenStack EC2) - this.fromPort = Integer.parseInt(currentOrNegative(currentText)); - } else if (equalsOrSuffix(qName, "toPort")) { - // Algorete: toPort can be an empty tag on EC2 clone (e.g. OpenStack EC2) - this.toPort = Integer.parseInt(currentOrNegative(currentText)); - } else if (equalsOrSuffix(qName, "cidrIp")) { - this.ipRanges.add(currentOrNull(currentText)); - } else if (equalsOrSuffix(qName, "ipPermissions")) { - inIpPermissions = false; - } else if (equalsOrSuffix(qName, "ipRanges")) { - inIpRanges = false; - } else if (equalsOrSuffix(qName, "groups")) { - inGroups = false; - } else if (equalsOrSuffix(qName, "item")) { - if (inIpPermissions && !inIpRanges && !inGroups) { - // TODO groups? we need an example of VPC stuff - ipPermissions.add(new IpPermissionImpl(ipProtocol, fromPort, toPort, groups, ImmutableSet. of(), - ipRanges)); - this.fromPort = -1; - this.toPort = -1; - this.groups = LinkedHashMultimap.create(); - this.ipProtocol = null; - this.ipRanges = Sets.newLinkedHashSet(); - } else if (inIpPermissions && !inIpRanges && inGroups) { - this.groups.put(userId, userIdGroupName); - this.userId = null; - this.userIdGroupName = null; - } else if (!inIpPermissions && !inIpRanges && !inGroups) { - String region = AWSUtils.findRegionInArgsOrNull(getRequest()); - if (region == null) - region = defaultRegion.get(); - securtyGroups.add(new SecurityGroup(region, groupId, groupName, ownerId, groupDescription, ipPermissions)); - this.groupName = null; - this.groupId = null; - this.ownerId = null; - this.groupDescription = null; - this.ipPermissions = Sets.newLinkedHashSet(); - } + /** + * {@inheritDoc} + */ + @Override + public void endElement(String uri, String name, String qName) throws SAXException { + if (equalsOrSuffix(qName, "item")) { + endItem(uri, name, qName); + itemDepth--; + } else if (equalsOrSuffix(qName, "securityGroupInfo")) { + inSecurityGroupInfo = false; + } else if (inSecurityGroupInfo) { + securityGroupHandler.endElement(uri, name, qName); } - currentText = new StringBuilder(); } - public void characters(char ch[], int start, int length) { - currentText.append(ch, start, length); + protected void endItem(String uri, String name, String qName) throws SAXException { + if (inSecurityGroupInfo) { + if (itemDepth == 1) + securityGroups.add(securityGroupHandler.getResult()); + else + securityGroupHandler.endElement(uri, name, qName); + } } + + /** + * {@inheritDoc} + */ + @Override + public void characters(char ch[], int start, int length) { + if (inSecurityGroupInfo) { + securityGroupHandler.characters(ch, start, length); + } else { + currentText.append(ch, start, length); + } + } + } diff --git a/apis/ec2/src/main/java/org/jclouds/ec2/xml/IpPermissionHandler.java b/apis/ec2/src/main/java/org/jclouds/ec2/xml/IpPermissionHandler.java new file mode 100644 index 0000000000..8045feee40 --- /dev/null +++ b/apis/ec2/src/main/java/org/jclouds/ec2/xml/IpPermissionHandler.java @@ -0,0 +1,75 @@ +package org.jclouds.ec2.xml; + +import static org.jclouds.util.SaxUtils.currentOrNegative; +import static org.jclouds.util.SaxUtils.currentOrNull; +import static org.jclouds.util.SaxUtils.equalsOrSuffix; + +import org.jclouds.ec2.domain.IpPermission; +import org.jclouds.ec2.domain.IpProtocol; +import org.jclouds.http.functions.ParseSax; +import org.xml.sax.SAXException; + +/** + * + * @author Adrian Cole + */ +public class IpPermissionHandler extends ParseSax.HandlerForGeneratedRequestWithResult { + + private StringBuilder currentText = new StringBuilder(); + private IpPermission.Builder builder = IpPermission.builder(); + + /** + * {@inheritDoc} + */ + @Override + public IpPermission getResult() { + try { + return builder.build(); + } finally { + builder = IpPermission.builder(); + } + } + + private String userId; + private String groupId; + + /** + * {@inheritDoc} + */ + @Override + public void endElement(String uri, String name, String qName) throws SAXException { + if (equalsOrSuffix(qName, "ipProtocol")) { + // Algorete: ipProtocol can be an empty tag on EC2 clone (e.g. + // OpenStack EC2) + builder.ipProtocol(IpProtocol.fromValue(currentOrNegative(currentText))); + } else if (equalsOrSuffix(qName, "fromPort")) { + // Algorete: fromPort can be an empty tag on EC2 clone (e.g. OpenStack + // EC2) + builder.fromPort(Integer.parseInt(currentOrNegative(currentText))); + } else if (equalsOrSuffix(qName, "toPort")) { + // Algorete: toPort can be an empty tag on EC2 clone (e.g. OpenStack + // EC2) + builder.toPort(Integer.parseInt(currentOrNegative(currentText))); + } else if (equalsOrSuffix(qName, "cidrIp")) { + builder.ipRange(currentOrNull(currentText)); + } else if (equalsOrSuffix(qName, "userId")) { + this.userId = currentOrNull(currentText); + } else if (equalsOrSuffix(qName, "groupName") || equalsOrSuffix(qName, "groupId")) { + this.groupId = currentOrNull(currentText); + } else if (equalsOrSuffix(qName, "item")) { + if (userId != null && groupId != null) + builder.userIdGroupPair(userId, groupId); + userId = groupId = null; + } + currentText = new StringBuilder(); + } + + /** + * {@inheritDoc} + */ + @Override + public void characters(char ch[], int start, int length) { + currentText.append(ch, start, length); + } + +} diff --git a/apis/ec2/src/main/java/org/jclouds/ec2/xml/SecurityGroupHandler.java b/apis/ec2/src/main/java/org/jclouds/ec2/xml/SecurityGroupHandler.java new file mode 100644 index 0000000000..aeb7dbdec0 --- /dev/null +++ b/apis/ec2/src/main/java/org/jclouds/ec2/xml/SecurityGroupHandler.java @@ -0,0 +1,145 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.ec2.xml; + +import static org.jclouds.util.SaxUtils.currentOrNull; +import static org.jclouds.util.SaxUtils.equalsOrSuffix; + +import org.jclouds.aws.util.AWSUtils; +import org.jclouds.ec2.domain.SecurityGroup; +import org.jclouds.http.HttpRequest; +import org.jclouds.http.functions.ParseSax; +import org.jclouds.http.functions.ParseSax.HandlerForGeneratedRequestWithResult; +import org.jclouds.location.Region; +import org.jclouds.rest.internal.GeneratedHttpRequest; +import org.xml.sax.Attributes; +import org.xml.sax.SAXException; + +import com.google.common.base.Supplier; +import com.google.inject.Inject; + +/** + * @author Adrian Cole + */ +public class SecurityGroupHandler extends ParseSax.HandlerForGeneratedRequestWithResult { + + protected final IpPermissionHandler ipPermissionHandler; + protected final Supplier defaultRegion; + + protected StringBuilder currentText = new StringBuilder(); + protected SecurityGroup.Builder builder; + protected boolean inIpPermissions; + + protected int itemDepth; + + protected String region; + + @Inject + public SecurityGroupHandler(IpPermissionHandler ipPermissionHandler, @Region Supplier defaultRegion) { + this.ipPermissionHandler = ipPermissionHandler; + this.defaultRegion = defaultRegion; + } + + protected SecurityGroup.Builder builder() { + return SecurityGroup.builder().region(region); + } + + @Override + public HandlerForGeneratedRequestWithResult setContext(HttpRequest request) { + region = AWSUtils.findRegionInArgsOrNull(GeneratedHttpRequest.class.cast(request)); + if (region == null) + region = defaultRegion.get(); + builder = builder(); + return super.setContext(request); + } + + /** + * {@inheritDoc} + */ + @Override + public SecurityGroup getResult() { + try { + return builder.build(); + } finally { + builder = builder(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public void startElement(String url, String name, String qName, Attributes attributes) throws SAXException { + if (equalsOrSuffix(qName, "item")) { + itemDepth++; + } else if (equalsOrSuffix(qName, "ipPermissions")) { + inIpPermissions = true; + } + if (inIpPermissions) { + ipPermissionHandler.startElement(url, name, qName, attributes); + } + } + + /** + * {@inheritDoc} + */ + @Override + public void endElement(String uri, String name, String qName) throws SAXException { + if (equalsOrSuffix(qName, "item")) { + endItem(uri, name, qName); + itemDepth--; + } else if (equalsOrSuffix(qName, "ipPermissions")) { + inIpPermissions = false; + itemDepth = 0; + } else if (inIpPermissions) { + ipPermissionHandler.endElement(uri, name, qName); + } else if (equalsOrSuffix(qName, "groupName")) { + builder.name(currentOrNull(currentText)); + } else if (equalsOrSuffix(qName, "groupId")) { + builder.id(currentOrNull(currentText)); + } else if (equalsOrSuffix(qName, "ownerId")) { + builder.ownerId(currentOrNull(currentText)); + } else if (equalsOrSuffix(qName, "groupDescription")) { + builder.description(currentOrNull(currentText)); + } + currentText = new StringBuilder(); + } + + protected void endItem(String uri, String name, String qName) throws SAXException { + if (inIpPermissions) { + if (itemDepth == 2) + builder.ipPermission(ipPermissionHandler.getResult()); + else + ipPermissionHandler.endElement(uri, name, qName); + } + } + + /** + * {@inheritDoc} + */ + @Override + public void characters(char ch[], int start, int length) { + if (inIpPermissions) { + ipPermissionHandler.characters(ch, start, length); + } else { + currentText.append(ch, start, length); + } + } + +} diff --git a/apis/ec2/src/test/java/org/jclouds/ec2/compute/EC2ComputeServiceLiveTest.java b/apis/ec2/src/test/java/org/jclouds/ec2/compute/EC2ComputeServiceLiveTest.java index b204a073ef..f8ae751245 100644 --- a/apis/ec2/src/test/java/org/jclouds/ec2/compute/EC2ComputeServiceLiveTest.java +++ b/apis/ec2/src/test/java/org/jclouds/ec2/compute/EC2ComputeServiceLiveTest.java @@ -151,7 +151,7 @@ public class EC2ComputeServiceLiveTest extends BaseComputeServiceLiveTest { assertEquals(instance.getKeyName(), group); // make sure we made our dummy group and also let in the user's group - assertEquals(Sets.newTreeSet(instance.getGroupIds()), ImmutableSortedSet. of("jclouds#" + group + "#" + assertEquals(Sets.newTreeSet(instance.getGroupNames()), ImmutableSortedSet. of("jclouds#" + group + "#" + instance.getRegion(), group)); // make sure our dummy group has no rules diff --git a/apis/ec2/src/test/java/org/jclouds/ec2/compute/functions/RunningInstanceToNodeMetadataTest.java b/apis/ec2/src/test/java/org/jclouds/ec2/compute/functions/RunningInstanceToNodeMetadataTest.java index f677c320d6..75e5016c55 100644 --- a/apis/ec2/src/test/java/org/jclouds/ec2/compute/functions/RunningInstanceToNodeMetadataTest.java +++ b/apis/ec2/src/test/java/org/jclouds/ec2/compute/functions/RunningInstanceToNodeMetadataTest.java @@ -241,13 +241,13 @@ public class RunningInstanceToNodeMetadataTest { public void testGroupNameIsSetWhenCustomKeyNameIsSetAndSecurityGroupIsGenerated() { checkGroupName(RunningInstance.builder().instanceId("id").imageId("image").instanceType("m1.small") .instanceState(InstanceState.RUNNING).rawState("running").region("us-east-1").keyName("custom-key") - .groupId("jclouds#groupname").build()); + .groupName("jclouds#groupname").build()); } @Test public void testGroupNameIsSetWhenCustomSecurityGroupIsSetAndKeyNameIsGenerated() { checkGroupName(RunningInstance.builder().instanceId("id").imageId("image").instanceType("m1.small") - .instanceState(InstanceState.RUNNING).rawState("running").region("us-east-1").groupId("custom-sec") + .instanceState(InstanceState.RUNNING).rawState("running").region("us-east-1").groupName("custom-sec") .keyName("jclouds#groupname#23").build()); } diff --git a/apis/ec2/src/test/java/org/jclouds/ec2/options/BundleInstanceS3StorageOptionsTest.java b/apis/ec2/src/test/java/org/jclouds/ec2/options/BundleInstanceS3StorageOptionsTest.java index a753bbdc94..9a5aaa981a 100644 --- a/apis/ec2/src/test/java/org/jclouds/ec2/options/BundleInstanceS3StorageOptionsTest.java +++ b/apis/ec2/src/test/java/org/jclouds/ec2/options/BundleInstanceS3StorageOptionsTest.java @@ -18,11 +18,11 @@ */ package org.jclouds.ec2.options; -import static java.util.Collections.EMPTY_LIST; -import static java.util.Collections.singleton; import static org.jclouds.ec2.options.BundleInstanceS3StorageOptions.Builder.bucketOwnedBy; import static org.testng.Assert.assertEquals; +import com.google.common.collect.ImmutableList; + import org.jclouds.http.options.HttpRequestOptions; import org.testng.annotations.Test; @@ -44,26 +44,26 @@ public class BundleInstanceS3StorageOptionsTest { public void testBucketOwnedBy() { BundleInstanceS3StorageOptions options = new BundleInstanceS3StorageOptions(); options.bucketOwnedBy("test"); - assertEquals(options.buildFormParameters().get("Storage.S3.AWSAccessKeyId"), singleton("test")); + assertEquals(options.buildFormParameters().get("Storage.S3.AWSAccessKeyId"), ImmutableList.of("test")); } @Test(expectedExceptions = IllegalStateException.class) public void testNullBucketOwnedByNotInjected() { BundleInstanceS3StorageOptions options = new BundleInstanceS3StorageOptions(); - assertEquals(options.buildFormParameters().get("Storage.S3.AWSAccessKeyId"), EMPTY_LIST); + assertEquals(options.buildFormParameters().get("Storage.S3.AWSAccessKeyId"), ImmutableList.of()); } @Test public void testNullBucketOwnedBy() { BundleInstanceS3StorageOptions options = new BundleInstanceS3StorageOptions(); options.currentAwsAccessKeyId = "foo"; - assertEquals(options.buildFormParameters().get("Storage.S3.AWSAccessKeyId"), singleton("foo")); + assertEquals(options.buildFormParameters().get("Storage.S3.AWSAccessKeyId"), ImmutableList.of("foo")); } @Test public void testBucketOwnedByStatic() { BundleInstanceS3StorageOptions options = bucketOwnedBy("test"); - assertEquals(options.buildFormParameters().get("Storage.S3.AWSAccessKeyId"), singleton("test")); + assertEquals(options.buildFormParameters().get("Storage.S3.AWSAccessKeyId"), ImmutableList.of("test")); } @Test(expectedExceptions = NullPointerException.class) diff --git a/apis/ec2/src/test/java/org/jclouds/ec2/options/CreateImageOptionsTest.java b/apis/ec2/src/test/java/org/jclouds/ec2/options/CreateImageOptionsTest.java index 2c914ede7e..dd82439927 100644 --- a/apis/ec2/src/test/java/org/jclouds/ec2/options/CreateImageOptionsTest.java +++ b/apis/ec2/src/test/java/org/jclouds/ec2/options/CreateImageOptionsTest.java @@ -22,7 +22,7 @@ import static org.jclouds.ec2.options.CreateImageOptions.Builder.noReboot; import static org.jclouds.ec2.options.CreateImageOptions.Builder.withDescription; import static org.testng.Assert.assertEquals; -import java.util.Collections; +import com.google.common.collect.ImmutableList; import org.jclouds.http.options.HttpRequestOptions; import org.testng.annotations.Test; @@ -44,21 +44,21 @@ public class CreateImageOptionsTest { public void testWithDescription() { CreateImageOptions options = new CreateImageOptions(); options.withDescription("test"); - assertEquals(options.buildFormParameters().get("Description"), Collections - .singletonList("test")); + assertEquals(options.buildFormParameters().get("Description"), + ImmutableList.of("test")); } @Test public void testNullWithDescription() { CreateImageOptions options = new CreateImageOptions(); - assertEquals(options.buildFormParameters().get("Description"), Collections.EMPTY_LIST); + assertEquals(options.buildFormParameters().get("Description"), ImmutableList.of()); } @Test public void testWithDescriptionStatic() { CreateImageOptions options = withDescription("test"); - assertEquals(options.buildFormParameters().get("Description"), Collections - .singletonList("test")); + assertEquals(options.buildFormParameters().get("Description"), + ImmutableList.of("test")); } @Test(expectedExceptions = NullPointerException.class) @@ -70,13 +70,13 @@ public class CreateImageOptionsTest { public void testNoReboot() { CreateImageOptions options = new CreateImageOptions(); options.noReboot(); - assertEquals(options.buildFormParameters().get("NoReboot"), Collections.singletonList("true")); + assertEquals(options.buildFormParameters().get("NoReboot"), ImmutableList.of("true")); } @Test public void testNoRebootStatic() { CreateImageOptions options = noReboot(); - assertEquals(options.buildFormParameters().get("NoReboot"), Collections.singletonList("true")); + assertEquals(options.buildFormParameters().get("NoReboot"), ImmutableList.of("true")); } } diff --git a/apis/ec2/src/test/java/org/jclouds/ec2/options/CreateSnapshotOptionsTest.java b/apis/ec2/src/test/java/org/jclouds/ec2/options/CreateSnapshotOptionsTest.java index ccfe726390..d88cfaa4fd 100644 --- a/apis/ec2/src/test/java/org/jclouds/ec2/options/CreateSnapshotOptionsTest.java +++ b/apis/ec2/src/test/java/org/jclouds/ec2/options/CreateSnapshotOptionsTest.java @@ -21,7 +21,7 @@ package org.jclouds.ec2.options; import static org.jclouds.ec2.options.CreateSnapshotOptions.Builder.withDescription; import static org.testng.Assert.assertEquals; -import java.util.Collections; +import com.google.common.collect.ImmutableList; import org.jclouds.http.options.HttpRequestOptions; import org.testng.annotations.Test; @@ -43,21 +43,21 @@ public class CreateSnapshotOptionsTest { public void testWithDescription() { CreateSnapshotOptions options = new CreateSnapshotOptions(); options.withDescription("test"); - assertEquals(options.buildFormParameters().get("Description"), Collections - .singletonList("test")); + assertEquals(options.buildFormParameters().get("Description"), + ImmutableList.of("test")); } @Test public void testNullWithDescription() { CreateSnapshotOptions options = new CreateSnapshotOptions(); - assertEquals(options.buildFormParameters().get("Description"), Collections.EMPTY_LIST); + assertEquals(options.buildFormParameters().get("Description"), ImmutableList.of()); } @Test public void testWithDescriptionStatic() { CreateSnapshotOptions options = withDescription("test"); - assertEquals(options.buildFormParameters().get("Description"), Collections - .singletonList("test")); + assertEquals(options.buildFormParameters().get("Description"), + ImmutableList.of("test")); } @Test(expectedExceptions = NullPointerException.class) diff --git a/apis/ec2/src/test/java/org/jclouds/ec2/options/DescribeImagesOptionsTest.java b/apis/ec2/src/test/java/org/jclouds/ec2/options/DescribeImagesOptionsTest.java index f18a41c799..a93f872e26 100644 --- a/apis/ec2/src/test/java/org/jclouds/ec2/options/DescribeImagesOptionsTest.java +++ b/apis/ec2/src/test/java/org/jclouds/ec2/options/DescribeImagesOptionsTest.java @@ -23,7 +23,7 @@ import static org.jclouds.ec2.options.DescribeImagesOptions.Builder.imageIds; import static org.jclouds.ec2.options.DescribeImagesOptions.Builder.ownedBy; import static org.testng.Assert.assertEquals; -import java.util.Collections; +import com.google.common.collect.ImmutableList; import org.jclouds.http.options.HttpRequestOptions; import org.testng.annotations.Test; @@ -45,21 +45,21 @@ public class DescribeImagesOptionsTest { public void testExecutableBy() { DescribeImagesOptions options = new DescribeImagesOptions(); options.executableBy("test"); - assertEquals(options.buildFormParameters().get("ExecutableBy"), Collections - .singletonList("test")); + assertEquals(options.buildFormParameters().get("ExecutableBy"), + ImmutableList.of("test")); } @Test public void testNullExecutableBy() { DescribeImagesOptions options = new DescribeImagesOptions(); - assertEquals(options.buildFormParameters().get("ExecutableBy"), Collections.EMPTY_LIST); + assertEquals(options.buildFormParameters().get("ExecutableBy"), ImmutableList.of()); } @Test public void testExecutableByStatic() { DescribeImagesOptions options = executableBy("test"); - assertEquals(options.buildFormParameters().get("ExecutableBy"), Collections - .singletonList("test")); + assertEquals(options.buildFormParameters().get("ExecutableBy"), + ImmutableList.of("test")); } @Test(expectedExceptions = NullPointerException.class) @@ -71,28 +71,28 @@ public class DescribeImagesOptionsTest { public void testOwners() { DescribeImagesOptions options = new DescribeImagesOptions(); options.ownedBy("test"); - assertEquals(options.buildFormParameters().get("Owner.1"), Collections.singletonList("test")); + assertEquals(options.buildFormParameters().get("Owner.1"), ImmutableList.of("test")); } @Test public void testMultipleOwners() { DescribeImagesOptions options = new DescribeImagesOptions(); options.ownedBy("test", "trouble"); - assertEquals(options.buildFormParameters().get("Owner.1"), Collections.singletonList("test")); - assertEquals(options.buildFormParameters().get("Owner.2"), Collections - .singletonList("trouble")); + assertEquals(options.buildFormParameters().get("Owner.1"), ImmutableList.of("test")); + assertEquals(options.buildFormParameters().get("Owner.2"), + ImmutableList.of("trouble")); } @Test public void testNullOwners() { DescribeImagesOptions options = new DescribeImagesOptions(); - assertEquals(options.buildFormParameters().get("Owner.1"), Collections.EMPTY_LIST); + assertEquals(options.buildFormParameters().get("Owner.1"), ImmutableList.of()); } @Test public void testOwnersStatic() { DescribeImagesOptions options = ownedBy("test"); - assertEquals(options.buildFormParameters().get("Owner.1"), Collections.singletonList("test")); + assertEquals(options.buildFormParameters().get("Owner.1"), ImmutableList.of("test")); } public void testNoOwners() { @@ -103,31 +103,31 @@ public class DescribeImagesOptionsTest { public void testImageIds() { DescribeImagesOptions options = new DescribeImagesOptions(); options.imageIds("test"); - assertEquals(options.buildFormParameters().get("ImageId.1"), Collections - .singletonList("test")); + assertEquals(options.buildFormParameters().get("ImageId.1"), + ImmutableList.of("test")); } @Test public void testMultipleImageIds() { DescribeImagesOptions options = new DescribeImagesOptions(); options.imageIds("test", "trouble"); - assertEquals(options.buildFormParameters().get("ImageId.1"), Collections - .singletonList("test")); - assertEquals(options.buildFormParameters().get("ImageId.2"), Collections - .singletonList("trouble")); + assertEquals(options.buildFormParameters().get("ImageId.1"), + ImmutableList.of("test")); + assertEquals(options.buildFormParameters().get("ImageId.2"), + ImmutableList.of("trouble")); } @Test public void testNullImageIds() { DescribeImagesOptions options = new DescribeImagesOptions(); - assertEquals(options.buildFormParameters().get("ImageId.1"), Collections.EMPTY_LIST); + assertEquals(options.buildFormParameters().get("ImageId.1"), ImmutableList.of()); } @Test public void testImageIdsStatic() { DescribeImagesOptions options = imageIds("test"); - assertEquals(options.buildFormParameters().get("ImageId.1"), Collections - .singletonList("test")); + assertEquals(options.buildFormParameters().get("ImageId.1"), + ImmutableList.of("test")); } public void testNoImageIds() { diff --git a/apis/ec2/src/test/java/org/jclouds/ec2/options/DescribeSnapshotsOptionsTest.java b/apis/ec2/src/test/java/org/jclouds/ec2/options/DescribeSnapshotsOptionsTest.java index 03434b31c5..eca1f3f154 100644 --- a/apis/ec2/src/test/java/org/jclouds/ec2/options/DescribeSnapshotsOptionsTest.java +++ b/apis/ec2/src/test/java/org/jclouds/ec2/options/DescribeSnapshotsOptionsTest.java @@ -23,7 +23,7 @@ import static org.jclouds.ec2.options.DescribeSnapshotsOptions.Builder.restorabl import static org.jclouds.ec2.options.DescribeSnapshotsOptions.Builder.snapshotIds; import static org.testng.Assert.assertEquals; -import java.util.Collections; +import com.google.common.collect.ImmutableList; import org.jclouds.http.options.HttpRequestOptions; import org.testng.annotations.Test; @@ -45,49 +45,49 @@ public class DescribeSnapshotsOptionsTest { public void testRestorableBy() { DescribeSnapshotsOptions options = new DescribeSnapshotsOptions(); options.restorableBy("test"); - assertEquals(options.buildFormParameters().get("RestorableBy.1"), Collections - .singletonList("test")); + assertEquals(options.buildFormParameters().get("RestorableBy.1"), + ImmutableList.of("test")); } @Test public void testNullRestorableBy() { DescribeSnapshotsOptions options = new DescribeSnapshotsOptions(); - assertEquals(options.buildFormParameters().get("RestorableBy.1"), Collections.EMPTY_LIST); + assertEquals(options.buildFormParameters().get("RestorableBy.1"), ImmutableList.of()); } @Test public void testRestorableByStatic() { DescribeSnapshotsOptions options = restorableBy("test"); - assertEquals(options.buildFormParameters().get("RestorableBy.1"), Collections - .singletonList("test")); + assertEquals(options.buildFormParameters().get("RestorableBy.1"), + ImmutableList.of("test")); } @Test public void testOwners() { DescribeSnapshotsOptions options = new DescribeSnapshotsOptions(); options.ownedBy("test"); - assertEquals(options.buildFormParameters().get("Owner.1"), Collections.singletonList("test")); + assertEquals(options.buildFormParameters().get("Owner.1"), ImmutableList.of("test")); } @Test public void testMultipleOwners() { DescribeSnapshotsOptions options = new DescribeSnapshotsOptions(); options.ownedBy("test", "trouble"); - assertEquals(options.buildFormParameters().get("Owner.1"), Collections.singletonList("test")); - assertEquals(options.buildFormParameters().get("Owner.2"), Collections - .singletonList("trouble")); + assertEquals(options.buildFormParameters().get("Owner.1"), ImmutableList.of("test")); + assertEquals(options.buildFormParameters().get("Owner.2"), + ImmutableList.of("trouble")); } @Test public void testNullOwners() { DescribeSnapshotsOptions options = new DescribeSnapshotsOptions(); - assertEquals(options.buildFormParameters().get("Owner.1"), Collections.EMPTY_LIST); + assertEquals(options.buildFormParameters().get("Owner.1"), ImmutableList.of()); } @Test public void testOwnersStatic() { DescribeSnapshotsOptions options = ownedBy("test"); - assertEquals(options.buildFormParameters().get("Owner.1"), Collections.singletonList("test")); + assertEquals(options.buildFormParameters().get("Owner.1"), ImmutableList.of("test")); } public void testNoOwners() { @@ -98,31 +98,31 @@ public class DescribeSnapshotsOptionsTest { public void testSnapshotIds() { DescribeSnapshotsOptions options = new DescribeSnapshotsOptions(); options.snapshotIds("test"); - assertEquals(options.buildFormParameters().get("SnapshotId.1"), Collections - .singletonList("test")); + assertEquals(options.buildFormParameters().get("SnapshotId.1"), + ImmutableList.of("test")); } @Test public void testMultipleSnapshotIds() { DescribeSnapshotsOptions options = new DescribeSnapshotsOptions(); options.snapshotIds("test", "trouble"); - assertEquals(options.buildFormParameters().get("SnapshotId.1"), Collections - .singletonList("test")); - assertEquals(options.buildFormParameters().get("SnapshotId.2"), Collections - .singletonList("trouble")); + assertEquals(options.buildFormParameters().get("SnapshotId.1"), + ImmutableList.of("test")); + assertEquals(options.buildFormParameters().get("SnapshotId.2"), + ImmutableList.of("trouble")); } @Test public void testNullSnapshotIds() { DescribeSnapshotsOptions options = new DescribeSnapshotsOptions(); - assertEquals(options.buildFormParameters().get("SnapshotId.1"), Collections.EMPTY_LIST); + assertEquals(options.buildFormParameters().get("SnapshotId.1"), ImmutableList.of()); } @Test public void testSnapshotIdsStatic() { DescribeSnapshotsOptions options = snapshotIds("test"); - assertEquals(options.buildFormParameters().get("SnapshotId.1"), Collections - .singletonList("test")); + assertEquals(options.buildFormParameters().get("SnapshotId.1"), + ImmutableList.of("test")); } public void testNoSnapshotIds() { diff --git a/apis/ec2/src/test/java/org/jclouds/ec2/options/DetachVolumeOptionsTest.java b/apis/ec2/src/test/java/org/jclouds/ec2/options/DetachVolumeOptionsTest.java index 42b8c9be07..975bf23f7d 100644 --- a/apis/ec2/src/test/java/org/jclouds/ec2/options/DetachVolumeOptionsTest.java +++ b/apis/ec2/src/test/java/org/jclouds/ec2/options/DetachVolumeOptionsTest.java @@ -22,7 +22,7 @@ import static org.jclouds.ec2.options.DetachVolumeOptions.Builder.fromDevice; import static org.jclouds.ec2.options.DetachVolumeOptions.Builder.fromInstance; import static org.testng.Assert.assertEquals; -import java.util.Collections; +import com.google.common.collect.ImmutableList; import org.jclouds.http.options.HttpRequestOptions; import org.testng.annotations.Test; @@ -44,19 +44,19 @@ public class DetachVolumeOptionsTest { public void testFromDevice() { DetachVolumeOptions options = new DetachVolumeOptions(); options.fromDevice("test"); - assertEquals(options.buildFormParameters().get("Device"), Collections.singletonList("test")); + assertEquals(options.buildFormParameters().get("Device"), ImmutableList.of("test")); } @Test public void testNullFromDevice() { DetachVolumeOptions options = new DetachVolumeOptions(); - assertEquals(options.buildFormParameters().get("Device"), Collections.EMPTY_LIST); + assertEquals(options.buildFormParameters().get("Device"), ImmutableList.of()); } @Test public void testFromDeviceStatic() { DetachVolumeOptions options = fromDevice("test"); - assertEquals(options.buildFormParameters().get("Device"), Collections.singletonList("test")); + assertEquals(options.buildFormParameters().get("Device"), ImmutableList.of("test")); } @Test(expectedExceptions = NullPointerException.class) @@ -68,21 +68,21 @@ public class DetachVolumeOptionsTest { public void testFromInstance() { DetachVolumeOptions options = new DetachVolumeOptions(); options.fromInstance("test"); - assertEquals(options.buildFormParameters().get("InstanceId"), Collections - .singletonList("test")); + assertEquals(options.buildFormParameters().get("InstanceId"), + ImmutableList.of("test")); } @Test public void testNullFromInstance() { DetachVolumeOptions options = new DetachVolumeOptions(); - assertEquals(options.buildFormParameters().get("InstanceId"), Collections.EMPTY_LIST); + assertEquals(options.buildFormParameters().get("InstanceId"), ImmutableList.of()); } @Test public void testFromInstanceStatic() { DetachVolumeOptions options = fromInstance("test"); - assertEquals(options.buildFormParameters().get("InstanceId"), Collections - .singletonList("test")); + assertEquals(options.buildFormParameters().get("InstanceId"), + ImmutableList.of("test")); } @Test(expectedExceptions = NullPointerException.class) diff --git a/apis/ec2/src/test/java/org/jclouds/ec2/options/RegisterImageBackedByEbsOptionsTest.java b/apis/ec2/src/test/java/org/jclouds/ec2/options/RegisterImageBackedByEbsOptionsTest.java index c0d5f0ae2d..e56e161391 100644 --- a/apis/ec2/src/test/java/org/jclouds/ec2/options/RegisterImageBackedByEbsOptionsTest.java +++ b/apis/ec2/src/test/java/org/jclouds/ec2/options/RegisterImageBackedByEbsOptionsTest.java @@ -28,12 +28,11 @@ import static org.jclouds.ec2.options.RegisterImageBackedByEbsOptions.Builder.wi import static org.jclouds.ec2.options.RegisterImageBackedByEbsOptions.Builder.withRamdisk; import static org.testng.Assert.assertEquals; -import java.util.Collections; - import org.jclouds.ec2.domain.Image.Architecture; import org.jclouds.http.options.HttpRequestOptions; import org.testng.annotations.Test; +import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMultimap; /** @@ -54,21 +53,21 @@ public class RegisterImageBackedByEbsOptionsTest { public void testWithDescription() { RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions(); options.withDescription("test"); - assertEquals(options.buildFormParameters().get("Description"), Collections - .singletonList("test")); + assertEquals(options.buildFormParameters().get("Description"), + ImmutableList.of("test")); } @Test public void testNullWithDescription() { RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions(); - assertEquals(options.buildFormParameters().get("Description"), Collections.EMPTY_LIST); + assertEquals(options.buildFormParameters().get("Description"), ImmutableList.of()); } @Test public void testWithDescriptionStatic() { RegisterImageBackedByEbsOptions options = withDescription("test"); - assertEquals(options.buildFormParameters().get("Description"), Collections - .singletonList("test")); + assertEquals(options.buildFormParameters().get("Description"), + ImmutableList.of("test")); } @Test(expectedExceptions = NullPointerException.class) @@ -80,21 +79,21 @@ public class RegisterImageBackedByEbsOptionsTest { public void testWithArchitecture() { RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions(); options.asArchitecture(Architecture.I386); - assertEquals(options.buildFormParameters().get("Architecture"), Collections - .singletonList("i386")); + assertEquals(options.buildFormParameters().get("Architecture"), + ImmutableList.of("i386")); } @Test public void testNullWithArchitecture() { RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions(); - assertEquals(options.buildFormParameters().get("Architecture"), Collections.EMPTY_LIST); + assertEquals(options.buildFormParameters().get("Architecture"), ImmutableList.of()); } @Test public void testWithArchitectureStatic() { RegisterImageBackedByEbsOptions options = asArchitecture(Architecture.I386); - assertEquals(options.buildFormParameters().get("Architecture"), Collections - .singletonList("i386")); + assertEquals(options.buildFormParameters().get("Architecture"), + ImmutableList.of("i386")); } @Test(expectedExceptions = NullPointerException.class) @@ -106,19 +105,19 @@ public class RegisterImageBackedByEbsOptionsTest { public void testWithKernelId() { RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions(); options.withKernelId("test"); - assertEquals(options.buildFormParameters().get("KernelId"), Collections.singletonList("test")); + assertEquals(options.buildFormParameters().get("KernelId"), ImmutableList.of("test")); } @Test public void testNullWithKernelId() { RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions(); - assertEquals(options.buildFormParameters().get("KernelId"), Collections.EMPTY_LIST); + assertEquals(options.buildFormParameters().get("KernelId"), ImmutableList.of()); } @Test public void testWithKernelIdStatic() { RegisterImageBackedByEbsOptions options = withKernelId("test"); - assertEquals(options.buildFormParameters().get("KernelId"), Collections.singletonList("test")); + assertEquals(options.buildFormParameters().get("KernelId"), ImmutableList.of("test")); } @Test(expectedExceptions = NullPointerException.class) @@ -130,21 +129,21 @@ public class RegisterImageBackedByEbsOptionsTest { public void testWithRamdisk() { RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions(); options.withRamdisk("test"); - assertEquals(options.buildFormParameters().get("RamdiskId"), Collections - .singletonList("test")); + assertEquals(options.buildFormParameters().get("RamdiskId"), + ImmutableList.of("test")); } @Test public void testNullWithRamdisk() { RegisterImageBackedByEbsOptions options = new RegisterImageBackedByEbsOptions(); - assertEquals(options.buildFormParameters().get("RamdiskId"), Collections.EMPTY_LIST); + assertEquals(options.buildFormParameters().get("RamdiskId"), ImmutableList.of()); } @Test public void testWithRamdiskStatic() { RegisterImageBackedByEbsOptions options = withRamdisk("test"); - assertEquals(options.buildFormParameters().get("RamdiskId"), Collections - .singletonList("test")); + assertEquals(options.buildFormParameters().get("RamdiskId"), + ImmutableList.of("test")); } @Test(expectedExceptions = NullPointerException.class) diff --git a/apis/ec2/src/test/java/org/jclouds/ec2/options/RegisterImageOptionsTest.java b/apis/ec2/src/test/java/org/jclouds/ec2/options/RegisterImageOptionsTest.java index 77fd80b64a..801ee40040 100644 --- a/apis/ec2/src/test/java/org/jclouds/ec2/options/RegisterImageOptionsTest.java +++ b/apis/ec2/src/test/java/org/jclouds/ec2/options/RegisterImageOptionsTest.java @@ -24,7 +24,7 @@ import static org.jclouds.ec2.options.RegisterImageOptions.Builder.withKernelId; import static org.jclouds.ec2.options.RegisterImageOptions.Builder.withRamdisk; import static org.testng.Assert.assertEquals; -import java.util.Collections; +import com.google.common.collect.ImmutableList; import org.jclouds.ec2.domain.Image.Architecture; import org.jclouds.http.options.HttpRequestOptions; @@ -47,21 +47,21 @@ public class RegisterImageOptionsTest { public void testWithDescription() { RegisterImageOptions options = new RegisterImageOptions(); options.withDescription("test"); - assertEquals(options.buildFormParameters().get("Description"), Collections - .singletonList("test")); + assertEquals(options.buildFormParameters().get("Description"), + ImmutableList.of("test")); } @Test public void testNullWithDescription() { RegisterImageOptions options = new RegisterImageOptions(); - assertEquals(options.buildFormParameters().get("Description"), Collections.EMPTY_LIST); + assertEquals(options.buildFormParameters().get("Description"), ImmutableList.of()); } @Test public void testWithDescriptionStatic() { RegisterImageOptions options = withDescription("test"); - assertEquals(options.buildFormParameters().get("Description"), Collections - .singletonList("test")); + assertEquals(options.buildFormParameters().get("Description"), + ImmutableList.of("test")); } @Test(expectedExceptions = NullPointerException.class) @@ -73,21 +73,21 @@ public class RegisterImageOptionsTest { public void testWithArchitecture() { RegisterImageOptions options = new RegisterImageOptions(); options.asArchitecture(Architecture.I386); - assertEquals(options.buildFormParameters().get("Architecture"), Collections - .singletonList("i386")); + assertEquals(options.buildFormParameters().get("Architecture"), + ImmutableList.of("i386")); } @Test public void testNullWithArchitecture() { RegisterImageOptions options = new RegisterImageOptions(); - assertEquals(options.buildFormParameters().get("Architecture"), Collections.EMPTY_LIST); + assertEquals(options.buildFormParameters().get("Architecture"), ImmutableList.of()); } @Test public void testWithArchitectureStatic() { RegisterImageOptions options = asArchitecture(Architecture.I386); - assertEquals(options.buildFormParameters().get("Architecture"), Collections - .singletonList("i386")); + assertEquals(options.buildFormParameters().get("Architecture"), + ImmutableList.of("i386")); } @Test(expectedExceptions = NullPointerException.class) @@ -99,19 +99,19 @@ public class RegisterImageOptionsTest { public void testWithKernelId() { RegisterImageOptions options = new RegisterImageOptions(); options.withKernelId("test"); - assertEquals(options.buildFormParameters().get("KernelId"), Collections.singletonList("test")); + assertEquals(options.buildFormParameters().get("KernelId"), ImmutableList.of("test")); } @Test public void testNullWithKernelId() { RegisterImageOptions options = new RegisterImageOptions(); - assertEquals(options.buildFormParameters().get("KernelId"), Collections.EMPTY_LIST); + assertEquals(options.buildFormParameters().get("KernelId"), ImmutableList.of()); } @Test public void testWithKernelIdStatic() { RegisterImageOptions options = withKernelId("test"); - assertEquals(options.buildFormParameters().get("KernelId"), Collections.singletonList("test")); + assertEquals(options.buildFormParameters().get("KernelId"), ImmutableList.of("test")); } @Test(expectedExceptions = NullPointerException.class) @@ -123,21 +123,21 @@ public class RegisterImageOptionsTest { public void testWithRamdisk() { RegisterImageOptions options = new RegisterImageOptions(); options.withRamdisk("test"); - assertEquals(options.buildFormParameters().get("RamdiskId"), Collections - .singletonList("test")); + assertEquals(options.buildFormParameters().get("RamdiskId"), + ImmutableList.of("test")); } @Test public void testNullWithRamdisk() { RegisterImageOptions options = new RegisterImageOptions(); - assertEquals(options.buildFormParameters().get("RamdiskId"), Collections.EMPTY_LIST); + assertEquals(options.buildFormParameters().get("RamdiskId"), ImmutableList.of()); } @Test public void testWithRamdiskStatic() { RegisterImageOptions options = withRamdisk("test"); - assertEquals(options.buildFormParameters().get("RamdiskId"), Collections - .singletonList("test")); + assertEquals(options.buildFormParameters().get("RamdiskId"), + ImmutableList.of("test")); } @Test(expectedExceptions = NullPointerException.class) diff --git a/apis/ec2/src/test/java/org/jclouds/ec2/options/RunInstancesOptionsTest.java b/apis/ec2/src/test/java/org/jclouds/ec2/options/RunInstancesOptionsTest.java index 9091797931..bfccd8d561 100644 --- a/apis/ec2/src/test/java/org/jclouds/ec2/options/RunInstancesOptionsTest.java +++ b/apis/ec2/src/test/java/org/jclouds/ec2/options/RunInstancesOptionsTest.java @@ -27,13 +27,12 @@ import static org.jclouds.ec2.options.RunInstancesOptions.Builder.withSecurityGr import static org.jclouds.ec2.options.RunInstancesOptions.Builder.withUserData; import static org.testng.Assert.assertEquals; -import java.util.Collections; - import org.jclouds.ec2.domain.BlockDeviceMapping; import org.jclouds.ec2.domain.InstanceType; import org.jclouds.http.options.HttpRequestOptions; import org.testng.annotations.Test; +import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; /** @@ -53,19 +52,19 @@ public class RunInstancesOptionsTest { public void testWithKeyName() { RunInstancesOptions options = new RunInstancesOptions(); options.withKeyName("test"); - assertEquals(options.buildFormParameters().get("KeyName"), Collections.singletonList("test")); + assertEquals(options.buildFormParameters().get("KeyName"), ImmutableList.of("test")); } @Test public void testNullWithKeyName() { RunInstancesOptions options = new RunInstancesOptions(); - assertEquals(options.buildFormParameters().get("KeyName"), Collections.EMPTY_LIST); + assertEquals(options.buildFormParameters().get("KeyName"), ImmutableList.of()); } @Test public void testWithKeyNameStatic() { RunInstancesOptions options = withKeyName("test"); - assertEquals(options.buildFormParameters().get("KeyName"), Collections.singletonList("test")); + assertEquals(options.buildFormParameters().get("KeyName"), ImmutableList.of("test")); } @Test(expectedExceptions = NullPointerException.class) @@ -77,19 +76,19 @@ public class RunInstancesOptionsTest { public void testWithSecurityGroup() { RunInstancesOptions options = new RunInstancesOptions(); options.withSecurityGroup("test"); - assertEquals(options.buildFormParameters().get("SecurityGroup.1"), Collections.singletonList("test")); + assertEquals(options.buildFormParameters().get("SecurityGroup.1"), ImmutableList.of("test")); } @Test public void testNullWithSecurityGroup() { RunInstancesOptions options = new RunInstancesOptions(); - assertEquals(options.buildFormParameters().get("SecurityGroup"), Collections.EMPTY_LIST); + assertEquals(options.buildFormParameters().get("SecurityGroup"), ImmutableList.of()); } @Test public void testWithSecurityGroupStatic() { RunInstancesOptions options = withSecurityGroup("test"); - assertEquals(options.buildFormParameters().get("SecurityGroup.1"), Collections.singletonList("test")); + assertEquals(options.buildFormParameters().get("SecurityGroup.1"), ImmutableList.of("test")); } @Test(expectedExceptions = NullPointerException.class) @@ -100,26 +99,26 @@ public class RunInstancesOptionsTest { @Test public void testNullWithAdditionalInfo() { RunInstancesOptions options = new RunInstancesOptions(); - assertEquals(options.buildFormParameters().get("AdditionalInfo"), Collections.EMPTY_LIST); + assertEquals(options.buildFormParameters().get("AdditionalInfo"), ImmutableList.of()); } @Test public void testWithUserData() { RunInstancesOptions options = new RunInstancesOptions(); options.withUserData("test".getBytes()); - assertEquals(options.buildFormParameters().get("UserData"), Collections.singletonList("dGVzdA==")); + assertEquals(options.buildFormParameters().get("UserData"), ImmutableList.of("dGVzdA==")); } @Test public void testNullWithUserData() { RunInstancesOptions options = new RunInstancesOptions(); - assertEquals(options.buildFormParameters().get("UserData"), Collections.EMPTY_LIST); + assertEquals(options.buildFormParameters().get("UserData"), ImmutableList.of()); } @Test public void testWithUserDataStatic() { RunInstancesOptions options = withUserData("test".getBytes()); - assertEquals(options.buildFormParameters().get("UserData"), Collections.singletonList("dGVzdA==")); + assertEquals(options.buildFormParameters().get("UserData"), ImmutableList.of("dGVzdA==")); } @Test(expectedExceptions = NullPointerException.class) @@ -136,19 +135,19 @@ public class RunInstancesOptionsTest { public void testWithInstanceType() { RunInstancesOptions options = new RunInstancesOptions(); options.asType(InstanceType.C1_XLARGE); - assertEquals(options.buildFormParameters().get("InstanceType"), Collections.singletonList("c1.xlarge")); + assertEquals(options.buildFormParameters().get("InstanceType"), ImmutableList.of("c1.xlarge")); } @Test public void testNullWithInstanceType() { RunInstancesOptions options = new RunInstancesOptions(); - assertEquals(options.buildFormParameters().get("InstanceType"), Collections.EMPTY_LIST); + assertEquals(options.buildFormParameters().get("InstanceType"), ImmutableList.of()); } @Test public void testWithInstanceTypeStatic() { RunInstancesOptions options = asType(InstanceType.C1_XLARGE); - assertEquals(options.buildFormParameters().get("InstanceType"), Collections.singletonList("c1.xlarge")); + assertEquals(options.buildFormParameters().get("InstanceType"), ImmutableList.of("c1.xlarge")); } @Test(expectedExceptions = NullPointerException.class) @@ -160,19 +159,19 @@ public class RunInstancesOptionsTest { public void testWithKernelId() { RunInstancesOptions options = new RunInstancesOptions(); options.withKernelId("test"); - assertEquals(options.buildFormParameters().get("KernelId"), Collections.singletonList("test")); + assertEquals(options.buildFormParameters().get("KernelId"), ImmutableList.of("test")); } @Test public void testNullWithKernelId() { RunInstancesOptions options = new RunInstancesOptions(); - assertEquals(options.buildFormParameters().get("KernelId"), Collections.EMPTY_LIST); + assertEquals(options.buildFormParameters().get("KernelId"), ImmutableList.of()); } @Test public void testWithKernelIdStatic() { RunInstancesOptions options = withKernelId("test"); - assertEquals(options.buildFormParameters().get("KernelId"), Collections.singletonList("test")); + assertEquals(options.buildFormParameters().get("KernelId"), ImmutableList.of("test")); } @Test(expectedExceptions = NullPointerException.class) @@ -184,19 +183,19 @@ public class RunInstancesOptionsTest { public void testWithRamdisk() { RunInstancesOptions options = new RunInstancesOptions(); options.withRamdisk("test"); - assertEquals(options.buildFormParameters().get("RamdiskId"), Collections.singletonList("test")); + assertEquals(options.buildFormParameters().get("RamdiskId"), ImmutableList.of("test")); } @Test public void testNullWithRamdisk() { RunInstancesOptions options = new RunInstancesOptions(); - assertEquals(options.buildFormParameters().get("RamdiskId"), Collections.EMPTY_LIST); + assertEquals(options.buildFormParameters().get("RamdiskId"), ImmutableList.of()); } @Test public void testWithRamdiskStatic() { RunInstancesOptions options = withRamdisk("test"); - assertEquals(options.buildFormParameters().get("RamdiskId"), Collections.singletonList("test")); + assertEquals(options.buildFormParameters().get("RamdiskId"), ImmutableList.of("test")); } @Test(expectedExceptions = NullPointerException.class) @@ -207,7 +206,7 @@ public class RunInstancesOptionsTest { @Test public void testNullWithVirtualName() { RunInstancesOptions options = new RunInstancesOptions(); - assertEquals(options.buildFormParameters().get("BlockDeviceMapping.VirtualName"), Collections.EMPTY_LIST); + assertEquals(options.buildFormParameters().get("BlockDeviceMapping.VirtualName"), ImmutableList.of()); } @Test @@ -215,18 +214,18 @@ public class RunInstancesOptionsTest { BlockDeviceMapping mapping = new BlockDeviceMapping.MapNewVolumeToDevice("/dev/sda1", 120, true); RunInstancesOptions options = new RunInstancesOptions().withBlockDeviceMappings(ImmutableSet . of(mapping)); - assertEquals(options.buildFormParameters().get("BlockDeviceMapping.1.DeviceName"), Collections - .singletonList("/dev/sda1")); - assertEquals(options.buildFormParameters().get("BlockDeviceMapping.1.Ebs.VolumeSize"), Collections - .singletonList("120")); - assertEquals(options.buildFormParameters().get("BlockDeviceMapping.1.Ebs.DeleteOnTermination"), Collections - .singletonList("true")); + assertEquals(options.buildFormParameters().get("BlockDeviceMapping.1.DeviceName"), + ImmutableList.of("/dev/sda1")); + assertEquals(options.buildFormParameters().get("BlockDeviceMapping.1.Ebs.VolumeSize"), + ImmutableList.of("120")); + assertEquals(options.buildFormParameters().get("BlockDeviceMapping.1.Ebs.DeleteOnTermination"), + ImmutableList.of("true")); } @Test public void testNullWithBlockDeviceMapping() { RunInstancesOptions options = new RunInstancesOptions(); - assertEquals(options.buildFormParameters().get("BlockDeviceMapping"), Collections.EMPTY_LIST); + assertEquals(options.buildFormParameters().get("BlockDeviceMapping"), ImmutableList.of()); } @Test @@ -234,12 +233,12 @@ public class RunInstancesOptionsTest { BlockDeviceMapping mapping = new BlockDeviceMapping.MapNewVolumeToDevice("/dev/sda1", 120, true); RunInstancesOptions options = withBlockDeviceMappings(ImmutableSet . of(mapping)); - assertEquals(options.buildFormParameters().get("BlockDeviceMapping.1.DeviceName"), Collections - .singletonList("/dev/sda1")); - assertEquals(options.buildFormParameters().get("BlockDeviceMapping.1.Ebs.VolumeSize"), Collections - .singletonList("120")); - assertEquals(options.buildFormParameters().get("BlockDeviceMapping.1.Ebs.DeleteOnTermination"), Collections - .singletonList("true")); + assertEquals(options.buildFormParameters().get("BlockDeviceMapping.1.DeviceName"), + ImmutableList.of("/dev/sda1")); + assertEquals(options.buildFormParameters().get("BlockDeviceMapping.1.Ebs.VolumeSize"), + ImmutableList.of("120")); + assertEquals(options.buildFormParameters().get("BlockDeviceMapping.1.Ebs.DeleteOnTermination"), + ImmutableList.of("true")); } @Test(expectedExceptions = NullPointerException.class) diff --git a/apis/ec2/src/test/java/org/jclouds/ec2/services/EC2ElasticBlockStoreClientExpectTest.java b/apis/ec2/src/test/java/org/jclouds/ec2/services/EC2ElasticBlockStoreClientExpectTest.java index 3a0e92410e..4ef1fd8c0c 100644 --- a/apis/ec2/src/test/java/org/jclouds/ec2/services/EC2ElasticBlockStoreClientExpectTest.java +++ b/apis/ec2/src/test/java/org/jclouds/ec2/services/EC2ElasticBlockStoreClientExpectTest.java @@ -35,7 +35,16 @@ import com.google.common.collect.ImmutableMap.Builder; */ @Test(groups = "unit", testName = "EC2ElasticBlockStoreClientExpectTest") public class EC2ElasticBlockStoreClientExpectTest extends BaseEC2ExpectTest { - + Volume creating = Volume.builder() + .id("vol-2a21e543") + .status(Volume.Status.CREATING) + .availabilityZone("us-east-1a") + .region("us-east-1") + .id("vol-2a21e543") + .size(1) + .createTime(dateService.iso8601DateParse("2009-12-28T05:42:53.000Z")) + .build(); + public void testCreateVolumeInAvailabilityZone() { Builder builder = ImmutableMap.builder(); builder.put(describeRegionsRequest, describeRegionsResponse); @@ -51,18 +60,31 @@ public class EC2ElasticBlockStoreClientExpectTest extends BaseEC2ExpectTest builder = ImmutableMap.builder(); + builder.put(describeRegionsRequest, describeRegionsResponse); + builder.putAll(describeAvailabilityZonesRequestResponse); + builder.put( + formSigner.filter(HttpRequest.builder() + .method("POST") + .endpoint("https://ec2." + region + ".amazonaws.com/") + .addHeader("Host", "ec2." + region + ".amazonaws.com") + .addFormParam("Action", "CreateVolume") + .addFormParam("AvailabilityZone", "eu-west-1a") + .addFormParam("Size", "1") + .addFormParam("SnapshotId", "snap-8b7ffbdd").build()), + HttpResponse.builder() + .statusCode(200) + .payload(payloadFromResource("/created_volume.xml")).build()); + + ElasticBlockStoreClient client = requestsSendResponses(builder.build()).getElasticBlockStoreServices(); + assertEquals(client.createVolumeFromSnapshotInAvailabilityZone(region + "a", 1, "snap-8b7ffbdd"), creating.toBuilder().region(region).build()); + } } diff --git a/apis/ec2/src/test/java/org/jclouds/ec2/services/SecurityGroupClientLiveTest.java b/apis/ec2/src/test/java/org/jclouds/ec2/services/SecurityGroupClientLiveTest.java index 0f0c9e67a0..3cfa7738e2 100644 --- a/apis/ec2/src/test/java/org/jclouds/ec2/services/SecurityGroupClientLiveTest.java +++ b/apis/ec2/src/test/java/org/jclouds/ec2/services/SecurityGroupClientLiveTest.java @@ -23,7 +23,6 @@ import static org.testng.Assert.assertNotNull; import java.util.Iterator; import java.util.Set; -import java.util.SortedSet; import org.jclouds.compute.internal.BaseComputeServiceContextLiveTest; import org.jclouds.ec2.EC2ApiMetadata; @@ -32,14 +31,12 @@ import org.jclouds.ec2.domain.IpPermission; import org.jclouds.ec2.domain.IpProtocol; import org.jclouds.ec2.domain.SecurityGroup; import org.jclouds.ec2.domain.UserIdGroupPair; -import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.ImmutableSet; -import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Iterables; /** @@ -67,15 +64,13 @@ public class SecurityGroupClientLiveTest extends BaseComputeServiceContextLiveTe @Test void testDescribe() { for (String region : ec2Client.getConfiguredRegions()) { - SortedSet allResults = ImmutableSortedSet. copyOf(client - .describeSecurityGroupsInRegion(region)); + Set allResults = client.describeSecurityGroupsInRegion(region); assertNotNull(allResults); if (allResults.size() >= 1) { - SecurityGroup group = allResults.last(); - SortedSet result = ImmutableSortedSet. copyOf(client - .describeSecurityGroupsInRegion(region, group.getName())); + SecurityGroup group = Iterables.getLast(allResults); + Set result = client.describeSecurityGroupsInRegion(region, group.getName()); assertNotNull(result); - SecurityGroup compare = result.last(); + SecurityGroup compare = Iterables.getLast(result); assertEquals(compare, group); } } @@ -233,8 +228,7 @@ public class SecurityGroupClientLiveTest extends BaseComputeServiceContextLiveTe } protected void ensureGroupsExist(String group1Name, String group2Name) { - SortedSet twoResults = ImmutableSortedSet.copyOf(client.describeSecurityGroupsInRegion(null, - group1Name, group2Name)); + Set twoResults = client.describeSecurityGroupsInRegion(null, group1Name, group2Name); assertNotNull(twoResults); assertEquals(twoResults.size(), 2); Iterator iterator = twoResults.iterator(); @@ -279,8 +273,4 @@ public class SecurityGroupClientLiveTest extends BaseComputeServiceContextLiveTe public static final String PREFIX = System.getProperty("user.name") + "-ec2"; - @AfterTest - public void shutdown() { - view.close(); - } } diff --git a/apis/ec2/src/test/java/org/jclouds/ec2/suppliers/DescribeAvailabilityZonesInRegionTest.java b/apis/ec2/src/test/java/org/jclouds/ec2/suppliers/DescribeAvailabilityZonesInRegionTest.java index dd4f00ba37..c54565343d 100644 --- a/apis/ec2/src/test/java/org/jclouds/ec2/suppliers/DescribeAvailabilityZonesInRegionTest.java +++ b/apis/ec2/src/test/java/org/jclouds/ec2/suppliers/DescribeAvailabilityZonesInRegionTest.java @@ -23,7 +23,6 @@ import static org.easymock.classextension.EasyMock.createControl; import static org.testng.Assert.assertEquals; import static org.testng.Assert.fail; -import java.util.Collections; import java.util.Map; import java.util.Set; @@ -59,10 +58,10 @@ public class DescribeAvailabilityZonesInRegionTest { expect(client.getAvailabilityZoneAndRegionServices()).andStubReturn(regionClient); expect(regionClient.describeAvailabilityZonesInRegion("accessibleRegion1")).andReturn( - Collections.singleton(info1)); + ImmutableSet.of(info1)); expect(regionClient.describeAvailabilityZonesInRegion("inaccessibleRegion")).andThrow(exception); expect(regionClient.describeAvailabilityZonesInRegion("accessibleRegion2")).andReturn( - Collections.singleton(info2)); + ImmutableSet.of(info2)); expect(info1.getZone()).andStubReturn("zone1"); expect(info2.getZone()).andStubReturn("zone2"); @@ -113,14 +112,14 @@ public class DescribeAvailabilityZonesInRegionTest { expect(client.getAvailabilityZoneAndRegionServices()).andStubReturn(regionClient); expect(regionClient.describeAvailabilityZonesInRegion("emptyRegion")).andReturn( - Collections. emptySet()); + ImmutableSet. of()); Set regions = ImmutableSet.of("emptyRegion"); control.replay(); DescribeAvailabilityZonesInRegion regionIdToZoneId = new DescribeAvailabilityZonesInRegion(client, Suppliers .ofInstance(regions)); - assertEquals(regionIdToZoneId.get(), Collections. emptyMap()); + assertEquals(regionIdToZoneId.get(), ImmutableMap. of()); control.verify(); } } diff --git a/apis/ec2/src/test/java/org/jclouds/ec2/xml/DescribeInstancesResponseHandlerTest.java b/apis/ec2/src/test/java/org/jclouds/ec2/xml/DescribeInstancesResponseHandlerTest.java index ebdeba4a9f..24376d88cb 100644 --- a/apis/ec2/src/test/java/org/jclouds/ec2/xml/DescribeInstancesResponseHandlerTest.java +++ b/apis/ec2/src/test/java/org/jclouds/ec2/xml/DescribeInstancesResponseHandlerTest.java @@ -70,7 +70,7 @@ public class DescribeInstancesResponseHandlerTest extends BaseEC2HandlerTest { Set> contents = ImmutableSet.of(new Reservation(defaultRegion, ImmutableSet.of("adriancole.ec2ingress"), ImmutableSet.of(new RunningInstance.Builder().region( - defaultRegion).groupId("adriancole.ec2ingress").amiLaunchIndex("0").dnsName( + defaultRegion).groupName("adriancole.ec2ingress").amiLaunchIndex("0").dnsName( "ec2-174-129-81-68.compute-1.amazonaws.com").imageId("ami-82e4b5c7").instanceId("i-0799056f") .instanceState(InstanceState.RUNNING).rawState("running").instanceType(InstanceType.M1_SMALL) .ipAddress("174.129.81.68").kernelId("aki-a71cf9ce").keyName("adriancole.ec21").launchTime( @@ -83,7 +83,7 @@ public class DescribeInstancesResponseHandlerTest extends BaseEC2HandlerTest { Set> result = parseRunningInstances("/describe_instances_running.xml"); - assertEquals(result, contents); + assertEquals(result.toString(), contents.toString()); assertEquals(get(get(result, 0), 0).getInstanceState(), InstanceState.RUNNING); assertEquals(get(get(result, 0), 0).getRawState(), "running"); @@ -91,7 +91,7 @@ public class DescribeInstancesResponseHandlerTest extends BaseEC2HandlerTest { public void testApplyInputStream() { Set> contents = ImmutableSet.of(new Reservation(defaultRegion, - ImmutableSet.of("default"), ImmutableSet.of(new RunningInstance.Builder().region(defaultRegion).groupId( + ImmutableSet.of("default"), ImmutableSet.of(new RunningInstance.Builder().region(defaultRegion).groupName( "default").amiLaunchIndex("23").dnsName("ec2-72-44-33-4.compute-1.amazonaws.com").imageId( "ami-6ea54007").instanceId("i-28a64341").instanceState(InstanceState.RUNNING).rawState( "running").instanceType(InstanceType.M1_LARGE).kernelId("aki-ba3adfd3").keyName( @@ -101,7 +101,7 @@ public class DescribeInstancesResponseHandlerTest extends BaseEC2HandlerTest { "10-251-50-132.ec2.internal")// product codes // ImmutableSet.of("774F4FF8") .ramdiskId("ari-badbad00").rootDeviceType(RootDeviceType.INSTANCE_STORE).build(), - new RunningInstance.Builder().region(defaultRegion).groupId("default").amiLaunchIndex("23") + new RunningInstance.Builder().region(defaultRegion).groupName("default").amiLaunchIndex("23") .dnsName("ec2-72-44-33-6.compute-1.amazonaws.com").imageId("ami-6ea54007").instanceId( "i-28a64435").instanceState(InstanceState.RUNNING).rawState("running") .instanceType(InstanceType.M1_LARGE).kernelId("aki-ba3adfd3").keyName( @@ -116,7 +116,7 @@ public class DescribeInstancesResponseHandlerTest extends BaseEC2HandlerTest { Set> result = parseRunningInstances("/describe_instances.xml"); - assertEquals(result, contents); + assertEquals(result.toString(), contents.toString()); assertEquals(get(get(result, 0), 0).getInstanceState(), InstanceState.RUNNING); assertEquals(get(get(result, 0), 0).getRawState(), "running"); @@ -126,7 +126,7 @@ public class DescribeInstancesResponseHandlerTest extends BaseEC2HandlerTest { Set> contents = ImmutableSet.of(new Reservation(defaultRegion, ImmutableSet.of("adriancole.ec2ebsingress"), ImmutableSet.of(new RunningInstance.Builder().region( - defaultRegion).groupId("adriancole.ec2ebsingress").amiLaunchIndex("0").dnsName( + defaultRegion).groupName("adriancole.ec2ebsingress").amiLaunchIndex("0").dnsName( "ec2-75-101-203-146.compute-1.amazonaws.com").imageId("ami-849875ed").instanceId("i-e564438d") .instanceState(InstanceState.RUNNING).rawState("running").instanceType(InstanceType.M1_SMALL) .ipAddress("75.101.203.146").kernelId("aki-a71cf9ce") @@ -145,7 +145,7 @@ public class DescribeInstancesResponseHandlerTest extends BaseEC2HandlerTest { Set> result = parseRunningInstances("/describe_instances_ebs.xml"); - assertEquals(result, contents); + assertEquals(result.toString(), contents.toString()); assertEquals(get(get(result, 0), 0).getInstanceState(), InstanceState.RUNNING); assertEquals(get(get(result, 0), 0).getRawState(), "running"); } diff --git a/apis/ec2/src/test/java/org/jclouds/ec2/xml/DescribeSecurityGroupsResponseHandlerTest.java b/apis/ec2/src/test/java/org/jclouds/ec2/xml/DescribeSecurityGroupsResponseHandlerTest.java index 4026c9fc0f..b7bd44f62c 100644 --- a/apis/ec2/src/test/java/org/jclouds/ec2/xml/DescribeSecurityGroupsResponseHandlerTest.java +++ b/apis/ec2/src/test/java/org/jclouds/ec2/xml/DescribeSecurityGroupsResponseHandlerTest.java @@ -26,7 +26,7 @@ import static org.testng.Assert.assertEquals; import java.io.InputStream; import java.util.Set; -import org.jclouds.ec2.domain.IpPermissionImpl; +import org.jclouds.ec2.domain.IpPermission; import org.jclouds.ec2.domain.IpProtocol; import org.jclouds.ec2.domain.SecurityGroup; import org.jclouds.http.functions.ParseSax; @@ -41,7 +41,7 @@ import com.google.common.collect.Multimap; /** * Tests behavior of {@code DescribeSecurityGroupsResponseHandler} - * + * * @author Adrian Cole */ // NOTE:without testName, this will not call @Before* and fail w/NPE during @@ -54,40 +54,40 @@ public class DescribeSecurityGroupsResponseHandlerTest extends BaseEC2HandlerTes Set expected = ImmutableSet.of( new SecurityGroup(defaultRegion, null, "WebServers", "UYY3TLBUXIEON5NQVUUX6OMPWBZIQNFM", "Web Servers", - ImmutableSet.of(new IpPermissionImpl(IpProtocol.TCP, 80, 80, ImmutableMultimap. of(), + ImmutableSet.of(new IpPermission(IpProtocol.TCP, 80, 80, ImmutableMultimap. of(), ImmutableSet. of(), ImmutableSet.of("0.0.0.0/0")))), new SecurityGroup(defaultRegion, null, "RangedPortsBySource", "UYY3TLBUXIEON5NQVUUX6OMPWBZIQNFM", "Group A", - ImmutableSet.of(new IpPermissionImpl(IpProtocol.TCP, 6000, 7000, ImmutableMultimap + ImmutableSet.of(new IpPermission(IpProtocol.TCP, 6000, 7000, ImmutableMultimap . of(), ImmutableSet. of(), ImmutableSet. of())))); DescribeSecurityGroupsResponseHandler handler = injector.getInstance(DescribeSecurityGroupsResponseHandler.class); addDefaultRegionToHandler(handler); Set result = factory.create(handler).parse(is); - assertEquals(result, expected); + assertEquals(result.toString(), expected.toString()); } // Response from OpenStack 1.1 EC2 API public void testApplyInputStreamWithEmptyFields() { InputStream is = getClass().getResourceAsStream("/describe_securitygroups_empty.xml"); - + Multimap userIdGroupPairs = LinkedHashMultimap.create(); userIdGroupPairs.put("UYY3TLBUXIEON5NQVUUX6OMPWBZIQNFM", "jclouds#cluster#world"); - + Set expected = ImmutableSet.of( new SecurityGroup(defaultRegion, null, "jclouds#cluster#world", "UYY3TLBUXIEON5NQVUUX6OMPWBZIQNFM", "Cluster", ImmutableSet.of( - new IpPermissionImpl(IpProtocol.TCP, 22, 22, ImmutableMultimap. of(), + new IpPermission(IpProtocol.TCP, 22, 22, ImmutableMultimap. of(), ImmutableSet. of(), ImmutableSet.of("0.0.0.0/0")), - new IpPermissionImpl(IpProtocol.ALL, -1, -1, userIdGroupPairs, + new IpPermission(IpProtocol.ALL, -1, -1, userIdGroupPairs, ImmutableSet. of(), ImmutableSet. of())))); DescribeSecurityGroupsResponseHandler handler = injector.getInstance(DescribeSecurityGroupsResponseHandler.class); addDefaultRegionToHandler(handler); Set result = factory.create(handler).parse(is); - assertEquals(result, expected); + assertEquals(result.toString(), expected.toString()); } private void addDefaultRegionToHandler(ParseSax.HandlerWithResult handler) { diff --git a/apis/ec2/src/test/java/org/jclouds/ec2/xml/RunInstancesResponseHandlerTest.java b/apis/ec2/src/test/java/org/jclouds/ec2/xml/RunInstancesResponseHandlerTest.java index 0b23ebf203..1b37c5396e 100644 --- a/apis/ec2/src/test/java/org/jclouds/ec2/xml/RunInstancesResponseHandlerTest.java +++ b/apis/ec2/src/test/java/org/jclouds/ec2/xml/RunInstancesResponseHandlerTest.java @@ -65,19 +65,19 @@ public class RunInstancesResponseHandlerTest extends BaseEC2HandlerTest { Reservation expected = new Reservation(defaultRegion, ImmutableSet .of("default"), ImmutableSet.of( - new RunningInstance.Builder().region(defaultRegion).groupId("default").amiLaunchIndex("0") + new RunningInstance.Builder().region(defaultRegion).groupName("default").amiLaunchIndex("0") .imageId("ami-60a54009").instanceId("i-2ba64342").instanceState(InstanceState.PENDING).rawState( "pending").instanceType(InstanceType.M1_SMALL).keyName("example-key-name").launchTime( dateService.iso8601DateParse("2007-08-07T11:51:50.000Z"))// MonitoringState.ENABLED, .availabilityZone("us-east-1b").build(), - new RunningInstance.Builder().region(defaultRegion).groupId("default").amiLaunchIndex("1") + new RunningInstance.Builder().region(defaultRegion).groupName("default").amiLaunchIndex("1") .imageId("ami-60a54009").instanceId("i-2bc64242").instanceState(InstanceState.PENDING).rawState( "pending").instanceType(InstanceType.M1_SMALL).keyName("example-key-name").launchTime( dateService.iso8601DateParse("2007-08-07T11:51:50.000Z"))// MonitoringState.ENABLED, .availabilityZone("us-east-1b").build(), - new RunningInstance.Builder().region(defaultRegion).groupId("default").amiLaunchIndex("2") + new RunningInstance.Builder().region(defaultRegion).groupName("default").amiLaunchIndex("2") .imageId("ami-60a54009").instanceId("i-2be64332").instanceState(InstanceState.PENDING).rawState( "pending").instanceType(InstanceType.M1_SMALL).keyName("example-key-name").launchTime( dateService.iso8601DateParse("2007-08-07T11:51:50.000Z"))// MonitoringState.ENABLED, @@ -96,9 +96,9 @@ public class RunInstancesResponseHandlerTest extends BaseEC2HandlerTest { InputStream is = getClass().getResourceAsStream("/run_instances_cloudbridge.xml"); Reservation expected = new Reservation(defaultRegion, ImmutableSet - .of("default"), ImmutableSet.of( + .of("jclouds#greenqloud-computeblock"), ImmutableSet.of( - new RunningInstance.Builder().region(defaultRegion).groupId("jclouds#greenqloud-computeblock").amiLaunchIndex("0") + new RunningInstance.Builder().region(defaultRegion).groupName("jclouds#greenqloud-computeblock").amiLaunchIndex("0") .imageId("qmi-9ac92558").instanceId("i-01b0dac3").instanceState(InstanceState.PENDING).rawState( "pending").instanceType(InstanceType.M1_SMALL).keyName("jclouds#greenqloud-computeblock#35") .launchTime(dateService.iso8601DateParse("2012-06-15T19:06:35.000+00:00")) diff --git a/apis/ec2/src/test/resources/describe_securitygroups.xml b/apis/ec2/src/test/resources/describe_securitygroups.xml index 5d6087f546..3a6c9b86d3 100644 --- a/apis/ec2/src/test/resources/describe_securitygroups.xml +++ b/apis/ec2/src/test/resources/describe_securitygroups.xml @@ -1,36 +1,37 @@ - - - - UYY3TLBUXIEON5NQVUUX6OMPWBZIQNFM - WebServers - Web Servers - - - tcp - 80 - 80 - - - - 0.0.0.0/0 - - - - - - - UYY3TLBUXIEON5NQVUUX6OMPWBZIQNFM - RangedPortsBySource - Group A - - - tcp - 6000 - 7000 - - - - - - + + + + UYY3TLBUXIEON5NQVUUX6OMPWBZIQNFM + WebServers + Web Servers + + + tcp + 80 + 80 + + + + 0.0.0.0/0 + + + + + + + UYY3TLBUXIEON5NQVUUX6OMPWBZIQNFM + RangedPortsBySource + Group A + + + tcp + 6000 + 7000 + + + + + + \ No newline at end of file diff --git a/apis/ec2/src/test/resources/describe_securitygroups_empty.xml b/apis/ec2/src/test/resources/describe_securitygroups_empty.xml index 75add413cd..0079ee6abd 100644 --- a/apis/ec2/src/test/resources/describe_securitygroups_empty.xml +++ b/apis/ec2/src/test/resources/describe_securitygroups_empty.xml @@ -1,39 +1,39 @@ - - L6EFIZVPJS76T3K5-0UV - + + L6EFIZVPJS76T3K5-0UV + + + + + 22 + tcp + + + 0.0.0.0/0 + + + + 22 + - - - - 22 - tcp - - - 0.0.0.0/0 - - - - 22 - + + + + + + + jclouds#cluster#world + UYY3TLBUXIEON5NQVUUX6OMPWBZIQNFM + + + + + + jclouds#cluster#world + Cluster + UYY3TLBUXIEON5NQVUUX6OMPWBZIQNFM + - - - - - - - jclouds#cluster#world - UYY3TLBUXIEON5NQVUUX6OMPWBZIQNFM - - - - - - jclouds#cluster#world - Cluster - UYY3TLBUXIEON5NQVUUX6OMPWBZIQNFM - - - + diff --git a/apis/elasticstack/pom.xml b/apis/elasticstack/pom.xml index eabb89ac43..a2f2ecc9fd 100644 --- a/apis/elasticstack/pom.xml +++ b/apis/elasticstack/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.api @@ -33,27 +33,13 @@ jclouds components to access elasticstack bundle - - - - sonatype-nexus-snapshots - https://oss.sonatype.org/content/repositories/snapshots - - false - - - true - - - - https://api-lon-p.elastichosts.com - 1.0 + 2.0 FIXME FIXME - imageId=38df0986-4d85-4b76-b502-3878ffc80161 + imageId=38df0986-4d85-4b76-b502-3878ffc80161,loginUser=toor org.jclouds.elasticstack*;version="${project.version}" org.jclouds.compute.internal;version="${project.version}", diff --git a/apis/elasticstack/src/main/java/org/jclouds/elasticstack/compute/ElasticStackComputeServiceAdapter.java b/apis/elasticstack/src/main/java/org/jclouds/elasticstack/compute/ElasticStackComputeServiceAdapter.java index adce2eba15..217f71a13a 100644 --- a/apis/elasticstack/src/main/java/org/jclouds/elasticstack/compute/ElasticStackComputeServiceAdapter.java +++ b/apis/elasticstack/src/main/java/org/jclouds/elasticstack/compute/ElasticStackComputeServiceAdapter.java @@ -122,7 +122,8 @@ public class ElasticStackComputeServiceAdapter implements } Server toCreate = small(name, drive.getUuid(), defaultVncPassword).mem(template.getHardware().getRam()) - .cpu((int) (template.getHardware().getProcessors().get(0).getSpeed())).build(); + .cpu((int) (template.getHardware().getProcessors().get(0).getSpeed())) + .tags(template.getOptions().getTags()).userMetadata(template.getOptions().getUserMetadata()).build(); ServerInfo from = client.createServer(toCreate); client.startServer(from.getUuid()); diff --git a/apis/elasticstack/src/main/java/org/jclouds/elasticstack/compute/functions/ServerInfoToNodeMetadata.java b/apis/elasticstack/src/main/java/org/jclouds/elasticstack/compute/functions/ServerInfoToNodeMetadata.java index 887d0f3486..27f648f928 100644 --- a/apis/elasticstack/src/main/java/org/jclouds/elasticstack/compute/functions/ServerInfoToNodeMetadata.java +++ b/apis/elasticstack/src/main/java/org/jclouds/elasticstack/compute/functions/ServerInfoToNodeMetadata.java @@ -93,7 +93,8 @@ public class ServerInfoToNodeMetadata implements Function driveNotClaimed; protected String imageId; - @BeforeGroups(groups = { "integration", "live" }) @Override + @BeforeClass(groups = { "integration", "live" }) public void setupContext() { super.setupContext(); - cloudStackContext = view.unwrap(); + imageId = view.getComputeService().templateBuilder().build().getImage().getId(); - client = cloudStackContext.getApi(); + client = view.unwrap(ElasticStackApiMetadata.CONTEXT_TOKEN).getApi(); driveNotClaimed = new RetryablePredicate(Predicates.not(new DriveClaimed(client)), maxDriveImageTime, 1, TimeUnit.SECONDS); socketTester = new RetryablePredicate(new InetSocketAddressConnect(), maxDriveImageTime, 1, TimeUnit.SECONDS); - - if (template == null || template.getImageId() == null) { - imageId = view.getComputeService().templateBuilder().build().getImage().getId(); - } } - + @Test public void testListServers() throws Exception { Set servers = client.listServers(); diff --git a/apis/elasticstack/src/test/java/org/jclouds/elasticstack/compute/ElasticStackComputeServiceLiveTest.java b/apis/elasticstack/src/test/java/org/jclouds/elasticstack/compute/ElasticStackComputeServiceLiveTest.java index 98af64bd1c..82829c622f 100644 --- a/apis/elasticstack/src/test/java/org/jclouds/elasticstack/compute/ElasticStackComputeServiceLiveTest.java +++ b/apis/elasticstack/src/test/java/org/jclouds/elasticstack/compute/ElasticStackComputeServiceLiveTest.java @@ -24,13 +24,12 @@ import org.jclouds.compute.internal.BaseComputeServiceLiveTest; import org.jclouds.sshj.config.SshjSshClientModule; import org.testng.annotations.Test; -import com.google.common.collect.ImmutableMap; import com.google.inject.Module; /** * @author Adrian Cole */ -@Test(groups = "live") +@Test(groups = "live", testName = "ElasticStackComputeServiceLiveTest") public class ElasticStackComputeServiceLiveTest extends BaseComputeServiceLiveTest { public ElasticStackComputeServiceLiveTest() { @@ -42,13 +41,6 @@ public class ElasticStackComputeServiceLiveTest extends BaseComputeServiceLiveTe return new SshjSshClientModule(); } - // elasticstack does not support metadata - @Override - protected void checkUserMetadataInNodeEquals(NodeMetadata node, ImmutableMap userMetadata) { - assert node.getUserMetadata().equals(ImmutableMap. of()) : String.format( - "node userMetadata did not match %s %s", userMetadata, node); - } - @Override public void testOptionToNotBlock() { // start call is blocking anyway. @@ -56,6 +48,6 @@ public class ElasticStackComputeServiceLiveTest extends BaseComputeServiceLiveTe protected void checkResponseEqualsHostname(ExecResponse execResponse, NodeMetadata node1) { // hostname is not predictable based on node metadata - assert execResponse.getOutput().trim().equals("ubuntu"); + assert execResponse.getOutput().trim().equals("ubuntu") : execResponse.getOutput(); } } diff --git a/apis/eucalyptus/pom.xml b/apis/eucalyptus/pom.xml index 67848f5203..853552197f 100644 --- a/apis/eucalyptus/pom.xml +++ b/apis/eucalyptus/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.api diff --git a/apis/filesystem/pom.xml b/apis/filesystem/pom.xml index 108724bd8a..2276667ec3 100644 --- a/apis/filesystem/pom.xml +++ b/apis/filesystem/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.api diff --git a/apis/filesystem/src/main/java/org/jclouds/filesystem/config/FilesystemBlobStoreContextModule.java b/apis/filesystem/src/main/java/org/jclouds/filesystem/config/FilesystemBlobStoreContextModule.java index 1eb4079fcb..e72f769268 100644 --- a/apis/filesystem/src/main/java/org/jclouds/filesystem/config/FilesystemBlobStoreContextModule.java +++ b/apis/filesystem/src/main/java/org/jclouds/filesystem/config/FilesystemBlobStoreContextModule.java @@ -22,8 +22,8 @@ import org.jclouds.blobstore.AsyncBlobStore; import org.jclouds.blobstore.BlobRequestSigner; import org.jclouds.blobstore.BlobStore; import org.jclouds.blobstore.LocalAsyncBlobStore; +import org.jclouds.blobstore.LocalBlobRequestSigner; import org.jclouds.blobstore.LocalStorageStrategy; -import org.jclouds.blobstore.TransientBlobRequestSigner; import org.jclouds.blobstore.attr.ConsistencyModel; import org.jclouds.blobstore.config.BlobStoreMapModule; import org.jclouds.blobstore.config.BlobStoreObjectModule; @@ -60,7 +60,7 @@ public class FilesystemBlobStoreContextModule extends AbstractModule { bind(BlobUtils.class).to(FileSystemBlobUtilsImpl.class); bind(FilesystemBlobKeyValidator.class).to(FilesystemBlobKeyValidatorImpl.class); bind(FilesystemContainerNameValidator.class).to(FilesystemContainerNameValidatorImpl.class); - bind(BlobRequestSigner.class).to(TransientBlobRequestSigner.class); + bind(BlobRequestSigner.class).to(LocalBlobRequestSigner.class); } } diff --git a/apis/filesystem/src/main/java/org/jclouds/filesystem/strategy/internal/FilesystemStorageStrategyImpl.java b/apis/filesystem/src/main/java/org/jclouds/filesystem/strategy/internal/FilesystemStorageStrategyImpl.java index 71beb86f0e..7cb61e8de1 100644 --- a/apis/filesystem/src/main/java/org/jclouds/filesystem/strategy/internal/FilesystemStorageStrategyImpl.java +++ b/apis/filesystem/src/main/java/org/jclouds/filesystem/strategy/internal/FilesystemStorageStrategyImpl.java @@ -21,11 +21,8 @@ package org.jclouds.filesystem.strategy.internal; import static com.google.common.base.Preconditions.checkNotNull; import java.io.File; -import java.io.FileFilter; -import java.io.FileOutputStream; import java.io.IOException; import java.util.HashSet; -import java.util.Iterator; import java.util.Set; import javax.annotation.Resource; @@ -34,11 +31,11 @@ import javax.inject.Named; import javax.inject.Provider; import com.google.common.base.Throwables; -import com.google.common.io.Closeables; +import com.google.common.collect.ImmutableList; +import com.google.common.io.ByteStreams; import com.google.common.io.Files; import org.apache.commons.io.FileUtils; -import org.apache.commons.io.filefilter.DirectoryFileFilter; import org.jclouds.blobstore.LocalStorageStrategy; import org.jclouds.blobstore.domain.Blob; import org.jclouds.blobstore.domain.BlobBuilder; @@ -93,14 +90,17 @@ public class FilesystemStorageStrategyImpl implements LocalStorageStrategy { @Override public Iterable getAllContainerNames() { - Iterable containers = new Iterable() { - @Override - public Iterator iterator() { - return new FileIterator(buildPathStartingFromBaseDir(), DirectoryFileFilter.INSTANCE); + File[] files = new File(buildPathStartingFromBaseDir()).listFiles(); + if (files == null) { + return ImmutableList.of(); + } + ImmutableList.Builder containers = ImmutableList.builder(); + for (File file : files) { + if (file.isDirectory()) { + containers.add(file.getName()); } - }; - - return containers; + } + return containers.build(); } @Override @@ -201,14 +201,13 @@ public class FilesystemStorageStrategyImpl implements LocalStorageStrategy { filesystemContainerNameValidator.validate(containerName); filesystemBlobKeyValidator.validate(blobKey); File outputFile = getFileForBlobKey(containerName, blobKey); - FileOutputStream output = null; try { Files.createParentDirs(outputFile); if (payload.getRawContent() instanceof File) Files.copy((File) payload.getRawContent(), outputFile); else { - output = new FileOutputStream(outputFile); - payload.writeTo(output); + payload = Payloads.newPayload(ByteStreams.toByteArray(payload)); + Files.copy(payload, outputFile); } Payloads.calculateMD5(payload, crypto.md5()); String eTag = CryptoStreams.hex(payload.getContentMetadata().getContentMD5()); @@ -219,7 +218,6 @@ public class FilesystemStorageStrategyImpl implements LocalStorageStrategy { } throw ex; } finally { - Closeables.closeQuietly(output); payload.release(); } } @@ -435,39 +433,6 @@ public class FilesystemStorageStrategyImpl implements LocalStorageStrategy { return folder; } - private class FileIterator implements Iterator { - int currentFileIndex = 0; - File[] children = new File[0]; - File currentFile = null; - - public FileIterator(String fileName, FileFilter filter) { - File file = new File(fileName); - if (file.exists() && file.isDirectory()) { - children = file.listFiles(filter); - } - } - - @Override - public boolean hasNext() { - return currentFileIndex < children.length; - } - - @Override - public String next() { - currentFile = children[currentFileIndex++]; - return currentFile.getName(); - } - - @Override - public void remove() { - if (currentFile != null && currentFile.exists()) { - if (!currentFile.delete()) { - throw new RuntimeException("An error occurred deleting " + currentFile.getName()); - } - } - } - } - private void populateBlobKeysInContainer(File directory, Set blobNames) { File[] children = directory.listFiles(); for (File child : children) { diff --git a/apis/filesystem/src/test/java/org/jclouds/filesystem/FilesystemAsyncBlobStoreTest.java b/apis/filesystem/src/test/java/org/jclouds/filesystem/FilesystemAsyncBlobStoreTest.java index 2aa607970c..ce8095deba 100644 --- a/apis/filesystem/src/test/java/org/jclouds/filesystem/FilesystemAsyncBlobStoreTest.java +++ b/apis/filesystem/src/test/java/org/jclouds/filesystem/FilesystemAsyncBlobStoreTest.java @@ -37,7 +37,6 @@ import java.util.Properties; import java.util.Set; import org.apache.commons.io.FileUtils; -import org.apache.commons.io.IOUtils; import org.jclouds.ContextBuilder; import org.jclouds.blobstore.BlobRequestSigner; import org.jclouds.blobstore.BlobStore; @@ -56,13 +55,15 @@ import org.jclouds.filesystem.reference.FilesystemConstants; import org.jclouds.filesystem.utils.TestUtils; import org.jclouds.http.HttpRequest; import org.jclouds.io.InputSuppliers; +import org.jclouds.io.Payload; import org.jclouds.io.payloads.PhantomPayload; import org.jclouds.io.payloads.StringPayload; +import org.jclouds.util.Strings2; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; -import org.testng.annotations.DataProvider; import org.testng.annotations.Test; +import com.google.common.base.Charsets; import com.google.common.io.ByteStreams; import com.google.common.io.Closeables; import com.google.common.io.Files; @@ -649,7 +650,7 @@ public class FilesystemAsyncBlobStoreTest { assertNotNull(metadata.getUserMetadata(), "No blob UserMetadata"); assertEquals(metadata.getUserMetadata().size(), 0, "Wrong blob UserMetadata"); // metadata.getLastModified() - File file = new File(TARGET_CONTAINER_NAME + File.separator + BLOB_KEY); + File file = new File(TARGET_CONTAINER_NAME, BLOB_KEY); assertEquals(metadata.getContentMetadata().getContentLength(), Long.valueOf(file.length()), "Wrong blob size"); } @@ -731,39 +732,39 @@ public class FilesystemAsyncBlobStoreTest { public void testRanges() throws IOException { blobStore.createContainerInLocation(null, CONTAINER_NAME); - String payload = "abcdefgh"; - InputStream is; - Blob blob = blobStore.blobBuilder("test").payload(new StringPayload(payload)).build(); + String input = "abcdefgh"; + Payload payload; + Blob blob = blobStore.blobBuilder("test").payload(new StringPayload(input)).build(); blobStore.putBlob(CONTAINER_NAME, blob); GetOptions getOptionsRangeStartAt = new GetOptions(); getOptionsRangeStartAt.startAt(1); Blob blobRangeStartAt = blobStore.getBlob(CONTAINER_NAME, blob.getMetadata().getName(), getOptionsRangeStartAt); - is = blobRangeStartAt.getPayload().getInput(); + payload = blobRangeStartAt.getPayload(); try { - assertEquals("bcdefgh", IOUtils.toString(is)); + assertEquals(input.substring(1), Strings2.toString(payload)); } finally { - Closeables.closeQuietly(is); + Closeables.closeQuietly(payload); } GetOptions getOptionsRangeTail = new GetOptions(); getOptionsRangeTail.tail(3); Blob blobRangeTail = blobStore.getBlob(CONTAINER_NAME, blob.getMetadata().getName(), getOptionsRangeTail); - is = blobRangeTail.getPayload().getInput(); + payload = blobRangeTail.getPayload(); try { - assertEquals("fgh", IOUtils.toString(is)); + assertEquals(input.substring(5), Strings2.toString(payload)); } finally { - Closeables.closeQuietly(is); + Closeables.closeQuietly(payload); } GetOptions getOptionsFragment = new GetOptions(); getOptionsFragment.range(4, 6); Blob blobFragment = blobStore.getBlob(CONTAINER_NAME, blob.getMetadata().getName(), getOptionsFragment); - is = blobFragment.getPayload().getInput(); + payload = blobFragment.getPayload(); try { - assertEquals("efg", IOUtils.toString(is)); + assertEquals(input.substring(4, 7), Strings2.toString(payload)); } finally { - Closeables.closeQuietly(is); + Closeables.closeQuietly(payload); } } diff --git a/apis/filesystem/src/test/java/org/jclouds/filesystem/strategy/internal/FilesystemStorageStrategyImplTest.java b/apis/filesystem/src/test/java/org/jclouds/filesystem/strategy/internal/FilesystemStorageStrategyImplTest.java index f3790c14a7..8f83d35779 100644 --- a/apis/filesystem/src/test/java/org/jclouds/filesystem/strategy/internal/FilesystemStorageStrategyImplTest.java +++ b/apis/filesystem/src/test/java/org/jclouds/filesystem/strategy/internal/FilesystemStorageStrategyImplTest.java @@ -44,9 +44,9 @@ import org.jclouds.filesystem.predicates.validators.internal.FilesystemBlobKeyVa import org.jclouds.filesystem.predicates.validators.internal.FilesystemContainerNameValidatorImpl; import org.jclouds.filesystem.utils.TestUtils; import org.jclouds.io.payloads.FilePayload; +import org.jclouds.io.payloads.InputStreamPayload; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; -import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import com.google.common.io.ByteStreams; @@ -348,17 +348,36 @@ public class FilesystemStorageStrategyImplTest { } public void testWritePayloadOnFile() throws IOException { - String blobKey; - File sourceFile; - FilePayload filePayload; - - blobKey = TestUtils.createRandomBlobKey("writePayload-", ".img"); - sourceFile = TestUtils.getImageForBlobPayload(); - filePayload = new FilePayload(sourceFile); + String blobKey = TestUtils.createRandomBlobKey("writePayload-", ".img"); + File sourceFile = TestUtils.getImageForBlobPayload(); + FilePayload filePayload = new FilePayload(sourceFile); Blob blob = storageStrategy.newBlob(blobKey); blob.setPayload(filePayload); + // write files storageStrategy.putBlob(CONTAINER_NAME, blob); + + // verify that the files is equal + File blobFullPath = new File(TARGET_CONTAINER_NAME, blobKey); + InputSupplier expectedInput = + Files.newInputStreamSupplier(sourceFile); + InputSupplier actualInput = + Files.newInputStreamSupplier(blobFullPath); + assertTrue(ByteStreams.equal(expectedInput, actualInput), + "Files are not equal"); + } + + public void testWritePayloadOnFileInputStream() throws IOException { + String blobKey = TestUtils.createRandomBlobKey("writePayload-", ".img"); + File sourceFile = TestUtils.getImageForBlobPayload(); + InputStreamPayload fileInputStreamPayload = new InputStreamPayload( + new FileInputStream(sourceFile)); + Blob blob = storageStrategy.newBlob(blobKey); + blob.setPayload(fileInputStreamPayload); + + // write files + storageStrategy.putBlob(CONTAINER_NAME, blob); + // verify that the files is equal File blobFullPath = new File(TARGET_CONTAINER_NAME, blobKey); InputSupplier expectedInput = diff --git a/apis/filesystem/src/test/java/org/jclouds/filesystem/utils/TestUtils.java b/apis/filesystem/src/test/java/org/jclouds/filesystem/utils/TestUtils.java index 594281ae88..f068f25df9 100644 --- a/apis/filesystem/src/test/java/org/jclouds/filesystem/utils/TestUtils.java +++ b/apis/filesystem/src/test/java/org/jclouds/filesystem/utils/TestUtils.java @@ -23,10 +23,14 @@ import static org.testng.Assert.assertTrue; import java.io.File; import java.io.IOException; +import java.util.Iterator; import java.util.HashSet; import java.util.Set; import java.util.UUID; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Iterators; + import org.apache.commons.io.FileUtils; /** @@ -37,20 +41,17 @@ import org.apache.commons.io.FileUtils; public class TestUtils { private static final String TARGET_RESOURCE_DIR = "." + File.separator + "src" + File.separator + "test" + File.separator + "resources" + File.separator; + /** All the files available for the tests */ - private static String[] imageResource = new String[]{ - TARGET_RESOURCE_DIR + "image1.jpg", - TARGET_RESOURCE_DIR + "image2.jpg", - TARGET_RESOURCE_DIR + "image3.jpg", - TARGET_RESOURCE_DIR + "image4.jpg" - }; - private static int imageResourceIndex = 0; + private static final Iterator IMAGE_RESOURCES = + Iterators.cycle(ImmutableList.of( + new File(TARGET_RESOURCE_DIR + "image1.jpg"), + new File(TARGET_RESOURCE_DIR + "image2.jpg"), + new File(TARGET_RESOURCE_DIR + "image3.jpg"), + new File(TARGET_RESOURCE_DIR + "image4.jpg"))); public static final String TARGET_BASE_DIR = "." + File.separator + "target" + File.separator + "basedir" + File.separator; - public static final Object[][] NO_INVOCATIONS = new Object[0][0]; - public static final Object[][] SINGLE_NO_ARG_INVOCATION = new Object[][] { new Object[0] }; - public static boolean isWindowsOs() { return System.getProperty("os.name", "").toLowerCase().contains("windows"); } @@ -194,8 +195,6 @@ public class TestUtils { * @return */ public static File getImageForBlobPayload() { - String fileName = imageResource[imageResourceIndex++]; - if (imageResourceIndex >= imageResource.length) imageResourceIndex = 0; - return new File(fileName); + return IMAGE_RESOURCES.next(); } } diff --git a/apis/nova/pom.xml b/apis/nova/pom.xml index 5d6ac6c25c..6e8d855ee4 100644 --- a/apis/nova/pom.xml +++ b/apis/nova/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.api diff --git a/apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Resource.java b/apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Resource.java index 53ff322bfb..ba6c597e64 100644 --- a/apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Resource.java +++ b/apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Resource.java @@ -20,7 +20,6 @@ package org.jclouds.openstack.nova.domain; import static com.google.common.base.Preconditions.checkNotNull; -import java.beans.ConstructorProperties; import java.net.URI; import java.net.URISyntaxException; import java.util.List; diff --git a/apis/openstack-keystone/pom.xml b/apis/openstack-keystone/pom.xml index 2399ae689f..e9b205d45b 100644 --- a/apis/openstack-keystone/pom.xml +++ b/apis/openstack-keystone/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.api diff --git a/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/KeystoneApi.java b/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/KeystoneApi.java index 125b9ec155..2e83b5afb2 100644 --- a/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/KeystoneApi.java +++ b/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/KeystoneApi.java @@ -21,8 +21,6 @@ package org.jclouds.openstack.keystone.v2_0; import java.util.concurrent.TimeUnit; import org.jclouds.concurrent.Timeout; -import org.jclouds.javax.annotation.Nullable; -import org.jclouds.location.functions.ZoneToEndpoint; import org.jclouds.openstack.keystone.v2_0.domain.ApiMetadata; import org.jclouds.openstack.keystone.v2_0.features.ServiceApi; import org.jclouds.openstack.keystone.v2_0.features.TenantApi; @@ -30,7 +28,6 @@ import org.jclouds.openstack.keystone.v2_0.features.TokenApi; import org.jclouds.openstack.keystone.v2_0.features.UserApi; import org.jclouds.openstack.v2_0.features.ExtensionApi; import org.jclouds.rest.annotations.Delegate; -import org.jclouds.rest.annotations.EndpointParam; import com.google.common.base.Optional; diff --git a/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/config/KeystoneProperties.java b/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/config/KeystoneProperties.java index fc5146f8f5..5ae8f6aa8d 100644 --- a/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/config/KeystoneProperties.java +++ b/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/config/KeystoneProperties.java @@ -22,47 +22,55 @@ import org.jclouds.openstack.v2_0.ServiceType; /** * Configuration properties and constants used in Keystone connections. - * + * * @author Adrian Cole */ public interface KeystoneProperties { /** * Type of credentials used to log into the auth service. - * + * *

valid values

*
    *
  • apiAccessKeyCredentials
  • *
  • passwordCredentials
  • *
- * + * * @see CredentialTypes - * @see
*/ public static final String CREDENTIAL_TYPE = "jclouds.keystone.credential-type"; - + /** - * set this property to specify the tenant id of the authenticated user. Cannot be used simultaneously with {@link #TENANT_NAME} + * set this property to specify the tenant id of the authenticated user. + * Cannot be used simultaneously with {@link #TENANT_NAME} + * * @see openstack docs */ public static final String TENANT_ID = "jclouds.keystone.tenant-id"; - + /** - * set this property to specify the tenant name of the authenticated user. Cannot be used simultaneously with {@link #TENANT_ID} + * set this property to specify the tenant name of the authenticated user. + * Cannot be used simultaneously with {@link #TENANT_ID} + * * @see openstack docs */ public static final String TENANT_NAME = "jclouds.keystone.tenant-name"; - + /** - * set this property to {@code true} to designate that the service requires explicit specification of either {@link #TENANT_NAME} or {@link #TENANT_ID} + * set this property to {@code true} to designate that the service requires + * explicit specification of either {@link #TENANT_NAME} or + * {@link #TENANT_ID} + * * @see openstack docs */ public static final String REQUIRES_TENANT = "jclouds.keystone.requires-tenant"; - + /** * type of the keystone service. ex. {@code compute} - * + * * @see ServiceType */ public static final String SERVICE_TYPE = "jclouds.keystone.service-type"; diff --git a/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/config/KeystoneRestClientModule.java b/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/config/KeystoneRestClientModule.java index f473be2466..c77f70b1f9 100644 --- a/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/config/KeystoneRestClientModule.java +++ b/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/config/KeystoneRestClientModule.java @@ -73,7 +73,7 @@ import com.google.inject.assistedinject.FactoryModuleBuilder; /** * Configures the Keystone connection. - * + * * @author Adam Lowe */ @ConfiguresRestClient @@ -88,6 +88,7 @@ public class KeystoneRestClientModule aliases() { @@ -143,7 +144,7 @@ public class KeystoneRestClientModule>() { @Override public Set get() { - return keystoneApi.get().getExtensionApi().listExtensions(); + return keystoneApi.get().getExtensionApi().list(); } }))); } diff --git a/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/domain/Access.java b/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/domain/Access.java index ca5745afc2..7e8f58a8c1 100644 --- a/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/domain/Access.java +++ b/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/domain/Access.java @@ -23,18 +23,22 @@ import static com.google.common.base.Preconditions.checkNotNull; import java.beans.ConstructorProperties; import java.util.Set; +import org.jclouds.javax.annotation.Nullable; + import com.google.common.base.Objects; import com.google.common.base.Objects.ToStringHelper; +import com.google.common.collect.ForwardingSet; import com.google.common.collect.ImmutableSet; /** * TODO * * @author Adrian Cole - * @see + * @see */ -public class Access implements Comparable { +public class Access extends ForwardingSet implements Comparable { public static Builder builder() { return new ConcreteBuilder(); @@ -44,12 +48,12 @@ public class Access implements Comparable { return new ConcreteBuilder().fromAccess(this); } - public static abstract class Builder> { + public static abstract class Builder> { protected abstract T self(); protected Token token; protected User user; - protected Set serviceCatalog = ImmutableSet.of(); + protected ImmutableSet.Builder serviceCatalog = ImmutableSet. builder(); /** * @see Access#getToken() @@ -68,26 +72,44 @@ public class Access implements Comparable { } /** - * @see Access#getServiceCatalog() + * @see Access#delegate() */ - public T serviceCatalog(Set serviceCatalog) { - this.serviceCatalog = ImmutableSet.copyOf(checkNotNull(serviceCatalog, "serviceCatalog")); + public T service(Service service) { + this.serviceCatalog.add(service); return self(); } + /** + * @see Access#delegate() + */ + public T services(Iterable serviceCatalog) { + this.serviceCatalog.addAll(serviceCatalog); + return self(); + } + + /** + * @see #services(Iterable) + */ + @Deprecated + public T serviceCatalog(Set serviceCatalog) { + this.serviceCatalog.addAll(serviceCatalog); + return self(); + } + + /** + * @see #services(Iterable) + */ + @Deprecated public T serviceCatalog(Service... in) { return serviceCatalog(ImmutableSet.copyOf(in)); } public Access build() { - return new Access(token, user, serviceCatalog); + return new Access(token, user, serviceCatalog.build()); } public T fromAccess(Access in) { - return this - .token(in.getToken()) - .user(in.getUser()) - .serviceCatalog(in.getServiceCatalog()); + return this.token(in.getToken()).user(in.getUser()).services(in); } } @@ -102,13 +124,11 @@ public class Access implements Comparable { private final User user; private final Set serviceCatalog; - @ConstructorProperties({ - "token", "user", "serviceCatalog" - }) - protected Access(Token token, User user, Set serviceCatalog) { + @ConstructorProperties({ "token", "user", "serviceCatalog" }) + protected Access(Token token, User user, @Nullable Set serviceCatalog) { this.token = checkNotNull(token, "token"); this.user = checkNotNull(user, "user"); - this.serviceCatalog = ImmutableSet.copyOf(checkNotNull(serviceCatalog, "serviceCatalog")); + this.serviceCatalog = serviceCatalog == null ? ImmutableSet. of() : ImmutableSet.copyOf(serviceCatalog); } /** @@ -126,8 +146,9 @@ public class Access implements Comparable { } /** - * TODO + * Please access the service catalog via normal collection mechanisms */ + @Deprecated public Set getServiceCatalog() { return this.serviceCatalog; } @@ -139,24 +160,25 @@ public class Access implements Comparable { @Override public boolean equals(Object obj) { - if (this == obj) return true; - if (obj == null || getClass() != obj.getClass()) return false; + if (this == obj) + return true; + if (obj == null || getClass() != obj.getClass()) + return false; Access that = Access.class.cast(obj); - return Objects.equal(this.token, that.token) - && Objects.equal(this.user, that.user) + return Objects.equal(this.token, that.token) && Objects.equal(this.user, that.user) && Objects.equal(this.serviceCatalog, that.serviceCatalog); } protected ToStringHelper string() { - return Objects.toStringHelper(this) - .add("token", token).add("user", user).add("serviceCatalog", serviceCatalog); + return Objects.toStringHelper(this).omitNullValues().add("token", token).add("user", user) + .add("serviceCatalog", serviceCatalog); } @Override public String toString() { return string().toString(); } - + @Override public int compareTo(Access that) { if (that == null) @@ -166,4 +188,9 @@ public class Access implements Comparable { return this.token.compareTo(that.token); } + @Override + protected Set delegate() { + return serviceCatalog; + } + } diff --git a/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/domain/Endpoint.java b/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/domain/Endpoint.java index fe5e38d98d..9846c37aa7 100644 --- a/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/domain/Endpoint.java +++ b/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/domain/Endpoint.java @@ -27,13 +27,15 @@ import com.google.common.base.Objects; import com.google.common.base.Objects.ToStringHelper; /** - * An network-accessible address, usually described by URL, where a service may be accessed. If - * using an extension for templates, you can create an endpoint template, which represents the - * templates of all the consumable services that are available across the regions. + * An network-accessible address, usually described by URL, where a service may + * be accessed. If using an extension for templates, you can create an endpoint + * template, which represents the templates of all the consumable services that + * are available across the regions. * * @author AdrianCole - * @see + * @see */ public class Endpoint { @@ -45,9 +47,10 @@ public class Endpoint { return new ConcreteBuilder().fromEndpoint(this); } - public static abstract class Builder> { + public static abstract class Builder> { protected abstract T self(); + protected String id; protected String versionId; protected String region; protected URI publicURL; @@ -57,6 +60,15 @@ public class Endpoint { protected URI versionInfo; protected URI versionList; + + /** + * @see Endpoint#getId() + */ + public T id(String id) { + this.id = id; + return self(); + } + /** * @see Endpoint#getVersionId() */ @@ -113,6 +125,41 @@ public class Endpoint { return self(); } + /** + * @see Endpoint#getPublicURL() + */ + public T publicURL(String publicURL) { + return publicURL(URI.create(publicURL)); + } + + /** + * @see Endpoint#getInternalURL() + */ + public T internalURL(String internalURL) { + return internalURL(URI.create(internalURL)); + } + + /** + * @see Endpoint#getAdminURL() + */ + public T adminURL(String adminURL) { + return adminURL(URI.create(adminURL)); + } + + /** + * @see Endpoint#getVersionInfo() + */ + public T versionInfo(String versionInfo) { + return versionInfo(URI.create(versionInfo)); + } + + /** + * @see Endpoint#getVersionList() + */ + public T versionList(String versionList) { + return versionList(URI.create(versionList)); + } + /** * @see Endpoint#getTenantId() */ @@ -122,19 +169,14 @@ public class Endpoint { } public Endpoint build() { - return new Endpoint(null, versionId, region, publicURL, internalURL, adminURL, versionInfo, versionList, null, tenantId); + return new Endpoint(id, versionId, region, publicURL, internalURL, adminURL, versionInfo, versionList, null, + tenantId); } public T fromEndpoint(Endpoint in) { - return this - .versionId(in.getVersionId()) - .region(in.getRegion()) - .publicURL(in.getPublicURL()) - .internalURL(in.getInternalURL()) - .adminURL(in.getAdminURL()) - .versionInfo(in.getVersionInfo()) - .versionList(in.getVersionList()) - .tenantId(in.getTenantId()); + return this.versionId(in.getVersionId()).region(in.getRegion()).publicURL(in.getPublicURL()) + .internalURL(in.getInternalURL()).adminURL(in.getAdminURL()).versionInfo(in.getVersionInfo()) + .versionList(in.getVersionList()).tenantId(in.getTenantId()); } } @@ -145,22 +187,26 @@ public class Endpoint { } } - private final String versionId; + private final String id; + private final String tenantId; private final String region; private final URI publicURL; private final URI internalURL; private final URI adminURL; + + // fields not defined in + // https://github.com/openstack/keystone/blob/master/keystone/service.py + private final String versionId; private final URI versionInfo; private final URI versionList; - private final String tenantId; - @ConstructorProperties({ - "id", "versionId", "region", "publicURL", "internalURL", "adminURL", "versionInfo", "versionList", "tenantName", "tenantId" - }) - protected Endpoint(@Nullable String id, @Nullable String versionId, @Nullable String region, @Nullable URI publicURL, - @Nullable URI internalURL, @Nullable URI adminURL, @Nullable URI versionInfo, @Nullable URI versionList, - @Nullable String tenantName, @Nullable String tenantId) { - this.versionId = versionId != null ? versionId : id; + @ConstructorProperties({ "id", "versionId", "region", "publicURL", "internalURL", "adminURL", "versionInfo", + "versionList", "tenantName", "tenantId" }) + protected Endpoint(@Nullable String id, @Nullable String versionId, @Nullable String region, + @Nullable URI publicURL, @Nullable URI internalURL, @Nullable URI adminURL, @Nullable URI versionInfo, + @Nullable URI versionList, @Nullable String tenantName, @Nullable String tenantId) { + this.id = id; + this.versionId = versionId; this.tenantId = tenantId != null ? tenantId : tenantName; this.region = region; this.publicURL = publicURL; @@ -171,10 +217,26 @@ public class Endpoint { } /** - * When providing an ID, it is assumed that the endpoint exists in the current OpenStack - * deployment + * When providing an ID, it is assumed that the endpoint exists in the + * current OpenStack deployment * - * @return the versionId of the endpoint in the current OpenStack deployment, or null if not specified + * @return the id of the endpoint in the current OpenStack deployment, or + * null if not specified + */ + @Nullable + public String getId() { + return this.id; + } + + /** + * + *

Note

+ * + * This is not defined in
KeyStone, rather only in Rackspace */ @Nullable public String getVersionId() { @@ -213,11 +275,31 @@ public class Endpoint { return this.adminURL; } + /** + * + *

Note

+ * + * This is not defined in KeyStone, rather only in Rackspace + */ @Nullable public URI getVersionInfo() { return this.versionInfo; } + /** + * + *

Note

+ * + * This is not defined in KeyStone, rather only in Rackspace + */ @Nullable public URI getVersionList() { return this.versionList; @@ -233,28 +315,29 @@ public class Endpoint { @Override public int hashCode() { - return Objects.hashCode(versionId, region, publicURL, internalURL, adminURL, versionInfo, versionList, tenantId); + return Objects.hashCode(id, versionId, region, publicURL, internalURL, adminURL, versionInfo, versionList, + tenantId); } @Override public boolean equals(Object obj) { - if (this == obj) return true; - if (obj == null || getClass() != obj.getClass()) return false; + if (this == obj) + return true; + if (obj == null || getClass() != obj.getClass()) + return false; Endpoint that = Endpoint.class.cast(obj); - return Objects.equal(this.versionId, that.versionId) - && Objects.equal(this.region, that.region) - && Objects.equal(this.publicURL, that.publicURL) - && Objects.equal(this.internalURL, that.internalURL) - && Objects.equal(this.adminURL, that.adminURL) - && Objects.equal(this.versionInfo, that.versionInfo) - && Objects.equal(this.versionList, that.versionList) + return Objects.equal(this.id, that.id) && Objects.equal(this.versionId, that.versionId) + && Objects.equal(this.region, that.region) && Objects.equal(this.publicURL, that.publicURL) + && Objects.equal(this.internalURL, that.internalURL) && Objects.equal(this.adminURL, that.adminURL) + && Objects.equal(this.versionInfo, that.versionInfo) && Objects.equal(this.versionList, that.versionList) && Objects.equal(this.tenantId, that.tenantId); } protected ToStringHelper string() { - return Objects.toStringHelper(this) - .add("versionId", versionId).add("region", region).add("publicURL", publicURL).add("internalURL", internalURL) - .add("adminURL", adminURL).add("versionInfo", versionInfo).add("versionList", versionList).add("tenantId", tenantId); + return Objects.toStringHelper(this).omitNullValues().add("id", id).add("versionId", versionId) + .add("region", region).add("publicURL", publicURL).add("internalURL", internalURL) + .add("adminURL", adminURL).add("versionInfo", versionInfo).add("versionList", versionList) + .add("tenantId", tenantId); } @Override diff --git a/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/domain/PaginatedCollection.java b/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/domain/PaginatedCollection.java new file mode 100644 index 0000000000..2d8758025d --- /dev/null +++ b/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/domain/PaginatedCollection.java @@ -0,0 +1,87 @@ +/* + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.keystone.v2_0.domain; + +import static org.jclouds.http.utils.Queries.parseQueryToMap; + +import java.util.Collection; +import java.util.Iterator; + +import org.jclouds.collect.IterableWithMarker; +import org.jclouds.openstack.v2_0.domain.Link; + +import com.google.common.annotations.Beta; +import com.google.common.base.Function; +import com.google.common.base.Optional; +import com.google.common.base.Predicate; +import com.google.common.collect.FluentIterable; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Iterables; + +/** + * base class for a paginated collection in openstack + * + * @see + * docs + * @author Adrian Cole + */ +@Beta +public class PaginatedCollection extends IterableWithMarker { + + @SuppressWarnings({ "rawtypes", "unchecked" }) + public static final PaginatedCollection EMPTY = new PaginatedCollection(ImmutableSet.of(), ImmutableSet.of()); + + private Iterable resources; + private Iterable links; + + protected PaginatedCollection(Iterable resources, Iterable links) { + this.resources = resources != null ? resources : ImmutableSet. of(); + this.links = links != null ? links : ImmutableSet. of(); + } + + @Override + public Iterator iterator() { + return resources.iterator(); + } + + /** + * links that relate to this collection + */ + public Iterable getLinks() { + return links; + } + + @Override + public Optional nextMarker() { + return FluentIterable.from(getLinks()).filter(new Predicate() { + @Override + public boolean apply(Link link) { + return Link.Relation.NEXT == link.getRelation(); + } + }).transform(new Function>() { + @Override + public Optional apply(Link link) { + Collection markers = parseQueryToMap(link.getHref().getRawQuery()).get("marker"); + return Optional. fromNullable(markers == null ? null : Iterables.get(markers, 0)); + } + }).first().or(Optional.absent()); + } + +} diff --git a/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/domain/Role.java b/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/domain/Role.java index 88381659b1..700e4a75e5 100644 --- a/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/domain/Role.java +++ b/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/domain/Role.java @@ -195,7 +195,7 @@ public class Role { } protected ToStringHelper string() { - return Objects.toStringHelper(this) + return Objects.toStringHelper(this).omitNullValues() .add("id", id).add("name", name).add("description", description).add("serviceId", serviceId).add("tenantId", tenantId); } diff --git a/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/domain/Service.java b/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/domain/Service.java index 23a1bffbab..4198992815 100644 --- a/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/domain/Service.java +++ b/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/domain/Service.java @@ -25,7 +25,6 @@ import java.util.Set; import com.google.common.base.Objects; import com.google.common.base.Objects.ToStringHelper; -import com.google.common.collect.ComparisonChain; import com.google.common.collect.ForwardingSet; import com.google.common.collect.ImmutableSet; @@ -38,7 +37,7 @@ import com.google.common.collect.ImmutableSet; * @see */ -public class Service extends ForwardingSet implements Comparable { +public class Service extends ForwardingSet { public static Builder builder() { return new ConcreteBuilder(); @@ -53,7 +52,7 @@ public class Service extends ForwardingSet implements Comparable endpoints = ImmutableSet.of(); + protected ImmutableSet.Builder endpoints = ImmutableSet.builder(); /** * @see Service#getType() @@ -72,26 +71,38 @@ public class Service extends ForwardingSet implements Comparable endpoints) { - this.endpoints = ImmutableSet.copyOf(checkNotNull(endpoints, "endpoints")); + public T endpoint(Endpoint endpoint) { + this.endpoints.add(endpoint); return self(); } + /** + * @see Service#delegate() + */ + public T endpoints(Iterable endpoints) { + this.endpoints.addAll(endpoints); + return self(); + } + + /** + * @see #endpoints(Iterable) + */ + @Deprecated public T endpoints(Endpoint... in) { return endpoints(ImmutableSet.copyOf(in)); } public Service build() { - return new Service(type, name, endpoints); + return new Service(type, name, endpoints.build()); } public T fromService(Service in) { return this .type(in.getType()) .name(in.getName()) - .endpoints(in.getEndpoints()); + .endpoints(in); } } private static class ConcreteBuilder extends Builder { @@ -131,8 +142,9 @@ public class Service extends ForwardingSet implements Comparable getEndpoints() { return this.endpoints; } @@ -153,7 +165,7 @@ public class Service extends ForwardingSet implements Comparable implements Comparable delegate() { return endpoints; diff --git a/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/domain/Tenant.java b/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/domain/Tenant.java index 14100567f1..c5b9853d30 100644 --- a/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/domain/Tenant.java +++ b/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/domain/Tenant.java @@ -148,7 +148,7 @@ public class Tenant { } protected ToStringHelper string() { - return Objects.toStringHelper(this) + return Objects.toStringHelper(this).omitNullValues() .add("id", id).add("name", name).add("description", description); } diff --git a/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/domain/User.java b/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/domain/User.java index 82fbcd58cf..18aeacd4ef 100644 --- a/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/domain/User.java +++ b/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/domain/User.java @@ -27,6 +27,7 @@ import org.jclouds.javax.annotation.Nullable; import com.google.common.base.Objects; import com.google.common.base.Objects.ToStringHelper; +import com.google.common.collect.ForwardingSet; import com.google.common.collect.ImmutableSet; /** @@ -37,10 +38,10 @@ import com.google.common.collect.ImmutableSet; * tenant. * * @author Adrian Cole - * @see */ -public class User { +public class User extends ForwardingSet { public static Builder builder() { return new ConcreteBuilder(); @@ -55,7 +56,7 @@ public class User { protected String id; protected String name; - protected Set roles = ImmutableSet.of(); + protected ImmutableSet.Builder roles = ImmutableSet. builder(); /** * @see User#getId() @@ -74,26 +75,38 @@ public class User { } /** - * @see User#getRoles() + * @see User#delegate() */ - public T roles(Set roles) { - this.roles = ImmutableSet.copyOf(checkNotNull(roles, "roles")); + public T role(Role role) { + this.roles.add(role); return self(); } + /** + * @see User#delegate() + */ + public T roles(Iterable roles) { + this.roles.addAll(roles); + return self(); + } + + /** + * @see #roles(Iterable) + */ + @Deprecated public T roles(Role... in) { return roles(ImmutableSet.copyOf(in)); } public User build() { - return new User(id, name, roles); + return new User(id, name, roles.build()); } public T fromUser(User in) { return this .id(in.getId()) .name(in.getName()) - .roles(in.getRoles()); + .roles(in); } } @@ -114,7 +127,7 @@ public class User { protected User(String id, String name, @Nullable Set roles) { this.id = checkNotNull(id, "id"); this.name = checkNotNull(name, "name"); - this.roles = roles == null ? ImmutableSet.of() : ImmutableSet.copyOf(checkNotNull(roles, "roles")); + this.roles = roles == null ? ImmutableSet.of() : ImmutableSet.copyOf(roles); } /** @@ -134,8 +147,10 @@ public class User { } /** + * Please use User as a Set * @return the roles assigned to the user */ + @Deprecated public Set getRoles() { return this.roles; } @@ -156,7 +171,7 @@ public class User { } protected ToStringHelper string() { - return Objects.toStringHelper(this) + return Objects.toStringHelper(this).omitNullValues() .add("id", id).add("name", name).add("roles", roles); } @@ -165,4 +180,9 @@ public class User { return string().toString(); } + @Override + protected Set delegate() { + return roles; + } + } diff --git a/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/features/TenantApi.java b/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/features/TenantApi.java index 68a0118f43..813826155c 100644 --- a/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/features/TenantApi.java +++ b/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/features/TenantApi.java @@ -18,11 +18,13 @@ */ package org.jclouds.openstack.keystone.v2_0.features; -import java.util.Set; import java.util.concurrent.TimeUnit; +import org.jclouds.collect.PagedIterable; import org.jclouds.concurrent.Timeout; +import org.jclouds.openstack.keystone.v2_0.domain.PaginatedCollection; import org.jclouds.openstack.keystone.v2_0.domain.Tenant; +import org.jclouds.openstack.v2_0.options.PaginationOptions; /** * Provides synchronous access to the KeyStone Tenant API. @@ -40,7 +42,9 @@ public interface TenantApi { /** * The operation returns a list of tenants which the current token provides access to. */ - Set list(); + PagedIterable list(); + + PaginatedCollection list(PaginationOptions options); /** * Retrieve information about a tenant, by tenant ID diff --git a/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/features/TenantAsyncApi.java b/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/features/TenantAsyncApi.java index 43b1ebefe9..b2476cebe9 100644 --- a/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/features/TenantAsyncApi.java +++ b/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/features/TenantAsyncApi.java @@ -18,8 +18,6 @@ */ package org.jclouds.openstack.keystone.v2_0.features; -import java.util.Set; - import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.Path; @@ -27,14 +25,22 @@ import javax.ws.rs.PathParam; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; +import org.jclouds.collect.PagedIterable; +import org.jclouds.openstack.keystone.v2_0.domain.PaginatedCollection; import org.jclouds.openstack.keystone.v2_0.domain.Tenant; import org.jclouds.openstack.keystone.v2_0.filters.AuthenticateRequest; +import org.jclouds.openstack.keystone.v2_0.functions.ReturnEmptyPaginatedCollectionOnNotFoundOr404; +import org.jclouds.openstack.keystone.v2_0.functions.internal.ParseTenants; +import org.jclouds.openstack.keystone.v2_0.functions.internal.ParseTenants.ToPagedIterable; +import org.jclouds.openstack.v2_0.options.PaginationOptions; import org.jclouds.openstack.v2_0.services.Identity; import org.jclouds.rest.annotations.ExceptionParser; import org.jclouds.rest.annotations.RequestFilters; +import org.jclouds.rest.annotations.ResponseParser; import org.jclouds.rest.annotations.SelectJson; import org.jclouds.rest.annotations.SkipEncoding; -import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404; +import org.jclouds.rest.annotations.Transform; +import org.jclouds.rest.functions.ReturnEmptyPagedIterableOnNotFoundOr404; import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; import com.google.common.util.concurrent.ListenableFuture; @@ -57,12 +63,22 @@ public interface TenantAsyncApi { * @see TenantApi#list() */ @GET - @SelectJson("tenants") @Consumes(MediaType.APPLICATION_JSON) @Path("/tenants") @RequestFilters(AuthenticateRequest.class) - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> list(); + @ResponseParser(ParseTenants.class) + @Transform(ToPagedIterable.class) + @ExceptionParser(ReturnEmptyPagedIterableOnNotFoundOr404.class) + ListenableFuture> list(); + + /** @see TenantApi#list(PaginationOptions) */ + @GET + @Consumes(MediaType.APPLICATION_JSON) + @Path("/tenants") + @RequestFilters(AuthenticateRequest.class) + @ResponseParser(ParseTenants.class) + @ExceptionParser(ReturnEmptyPaginatedCollectionOnNotFoundOr404.class) + ListenableFuture> list(PaginationOptions options); /** @see TenantApi#get(String) */ @GET diff --git a/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/features/UserApi.java b/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/features/UserApi.java index 619ecf0153..ff7499914d 100644 --- a/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/features/UserApi.java +++ b/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/features/UserApi.java @@ -21,9 +21,12 @@ package org.jclouds.openstack.keystone.v2_0.features; import java.util.Set; import java.util.concurrent.TimeUnit; +import org.jclouds.collect.PagedIterable; import org.jclouds.concurrent.Timeout; +import org.jclouds.openstack.keystone.v2_0.domain.PaginatedCollection; import org.jclouds.openstack.keystone.v2_0.domain.Role; import org.jclouds.openstack.keystone.v2_0.domain.User; +import org.jclouds.openstack.v2_0.options.PaginationOptions; import com.google.common.annotations.Beta; @@ -48,7 +51,9 @@ public interface UserApi { * * @return the list of users */ - Set list(); + PagedIterable list(); + + PaginatedCollection list(PaginationOptions options); /** * Retrieve information about a user, by user ID diff --git a/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/features/UserAsyncApi.java b/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/features/UserAsyncApi.java index d7ba6a8bcb..f91d61f3b1 100644 --- a/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/features/UserAsyncApi.java +++ b/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/features/UserAsyncApi.java @@ -27,14 +27,23 @@ import javax.ws.rs.PathParam; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; +import org.jclouds.collect.PagedIterable; +import org.jclouds.openstack.keystone.v2_0.domain.PaginatedCollection; import org.jclouds.openstack.keystone.v2_0.domain.Role; import org.jclouds.openstack.keystone.v2_0.domain.User; import org.jclouds.openstack.keystone.v2_0.filters.AuthenticateRequest; +import org.jclouds.openstack.keystone.v2_0.functions.ReturnEmptyPaginatedCollectionOnNotFoundOr404; +import org.jclouds.openstack.keystone.v2_0.functions.internal.ParseUsers; +import org.jclouds.openstack.keystone.v2_0.functions.internal.ParseUsers.ToPagedIterable; +import org.jclouds.openstack.v2_0.options.PaginationOptions; import org.jclouds.openstack.v2_0.services.Identity; import org.jclouds.rest.annotations.ExceptionParser; import org.jclouds.rest.annotations.RequestFilters; +import org.jclouds.rest.annotations.ResponseParser; import org.jclouds.rest.annotations.SelectJson; import org.jclouds.rest.annotations.SkipEncoding; +import org.jclouds.rest.annotations.Transform; +import org.jclouds.rest.functions.ReturnEmptyPagedIterableOnNotFoundOr404; import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404; import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; @@ -43,10 +52,10 @@ import com.google.common.util.concurrent.ListenableFuture; /** * Provides asynchronous access to User via their REST API. *

- * + * * @see UserApi * @see * @author Adam Lowe */ @@ -54,14 +63,26 @@ import com.google.common.util.concurrent.ListenableFuture; @SkipEncoding({ '/', '=' }) public interface UserAsyncApi { - /** @see UserApi#list() */ + /** + * @see UserApi#list() + */ @GET - @SelectJson("users") @Consumes(MediaType.APPLICATION_JSON) @Path("/users") @RequestFilters(AuthenticateRequest.class) - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> list(); + @ResponseParser(ParseUsers.class) + @Transform(ToPagedIterable.class) + @ExceptionParser(ReturnEmptyPagedIterableOnNotFoundOr404.class) + ListenableFuture> list(); + + /** @see UserApi#list(PaginationOptions) */ + @GET + @Consumes(MediaType.APPLICATION_JSON) + @Path("/users") + @RequestFilters(AuthenticateRequest.class) + @ResponseParser(ParseUsers.class) + @ExceptionParser(ReturnEmptyPaginatedCollectionOnNotFoundOr404.class) + ListenableFuture> list(PaginationOptions options); /** @see UserApi#get(String) */ @GET @@ -71,7 +92,7 @@ public interface UserAsyncApi { @RequestFilters(AuthenticateRequest.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class) ListenableFuture get(@PathParam("userId") String userId); - + /** @see UserApi#getByName(String) */ @GET @SelectJson("user") @@ -80,7 +101,7 @@ public interface UserAsyncApi { @RequestFilters(AuthenticateRequest.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class) ListenableFuture getByName(@QueryParam("name") String userName); - + /** @see UserApi#listRolesOfUser(String) */ @GET @SelectJson("roles") @@ -97,5 +118,6 @@ public interface UserAsyncApi { @Path("/tenants/{tenantId}/users/{userId}/roles") @RequestFilters(AuthenticateRequest.class) @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> listRolesOfUserOnTenant(@PathParam("userId") String userId, @PathParam("tenantId") String tenantId); + ListenableFuture> listRolesOfUserOnTenant(@PathParam("userId") String userId, + @PathParam("tenantId") String tenantId); } diff --git a/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/functions/ReturnEmptyPaginatedCollectionOnNotFoundOr404.java b/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/functions/ReturnEmptyPaginatedCollectionOnNotFoundOr404.java new file mode 100644 index 0000000000..e454d20ea3 --- /dev/null +++ b/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/functions/ReturnEmptyPaginatedCollectionOnNotFoundOr404.java @@ -0,0 +1,58 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.keystone.v2_0.functions; + +import static com.google.common.base.Preconditions.checkNotNull; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.http.functions.ReturnTrueOn404; +import org.jclouds.openstack.keystone.v2_0.domain.PaginatedCollection; +import org.jclouds.rest.ResourceNotFoundException; + +import com.google.common.base.Function; +import com.google.common.base.Throwables; +import com.google.common.collect.Iterables; + +/** + * + * @author Adrian Cole + */ +@Singleton +public class ReturnEmptyPaginatedCollectionOnNotFoundOr404 implements Function { + private final ReturnTrueOn404 rto404; + + @Inject + private ReturnEmptyPaginatedCollectionOnNotFoundOr404(ReturnTrueOn404 rto404) { + this.rto404 = checkNotNull(rto404, "rto404"); + } + + public Object apply(Exception from) { + Iterable throwables = Iterables.filter(Throwables.getCausalChain(from), + ResourceNotFoundException.class); + if (Iterables.size(throwables) >= 1) { + return PaginatedCollection.EMPTY; + } else if (rto404.apply(from)) { + return PaginatedCollection.EMPTY; + } + throw Throwables.propagate(from); + } + +} diff --git a/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/functions/internal/ParseTenants.java b/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/functions/internal/ParseTenants.java new file mode 100644 index 0000000000..bd1f867961 --- /dev/null +++ b/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/functions/internal/ParseTenants.java @@ -0,0 +1,96 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.keystone.v2_0.functions.internal; + +import static com.google.common.base.Preconditions.checkNotNull; +import static org.jclouds.openstack.v2_0.options.PaginationOptions.Builder.marker; + +import java.beans.ConstructorProperties; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.collect.IterableWithMarker; +import org.jclouds.collect.internal.CallerArg0ToPagedIterable; +import org.jclouds.http.functions.ParseJson; +import org.jclouds.json.Json; +import org.jclouds.openstack.keystone.v2_0.KeystoneApi; +import org.jclouds.openstack.keystone.v2_0.domain.PaginatedCollection; +import org.jclouds.openstack.keystone.v2_0.domain.Tenant; +import org.jclouds.openstack.keystone.v2_0.features.TenantApi; +import org.jclouds.openstack.keystone.v2_0.functions.internal.ParseTenants.Tenants; +import org.jclouds.openstack.v2_0.domain.Link; + +import com.google.common.annotations.Beta; +import com.google.common.base.Function; +import com.google.inject.TypeLiteral; + +/** + * boiler plate until we determine a better way + * + * @author Adrian Cole + */ +@Beta +@Singleton +public class ParseTenants extends ParseJson> { + static class Tenants extends PaginatedCollection { + + @ConstructorProperties({ "tenants", "tenants_links" }) + protected Tenants(Iterable tenants, Iterable tenants_links) { + super(tenants, tenants_links); + } + + } + + @Inject + public ParseTenants(Json json) { + super(json, new TypeLiteral>() { + }); + } + + public static class ToPagedIterable extends CallerArg0ToPagedIterable { + + private final KeystoneApi api; + + @Inject + protected ToPagedIterable(KeystoneApi api) { + this.api = checkNotNull(api, "api"); + } + + @Override + protected Function> markerToNextForCallingArg0(final String ignored) { + final TenantApi tenantApi = api.getTenantApi().get(); + return new Function>() { + + @SuppressWarnings("unchecked") + @Override + public IterableWithMarker apply(Object input) { + return IterableWithMarker.class.cast(tenantApi.list(marker(input.toString()))); + } + + @Override + public String toString() { + return "listTenants()"; + } + }; + } + + } + +} diff --git a/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/functions/internal/ParseUsers.java b/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/functions/internal/ParseUsers.java new file mode 100644 index 0000000000..ad4dfb3041 --- /dev/null +++ b/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/functions/internal/ParseUsers.java @@ -0,0 +1,96 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.keystone.v2_0.functions.internal; + +import static com.google.common.base.Preconditions.checkNotNull; +import static org.jclouds.openstack.v2_0.options.PaginationOptions.Builder.marker; + +import java.beans.ConstructorProperties; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.collect.IterableWithMarker; +import org.jclouds.collect.internal.CallerArg0ToPagedIterable; +import org.jclouds.http.functions.ParseJson; +import org.jclouds.json.Json; +import org.jclouds.openstack.keystone.v2_0.KeystoneApi; +import org.jclouds.openstack.keystone.v2_0.domain.PaginatedCollection; +import org.jclouds.openstack.keystone.v2_0.domain.User; +import org.jclouds.openstack.keystone.v2_0.features.UserApi; +import org.jclouds.openstack.keystone.v2_0.functions.internal.ParseUsers.Users; +import org.jclouds.openstack.v2_0.domain.Link; + +import com.google.common.annotations.Beta; +import com.google.common.base.Function; +import com.google.inject.TypeLiteral; + +/** + * boiler plate until we determine a better way + * + * @author Adrian Cole + */ +@Beta +@Singleton +public class ParseUsers extends ParseJson> { + static class Users extends PaginatedCollection { + + @ConstructorProperties({ "users", "users_links" }) + protected Users(Iterable users, Iterable users_links) { + super(users, users_links); + } + + } + + @Inject + public ParseUsers(Json json) { + super(json, new TypeLiteral>() { + }); + } + + public static class ToPagedIterable extends CallerArg0ToPagedIterable { + + private final KeystoneApi api; + + @Inject + protected ToPagedIterable(KeystoneApi api) { + this.api = checkNotNull(api, "api"); + } + + @Override + protected Function> markerToNextForCallingArg0(final String ignored) { + final UserApi userApi = api.getUserApi().get(); + return new Function>() { + + @SuppressWarnings("unchecked") + @Override + public IterableWithMarker apply(Object input) { + return IterableWithMarker.class.cast(userApi.list(marker(input.toString()))); + } + + @Override + public String toString() { + return "listUsers()"; + } + }; + } + + } + +} diff --git a/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/suppliers/LocationIdToURIFromAccessForTypeAndVersion.java b/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/suppliers/LocationIdToURIFromAccessForTypeAndVersion.java index a316ee1b62..a4b968f54c 100644 --- a/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/suppliers/LocationIdToURIFromAccessForTypeAndVersion.java +++ b/apis/openstack-keystone/src/main/java/org/jclouds/openstack/keystone/v2_0/suppliers/LocationIdToURIFromAccessForTypeAndVersion.java @@ -18,29 +18,63 @@ */ package org.jclouds.openstack.keystone.v2_0.suppliers; +import static com.google.common.collect.Iterables.any; +import static com.google.common.collect.Iterables.concat; +import static com.google.common.collect.Iterables.size; +import static com.google.common.collect.Iterables.tryFind; +import static com.google.common.collect.Multimaps.index; + import java.net.URI; +import java.util.Collection; import java.util.Map; import java.util.NoSuchElementException; -import java.util.Set; -import javax.inject.Inject; +import javax.annotation.Resource; import javax.inject.Singleton; +import org.jclouds.javax.annotation.Nullable; +import org.jclouds.logging.Logger; import org.jclouds.openstack.keystone.v2_0.domain.Access; import org.jclouds.openstack.keystone.v2_0.domain.Endpoint; import org.jclouds.openstack.keystone.v2_0.domain.Service; import org.jclouds.openstack.keystone.v2_0.functions.EndpointToSupplierURI; +import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Function; +import com.google.common.base.Optional; import com.google.common.base.Predicate; import com.google.common.base.Supplier; +import com.google.common.collect.FluentIterable; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableMap.Builder; import com.google.common.collect.Iterables; import com.google.common.collect.Maps; -import com.google.common.collect.Sets; +import com.google.common.collect.Multimap; +import com.google.inject.Inject; import com.google.inject.assistedinject.Assisted; @Singleton public class LocationIdToURIFromAccessForTypeAndVersion implements Supplier>> { + + public static interface Factory { + /** + * + * @param apiType + * type of the api, according to the provider. ex. + * {@code compute} {@code object-store} + * @param apiVersion + * version of the api, or null if not available + * @return locations mapped to default uri + * @throws NoSuchElementException + * if the {@code apiType} is not present in the catalog + */ + LocationIdToURIFromAccessForTypeAndVersion createForApiTypeAndVersion(@Assisted("apiType") String apiType, + @Nullable @Assisted("apiVersion") String apiVersion) throws NoSuchElementException; + } + + @Resource + protected Logger logger = Logger.NULL; + protected final Supplier access; protected final EndpointToSupplierURI endpointToSupplierURI; protected final Function endpointToLocationId; @@ -49,8 +83,8 @@ public class LocationIdToURIFromAccessForTypeAndVersion implements Supplier access, - EndpointToSupplierURI endpointToSupplierURI, Function endpointToLocationId, - @Assisted("apiType") String apiType, @Assisted("apiVersion") String apiVersion) { + EndpointToSupplierURI endpointToSupplierURI, Function endpointToLocationId, + @Assisted("apiType") String apiType, @Nullable @Assisted("apiVersion") String apiVersion) { this.access = access; this.endpointToSupplierURI = endpointToSupplierURI; this.endpointToLocationId = endpointToLocationId; @@ -60,38 +94,112 @@ public class LocationIdToURIFromAccessForTypeAndVersion implements Supplier> get() { - Access accessResponse = access.get(); - Set services = Sets.filter(accessResponse.getServiceCatalog(), new Predicate() { + FluentIterable services = FluentIterable.from(access.get()).filter(apiTypeEquals); + if (services.toImmutableSet().size() == 0) + throw new NoSuchElementException(String.format("apiType %s not found in catalog %s", apiType, services)); - @Override - public boolean apply(Service input) { - return input.getType().equals(apiType); - } + Iterable endpoints = concat(services); - }); - if (services.size() == 0) - throw new NoSuchElementException(String.format("apiType %s not found in catalog %s", apiType, - accessResponse.getServiceCatalog())); + if (size(endpoints) == 0) + throw new NoSuchElementException( + String.format("no endpoints for apiType %s in services %s", apiType, services)); - Iterable endpoints = Iterables.filter(Iterables.concat(services), new Predicate() { + boolean checkVersionId = any(endpoints, versionAware); - @Override - public boolean apply(Endpoint input) { - if (input.getVersionId() == null) { - return true; - } - return input.getVersionId().equals(apiVersion); - } - - }); - - if (Iterables.size(endpoints) == 0) - throw new NoSuchElementException(String.format( + Multimap locationToEndpoints = index(endpoints, endpointToLocationId); + Map locationToEndpoint; + if (checkVersionId && apiVersion != null) { + locationToEndpoint = refineToVersionSpecificEndpoint(locationToEndpoints); + if (locationToEndpoint.size() == 0) + throw new NoSuchElementException(String.format( "no endpoints for apiType %s are of version %s, or version agnostic: %s", apiType, apiVersion, - services)); + locationToEndpoints)); + } else { + locationToEndpoint = firstEndpointInLocation(locationToEndpoints); + } - Map locationIdToEndpoint = Maps.uniqueIndex(endpoints, endpointToLocationId); - return Maps.transformValues(locationIdToEndpoint, endpointToSupplierURI); + logger.debug("endpoints for apiType %s and version %s: %s", apiType, apiVersion, locationToEndpoints); + return Maps.transformValues(locationToEndpoint, endpointToSupplierURI); + } + + @VisibleForTesting + Map firstEndpointInLocation(Multimap locationToEndpoints) { + Builder locationToEndpointBuilder = ImmutableMap. builder(); + for (String locationId : locationToEndpoints.keySet()) { + Collection endpoints = locationToEndpoints.get(locationId); + switch (endpoints.size()) { + case 0: + logNoEndpointsInLocation(locationId); + break; + default: + locationToEndpointBuilder.put(locationId, Iterables.get(endpoints, 0)); + } + } + return locationToEndpointBuilder.build(); + } + + @VisibleForTesting + Map refineToVersionSpecificEndpoint(Multimap locationToEndpoints) { + Builder locationToEndpointBuilder = ImmutableMap. builder(); + for (String locationId : locationToEndpoints.keySet()) { + Collection endpoints = locationToEndpoints.get(locationId); + switch (endpoints.size()) { + case 0: + logNoEndpointsInLocation(locationId); + break; + default: + putIfPresent(locationId, strictMatchEndpointVersion(endpoints, locationId), locationToEndpointBuilder); + } + + } + return locationToEndpointBuilder.build(); + } + + /** + * Prioritizes endpoint.versionId over endpoint.id when matching + */ + private Optional strictMatchEndpointVersion(Iterable endpoints, String locationId) { + Optional endpointOfVersion = tryFind(endpoints, apiVersionEqualsVersionId); + if (!endpointOfVersion.isPresent()) + logger.debug("no endpoints of apiType %s matched expected version %s in location %s: %s", apiType, apiVersion, + locationId, endpoints); + return endpointOfVersion; + } + + private void logNoEndpointsInLocation(String locationId) { + logger.debug("no endpoints found for apiType %s in location %s", apiType, locationId); + } + + private final Predicate apiVersionEqualsVersionId = new Predicate() { + + @Override + public boolean apply(Endpoint input) { + return input.getVersionId().equals(apiVersion); + } + + }; + + private final Predicate versionAware = new Predicate() { + + @Override + public boolean apply(Endpoint input) { + return input.getVersionId() != null; + } + + }; + + private final Predicate apiTypeEquals = new Predicate() { + + @Override + public boolean apply(Service input) { + return input.getType().equals(apiType); + } + + }; + + private static void putIfPresent(K key, Optional value, Builder builder) { + if (value.isPresent()) + builder.put(key, value.get()); } @Override diff --git a/apis/openstack-keystone/src/main/java/org/jclouds/openstack/v2_0/domain/Link.java b/apis/openstack-keystone/src/main/java/org/jclouds/openstack/v2_0/domain/Link.java index 61e45b6aef..e5e82ff551 100644 --- a/apis/openstack-keystone/src/main/java/org/jclouds/openstack/v2_0/domain/Link.java +++ b/apis/openstack-keystone/src/main/java/org/jclouds/openstack/v2_0/domain/Link.java @@ -25,18 +25,17 @@ import java.net.URI; 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.base.Optional; /** * For convenience, resources contain links to themselves. This allows a api to easily obtain a * resource URIs rather than to construct them. - * + * * @author AdrianCole * @see + * /> */ public class Link { /** @@ -57,9 +56,17 @@ public class Link { */ DESCRIBEDBY, /** - * an alternate representation of the resource. For example, an OpenStack Compute image may - * have an alternate representation in the OpenStack Image service. + * Indicates that the link's context is a part of a series, and that the next in the series is + * the link target. */ + NEXT, + + /** + * Indicates that the link's context is a part of a series, and that the previous in the + * series is the link target. + */ + PREVIOUS, + ALTERNATE, /** * the value returned by the OpenStack service was not recognized. @@ -83,80 +90,67 @@ public class Link { return new Link(relation, null, href); } - public static Link create(Relation relation,String type, URI href) { - return new Link(relation, type, href); + public static Link create(Relation relation, String type, URI href) { + return new Link(relation, Optional.fromNullable(type), href); } - public static Builder builder() { - return new ConcreteBuilder(); + public static Builder builder() { + return new Builder(); } - public Builder toBuilder() { - return new ConcreteBuilder().fromLink(this); + public Builder toBuilder() { + return builder().fromLink(this); } - public static abstract class Builder> { - protected abstract T self(); + public static class Builder { protected Link.Relation relation; - protected String type; + protected Optional type = Optional.absent(); protected URI href; /** * @see Link#getRelation() */ - public T relation(Link.Relation relation) { + public Builder relation(Link.Relation relation) { this.relation = relation; - return self(); + return this; } /** * @see Link#getType() */ - public T type(String type) { - this.type = type; - return self(); + public Builder type(String type) { + this.type = Optional.fromNullable(type); + return this; } /** * @see Link#getHref() */ - public T href(URI href) { + public Builder href(URI href) { this.href = href; - return self(); + return this; } public Link build() { return new Link(relation, type, href); } - public T fromLink(Link in) { - return this - .relation(in.getRelation()) - .type(in.getType()) - .href(in.getHref()); - } - } - - private static class ConcreteBuilder extends Builder { - @Override - protected ConcreteBuilder self() { - return this; + public Builder fromLink(Link in) { + return this.relation(in.getRelation()).type(in.getType().orNull()).href(in.getHref()); } } @Named("rel") private final Link.Relation relation; - private final String type; + private final Optional type; private final URI href; - @ConstructorProperties({ - "rel", "type", "href" - }) - protected Link(Link.Relation relation, @Nullable String type, URI href) { - this.relation = checkNotNull(relation, "relation"); - this.type = type; + @ConstructorProperties({ "rel", "type", "href" }) + protected Link(Link.Relation relation, Optional type, URI href) { this.href = checkNotNull(href, "href"); + this.relation = checkNotNull(relation, "relation of %s", href); + this.type = (type == null) ? Optional. absent() : type; } /** @@ -167,7 +161,7 @@ public class Link { * of the resource. For example, an OpenStack Compute image may have an alternate representation * in the OpenStack Image service. Note that the type attribute here is used to provide a hint as * to the type of representation to expect when following the link. - * + * * @return the relation of the resource in the current OpenStack deployment */ public Link.Relation getRelation() { @@ -177,8 +171,7 @@ public class Link { /** * @return the type of the resource or null if not specified */ - @Nullable - public String getType() { + public Optional getType() { return this.type; } @@ -196,17 +189,18 @@ public class Link { @Override public boolean equals(Object obj) { - if (this == obj) return true; - if (obj == null || getClass() != obj.getClass()) return false; + if (this == obj) + return true; + if (obj == null || getClass() != obj.getClass()) + return false; Link that = Link.class.cast(obj); - return Objects.equal(this.relation, that.relation) - && Objects.equal(this.type, that.type) - && Objects.equal(this.href, that.href); + return Objects.equal(this.relation, that.relation) && Objects.equal(this.type, that.type) + && Objects.equal(this.href, that.href); } protected ToStringHelper string() { - return Objects.toStringHelper(this) - .add("relation", relation).add("type", type).add("href", href); + return Objects.toStringHelper(this).omitNullValues().add("relation", relation).add("type", type.orNull()) + .add("href", href); } @Override diff --git a/apis/openstack-keystone/src/main/java/org/jclouds/openstack/v2_0/features/ExtensionApi.java b/apis/openstack-keystone/src/main/java/org/jclouds/openstack/v2_0/features/ExtensionApi.java index e8f746ea2a..7705ca498e 100644 --- a/apis/openstack-keystone/src/main/java/org/jclouds/openstack/v2_0/features/ExtensionApi.java +++ b/apis/openstack-keystone/src/main/java/org/jclouds/openstack/v2_0/features/ExtensionApi.java @@ -28,7 +28,7 @@ import org.jclouds.openstack.v2_0.domain.Extension; * Provides asynchronous access to Extensions via their REST API. *

* - * @see ExtensionApi + * @see ExtensionAsyncApi * @see @@ -42,7 +42,7 @@ public interface ExtensionApi { * * @return all extensions */ - Set listExtensions(); + Set list(); /** * Extensions may also be queried individually by their unique alias. @@ -51,6 +51,6 @@ public interface ExtensionApi { * id of the extension * @return extension or null if not found */ - Extension getExtensionByAlias(String alias); + Extension get(String alias); } diff --git a/apis/openstack-keystone/src/main/java/org/jclouds/openstack/v2_0/features/ExtensionAsyncApi.java b/apis/openstack-keystone/src/main/java/org/jclouds/openstack/v2_0/features/ExtensionAsyncApi.java index c6b957f807..ef88c60272 100644 --- a/apis/openstack-keystone/src/main/java/org/jclouds/openstack/v2_0/features/ExtensionAsyncApi.java +++ b/apis/openstack-keystone/src/main/java/org/jclouds/openstack/v2_0/features/ExtensionAsyncApi.java @@ -52,23 +52,23 @@ import com.google.common.util.concurrent.ListenableFuture; public interface ExtensionAsyncApi { /** - * @see ExtensionApi#listExtensions + * @see ExtensionApi#list */ @GET @SelectJson("extensions") @Consumes(MediaType.APPLICATION_JSON) @Path("/extensions") @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> listExtensions(); + ListenableFuture> list(); /** - * @see ExtensionApi#getExtensionByAlias + * @see ExtensionApi#get */ @GET @SelectJson("extension") @Consumes(MediaType.APPLICATION_JSON) @Path("/extensions/{alias}") @ExceptionParser(ReturnNullOnNotFoundOr404.class) - ListenableFuture getExtensionByAlias(@PathParam("alias") String id); + ListenableFuture get(@PathParam("alias") String id); } diff --git a/apis/openstack-keystone/src/main/java/org/jclouds/openstack/v2_0/options/BaseListOptions.java b/apis/openstack-keystone/src/main/java/org/jclouds/openstack/v2_0/options/PaginationOptions.java similarity index 59% rename from apis/openstack-keystone/src/main/java/org/jclouds/openstack/v2_0/options/BaseListOptions.java rename to apis/openstack-keystone/src/main/java/org/jclouds/openstack/v2_0/options/PaginationOptions.java index f21f1d047d..6e68c61aee 100644 --- a/apis/openstack-keystone/src/main/java/org/jclouds/openstack/v2_0/options/BaseListOptions.java +++ b/apis/openstack-keystone/src/main/java/org/jclouds/openstack/v2_0/options/PaginationOptions.java @@ -28,30 +28,26 @@ import org.jclouds.http.options.BaseHttpRequestOptions; /** * Options used to control paginated results (aka list commands). * - * @see + * @see * @author Adrian Cole */ -public class BaseListOptions extends BaseHttpRequestOptions { - public static final BaseListOptions NONE = new BaseListOptions(); - +public class PaginationOptions extends BaseHttpRequestOptions { /** * Only return objects changed since this time. */ - public BaseListOptions changesSince(Date ifModifiedSince) { - this.queryParameters.put("changes-since", checkNotNull(ifModifiedSince, "ifModifiedSince") - .getTime() - / 1000 + ""); + public PaginationOptions changesSince(Date ifModifiedSince) { + this.queryParameters.put("changes-since", checkNotNull(ifModifiedSince, "ifModifiedSince").getTime() / 1000 + ""); return this; } /** - * Indicates where to begin listing. The list will only include objects that occur after the - * offset. This is convenient for pagination: To get the next page of results use the last result - * number of the current page + current page offset as the offset. + * The marker parameter is the ID of the last item in the previous list. Items are sorted by + * create time in descending order. When a create time is not available they are sorted by ID. */ - public BaseListOptions startAt(long offset) { - checkState(offset >= 0, "offset must be >= 0"); - queryParameters.put("offset", Long.toString(checkNotNull(offset, "offset"))); + public PaginationOptions marker(String marker) { + queryParameters.put("marker", checkNotNull(marker, "marker")); return this; } @@ -63,7 +59,7 @@ public class BaseListOptions extends BaseHttpRequestOptions { *

* Note that list operations never return itemNotFound (404) faults. */ - public BaseListOptions maxResults(int limit) { + public PaginationOptions limit(int limit) { checkState(limit >= 0, "limit must be >= 0"); checkState(limit <= 10000, "limit must be <= 10000"); queryParameters.put("limit", Integer.toString(limit)); @@ -73,26 +69,26 @@ public class BaseListOptions extends BaseHttpRequestOptions { public static class Builder { /** - * @see BaseListOptions#startAt(long) + * @see PaginationOptions#marker(String) */ - public static BaseListOptions startAt(long prefix) { - BaseListOptions options = new BaseListOptions(); - return options.startAt(prefix); + public static PaginationOptions marker(String marker) { + PaginationOptions options = new PaginationOptions(); + return options.marker(marker); } /** - * @see BaseListOptions#maxResults + * @see PaginationOptions#limit */ - public static BaseListOptions maxResults(int maxKeys) { - BaseListOptions options = new BaseListOptions(); - return options.maxResults(maxKeys); + public static PaginationOptions limit(int limit) { + PaginationOptions options = new PaginationOptions(); + return options.limit(limit); } /** - * @see BaseListOptions#changesSince(Date) + * @see PaginationOptions#changesSince(Date) */ - public static BaseListOptions changesSince(Date since) { - BaseListOptions options = new BaseListOptions(); + public static PaginationOptions changesSince(Date since) { + PaginationOptions options = new PaginationOptions(); return options.changesSince(since); } diff --git a/apis/openstack-keystone/src/main/java/org/jclouds/openstack/v2_0/predicates/LinkPredicates.java b/apis/openstack-keystone/src/main/java/org/jclouds/openstack/v2_0/predicates/LinkPredicates.java index dc5b12505f..85b8cf9877 100644 --- a/apis/openstack-keystone/src/main/java/org/jclouds/openstack/v2_0/predicates/LinkPredicates.java +++ b/apis/openstack-keystone/src/main/java/org/jclouds/openstack/v2_0/predicates/LinkPredicates.java @@ -91,7 +91,7 @@ public class LinkPredicates { return new Predicate() { @Override public boolean apply(Link link) { - return type.equals(link.getType()); + return type.equals(link.getType().orNull()); } @Override diff --git a/apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/features/TenantApiExpectTest.java b/apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/features/TenantApiExpectTest.java index 094d657221..6d37a3de07 100644 --- a/apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/features/TenantApiExpectTest.java +++ b/apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/features/TenantApiExpectTest.java @@ -31,6 +31,7 @@ import org.jclouds.http.HttpResponse; import org.jclouds.openstack.keystone.v2_0.KeystoneApi; import org.jclouds.openstack.keystone.v2_0.domain.Tenant; import org.jclouds.openstack.keystone.v2_0.internal.BaseKeystoneRestApiExpectTest; +import org.jclouds.openstack.v2_0.options.PaginationOptions; import org.jclouds.rest.AuthorizationException; import org.testng.annotations.Test; @@ -47,7 +48,10 @@ public class TenantApiExpectTest extends BaseKeystoneRestApiExpectTest expectedTenants = ImmutableSet.of(Tenant.builder().name("demo").id("05d1dc7af71646deba64cfc17b81bec0") + .build(), Tenant.builder().name("admin").id("7aa2e17ec29f44d193c48feaba0852cc").build()); + public void testListTenants() { TenantApi api = requestsSendResponses( keystoneAuthWithUsernameAndPassword, @@ -56,16 +60,28 @@ public class TenantApiExpectTest extends BaseKeystoneRestApiExpectTest tenants = api.list(); + + assertEquals(api.list().concat().toImmutableSet(), expectedTenants); + } + + public void testListTenantsPage() { + TenantApi api = requestsSendResponses( + keystoneAuthWithUsernameAndPassword, + responseWithKeystoneAccess, + authenticatedGET().endpoint(endpoint + "/v2.0/tenants").build(), + HttpResponse.builder().statusCode(200).payload( + payloadFromResourceWithContentType("/tenant_list.json", APPLICATION_JSON)).build()) + .getTenantApi().get(); + Set tenants = api.list(new PaginationOptions()).toImmutableSet(); assertNotNull(tenants); assertFalse(tenants.isEmpty()); - Set expected = ImmutableSet.of(Tenant.builder().name("demo").id("05d1dc7af71646deba64cfc17b81bec0") - .build(), Tenant.builder().name("admin").id("7aa2e17ec29f44d193c48feaba0852cc").build()); - - assertEquals(tenants, expected); + assertEquals(tenants, expectedTenants); } + // this is not a compatible format of json per: + // http://docs.openstack.org/api/openstack-identity-service/2.0/content/Paginated_Collections-d1e325.html + @Test(enabled = false) public void testListTenantsATT() { TenantApi api = requestsSendResponses( keystoneAuthWithUsernameAndPassword, @@ -74,15 +90,15 @@ public class TenantApiExpectTest extends BaseKeystoneRestApiExpectTest tenants = api.list(); - assertNotNull(tenants); - assertFalse(tenants.isEmpty()); Set expected = ImmutableSet.of(Tenant.builder().name("this-is-a-test").id("14").description("None").build()); - assertEquals(tenants, expected); + assertEquals(api.list().concat().toImmutableSet(), expected); } + // this is not a compatible format of json per: + // http://docs.openstack.org/api/openstack-identity-service/2.0/content/Paginated_Collections-d1e325.html + @Test(enabled = false) public void testListTenantsFailNotFound() { TenantApi api = requestsSendResponses(keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, authenticatedGET().endpoint(endpoint + "/v2.0/tenants").build(), HttpResponse.builder().statusCode(404).build()) diff --git a/apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/features/TenantApiLiveTest.java b/apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/features/TenantApiLiveTest.java index 8c09e41c95..e3a40336d7 100644 --- a/apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/features/TenantApiLiveTest.java +++ b/apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/features/TenantApiLiveTest.java @@ -38,7 +38,7 @@ public class TenantApiLiveTest extends BaseKeystoneApiLiveTest { public void testTenants() { TenantApi api = keystoneContext.getApi().getTenantApi().get(); - Set result = api.list(); + Set result = api.list().concat().toImmutableSet(); assertNotNull(result); assertFalse(result.isEmpty()); @@ -56,7 +56,7 @@ public class TenantApiLiveTest extends BaseKeystoneApiLiveTest { TenantApi api = keystoneContext.getApi().getTenantApi().get(); - for (Tenant tenant : api.list()) { + for (Tenant tenant : api.list().concat()) { Tenant aTenant = api.getByName(tenant.getName()); assertNotNull(aTenant, "get returned null for tenant: " + tenant); diff --git a/apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/features/TokenApiExpectTest.java b/apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/features/TokenApiExpectTest.java index 9132077d6e..9b59b98ab0 100644 --- a/apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/features/TokenApiExpectTest.java +++ b/apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/features/TokenApiExpectTest.java @@ -55,7 +55,7 @@ public class TokenApiExpectTest extends BaseKeystoneRestApiExpectTest endpoints = api.listEndpointsForToken("XXXXXX"); - + assertEquals(endpoints, ImmutableSet.of( Endpoint.builder().publicURL(URI.create("https://csnode.jclouds.org/v2.0/")) .adminURL(URI.create("https://csnode.jclouds.org:35357/v2.0/")) - .region("region-a.geo-1").versionId("2.0").build() + .region("region-a.geo-1").id("2.0").versionId("2.0").build() )); } - + @Test public void testGetEndpointsForTokenFailNotFound() { TokenApi api = requestsSendResponses( @@ -157,5 +157,5 @@ public class TokenApiExpectTest extends BaseKeystoneRestApiExpectTest { public UserApiExpectTest(){ endpoint = "https://csnode.jclouds.org:35357"; } - + + Set expectedUsers = ImmutableSet.of( + User.builder().name("nova").id("e021dfd758eb44a89f1c57c8ef3be8e2").build(), + User.builder().name("glance").id("3f6c1c9ba993495ead7d2eb2192e284f").build(), + User.builder().name("demo").id("667b2e1420604df8b67cd8ea57d4ee64").build(), + User.builder().name("admin").id("2b9b606181634ae9ac86fd95a8bc2cde").build() + ); + public void testListUsers() { UserApi api = requestsSendResponses( keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, authenticatedGET().endpoint(endpoint + "/v2.0/users").build(), HttpResponse.builder().statusCode(200).payload(payloadFromResourceWithContentType("/user_list.json", APPLICATION_JSON)).build()) .getUserApi().get(); - Set users = api.list(); + + assertEquals(api.list().concat().toImmutableSet(), expectedUsers); + } + + public void testListUsersPage() { + UserApi api = requestsSendResponses( + keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, + authenticatedGET().endpoint(endpoint + "/v2.0/users").build(), + HttpResponse.builder().statusCode(200).payload(payloadFromResourceWithContentType("/user_list.json", APPLICATION_JSON)).build()) + .getUserApi().get(); + PaginatedCollection users = api.list(new PaginationOptions()); assertNotNull(users); assertFalse(users.isEmpty()); - Set expected = ImmutableSet.of( - User.builder().name("nova").id("e021dfd758eb44a89f1c57c8ef3be8e2").build(), - User.builder().name("glance").id("3f6c1c9ba993495ead7d2eb2192e284f").build(), - User.builder().name("demo").id("667b2e1420604df8b67cd8ea57d4ee64").build(), - User.builder().name("admin").id("2b9b606181634ae9ac86fd95a8bc2cde").build() - ); - assertEquals(users, expected); + assertEquals(users.toImmutableSet(), expectedUsers); + } + + public void testListUsersNotFound() { + UserApi api = requestsSendResponses( + keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, + authenticatedGET().endpoint(endpoint + "/v2.0/users").build(), + HttpResponse.builder().statusCode(404).build()).getUserApi().get(); + assertEquals( api.list(new PaginationOptions()).size(), 0); } @Test(expectedExceptions = AuthorizationException.class) @@ -76,7 +97,7 @@ public class UserApiExpectTest extends BaseKeystoneRestApiExpectTest users = api.list(); + Set users = api.list().concat().toImmutableSet(); assertNotNull(users); assertFalse(users.isEmpty()); for (User user : users) { @@ -54,10 +54,9 @@ public class UserApiLiveTest extends BaseKeystoneApiLiveTest { public void testUserRolesOnTenant() { UserApi api = keystoneContext.getApi().getUserApi().get(); - Set users = api.list(); - Set tenants = keystoneContext.getApi().getTenantApi().get().list(); + Set tenants = keystoneContext.getApi().getTenantApi().get().list().concat().toImmutableSet(); - for (User user : users) { + for (User user : api.list().concat()) { for (Tenant tenant : tenants) { Set roles = api.listRolesOfUserOnTenant(user.getId(), tenant.getId()); for (Role role : roles) { @@ -71,7 +70,7 @@ public class UserApiLiveTest extends BaseKeystoneApiLiveTest { public void testListRolesOfUser() { UserApi api = keystoneContext.getApi().getUserApi().get(); - for (User user : api.list()) { + for (User user : api.list().concat()) { Set roles = api.listRolesOfUser(user.getId()); for (Role role : roles) { assertNotNull(role.getId()); @@ -83,7 +82,7 @@ public class UserApiLiveTest extends BaseKeystoneApiLiveTest { public void testUsersByName() { UserApi api = keystoneContext.getApi().getUserApi().get(); - for (User user : api.list()) { + for (User user : api.list().concat()) { User aUser = api.getByName(user.getName()); assertEquals(aUser, user); } diff --git a/apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/parse/ParseAccessTest.java b/apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/parse/ParseAccessTest.java index ba381dd055..4244b7f510 100644 --- a/apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/parse/ParseAccessTest.java +++ b/apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/parse/ParseAccessTest.java @@ -18,8 +18,6 @@ */ package org.jclouds.openstack.keystone.v2_0.parse; -import java.net.URI; - import javax.ws.rs.Consumes; import javax.ws.rs.core.MediaType; @@ -50,70 +48,67 @@ public class ParseAccessTest extends BaseItemParserTest { @SelectJson("access") @Consumes(MediaType.APPLICATION_JSON) public Access expected() { - return Access.builder().token( - Token.builder().expires(new SimpleDateFormatDateService().iso8601DateParse("2012-01-18T21:35:59.050Z")) - .id("Auth_4f173437e4b013bee56d1007").tenant( - Tenant.builder().id("40806637803162").name("user@jclouds.org-default-tenant").build()) - .build()).user( - User.builder().id("36980896575174").name("user@jclouds.org").roles( - Role.builder().id("00000000004022").serviceId("110").name("Admin").tenantId("40806637803162") - .build(), - Role.builder().id("00000000004024").serviceId("140").name("user").tenantId("40806637803162") - .build(), - Role.builder().id("00000000004004").serviceId("100").name("domainuser").build(), - Role.builder().id("00000000004016").serviceId("120").name("netadmin") - .tenantId("40806637803162").build()).build()).serviceCatalog( - - Service.builder().name("Object Storage").type("object-store").endpoints( - Endpoint.builder().tenantId("40806637803162").publicURL( - URI.create("https://objects.jclouds.org/v1.0/40806637803162")) - .adminURL(URI.create("https://objects.jclouds.org/v1.0/")) - .region("region-a.geo-1").versionId("1.0").build()).build(), - - Service.builder().name("Identity").type("identity").endpoints( - Endpoint.builder().publicURL(URI.create("https://csnode.jclouds.org/v2.0/")) - .adminURL(URI.create("https://csnode.jclouds.org:35357/v2.0/")) - .region("region-a.geo-1").versionId("2.0").build()).build(), - - Service.builder().name("Image Management").type("image").endpoints( - Endpoint.builder().tenantId("40806637803162").publicURL( - URI.create("https://glance.jclouds.org:9292/v1.0")).region("az-1.region-a.geo-1") - .versionId("1.0").build()).build(), - - Service.builder().name("Compute").type("compute").endpoints( - Endpoint.builder() - .tenantId("3456") - .publicURL(URI.create("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456")) - .region("az-1.region-a.geo-1") - .versionId("1.1") - .versionInfo(URI.create("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/")) - .versionList(URI.create("https://az-1.region-a.geo-1.compute.hpcloudsvc.com")).build(), - Endpoint.builder() - .tenantId("3456") - .publicURL(URI.create("https://az-2.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456")) - .region("az-2.region-a.geo-1") - .versionId("1.1") - .versionInfo(URI.create("https://az-2.region-a.geo-1.compute.hpcloudsvc.com/v1.1/")) - .versionList(URI.create("https://az-2.region-a.geo-1.compute.hpcloudsvc.com")).build(), - Endpoint.builder() - .tenantId("3456") - .publicURL(URI.create("https://az-3.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456")) - .region("az-3.region-a.geo-1") - .versionId("1.1") - .versionInfo(URI.create("https://az-3.region-a.geo-1.compute.hpcloudsvc.com/v1.1/")) - .versionList(URI.create("https://az-3.region-a.geo-1.compute.hpcloudsvc.com")).build()).build(), - - Service.builder().name("Quantum Service").type("network").endpoints( - Endpoint.builder() - .tenantId("3456") - .publicURL(URI.create("https://csnode.jclouds.org:9696/v1.0/tenants/3456")) - .internalURL(URI.create("https://csnode.jclouds.org:9696/v1.0/tenants/3456")) - .adminURL(URI.create("https://csnode.jclouds.org:9696/v1.0")) - .region("region-a.geo-1") - .versionId("1.0").build() - ).build()) - - .build(); + return Access.builder() + .token(Token.builder() + .expires(new SimpleDateFormatDateService().iso8601DateParse("2012-01-18T21:35:59.050Z")) + .id("Auth_4f173437e4b013bee56d1007") + .tenant(Tenant.builder().id("40806637803162").name("user@jclouds.org-default-tenant").build()).build()) + .user(User.builder() + .id("36980896575174").name("user@jclouds.org") + .role(Role.builder().id("00000000004022").serviceId("110").name("Admin").tenantId("40806637803162").build()) + .role(Role.builder().id("00000000004024").serviceId("140").name("user").tenantId("40806637803162").build()) + .role(Role.builder().id("00000000004004").serviceId("100").name("domainuser").build()) + .role(Role.builder().id("00000000004016").serviceId("120").name("netadmin").tenantId("40806637803162").build()).build()) + .service(Service.builder().name("Object Storage").type("object-store") + .endpoint(Endpoint.builder() + .tenantId("40806637803162") + .publicURL("https://objects.jclouds.org/v1.0/40806637803162") + .adminURL("https://objects.jclouds.org/v1.0/") + .id("1.0") + .region("region-a.geo-1").build()).build()) + .service(Service.builder().name("Identity").type("identity") + .endpoint(Endpoint.builder() + .publicURL("https://csnode.jclouds.org/v2.0/") + .adminURL("https://csnode.jclouds.org:35357/v2.0/") + .region("region-a.geo-1") + .id("2.0") + .versionId("2.0").build()).build()) + .service(Service.builder().name("Image Management").type("image") + .endpoint(Endpoint.builder() + .tenantId("40806637803162") + .publicURL("https://glance.jclouds.org:9292/v1.0") + .region("az-1.region-a.geo-1") + .id("1.0").build()).build()) + .service(Service.builder().name("Compute").type("compute") + .endpoint(Endpoint.builder() + .tenantId("3456") + .publicURL("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456") + .region("az-1.region-a.geo-1") + .versionId("1.1") + .versionInfo("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/") + .versionList("https://az-1.region-a.geo-1.compute.hpcloudsvc.com").build()) + .endpoint(Endpoint.builder() + .tenantId("3456") + .publicURL("https://az-2.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456") + .region("az-2.region-a.geo-1") + .versionId("1.1") + .versionInfo("https://az-2.region-a.geo-1.compute.hpcloudsvc.com/v1.1/") + .versionList("https://az-2.region-a.geo-1.compute.hpcloudsvc.com").build()) + .endpoint(Endpoint.builder() + .tenantId("3456") + .publicURL("https://az-3.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456") + .region("az-3.region-a.geo-1") + .versionId("1.1") + .versionInfo("https://az-3.region-a.geo-1.compute.hpcloudsvc.com/v1.1/") + .versionList("https://az-3.region-a.geo-1.compute.hpcloudsvc.com").build()).build()) + .service(Service.builder().name("Quantum Service").type("network") + .endpoint(Endpoint.builder() + .tenantId("3456") + .publicURL("https://csnode.jclouds.org:9696/v1.0/tenants/3456") + .internalURL("https://csnode.jclouds.org:9696/v1.0/tenants/3456") + .adminURL("https://csnode.jclouds.org:9696/v1.0") + .region("region-a.geo-1") + .versionId("1.0").build()).build()).build(); } } diff --git a/apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/parse/ParseAdminAccessTest.java b/apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/parse/ParseAdminAccessTest.java index 89d697d2e6..b5e96b6801 100644 --- a/apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/parse/ParseAdminAccessTest.java +++ b/apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/parse/ParseAdminAccessTest.java @@ -18,8 +18,6 @@ */ package org.jclouds.openstack.keystone.v2_0.parse; -import java.net.URI; - import javax.ws.rs.Consumes; import javax.ws.rs.core.MediaType; @@ -36,7 +34,7 @@ import org.jclouds.rest.annotations.SelectJson; import org.testng.annotations.Test; /** - * @author Adam Lowe + * @author Adam Lowe, Adrian Cole */ @Test(groups = "unit", testName = "ParseAdminAccessTest") public class ParseAdminAccessTest extends BaseItemParserTest { @@ -50,52 +48,52 @@ public class ParseAdminAccessTest extends BaseItemParserTest { @SelectJson("access") @Consumes(MediaType.APPLICATION_JSON) public Access expected() { - return Access.builder().token( - Token.builder().expires(new SimpleDateFormatDateService().iso8601SecondsDateParse("2012-08-01T13:08:52Z")) - .id("946b8ad1ede4422f87ab21dcba27896d").tenant( - Tenant.builder().id("2fdc88ae152948c690b97ba307acae9b").name("admin").build()) - .build()).user( - User.builder().id("b4d134cfe3cf43ad8ba0c2fc5b5d8f91").name("admin").roles( - Role.builder().name("admin").build(), - Role.builder().name("KeystoneServiceAdmin").build(), - Role.builder().name("KeystoneAdmin").build()).build()) - .serviceCatalog( - Service.builder().name("Compute Service").type("compute").endpoints( - Endpoint.builder() - .adminURL(URI.create("http://10.0.1.13:8774/v2/2fdc88ae152948c690b97ba307acae9b")) - .internalURL(URI.create("http://10.0.1.13:8774/v2/2fdc88ae152948c690b97ba307acae9b")) - .publicURL(URI.create("http://10.0.1.13:8774/v2/2fdc88ae152948c690b97ba307acae9b")) - .region("RegionOne").build()).build(), - Service.builder().name("S3 Service").type("s3").endpoints( - Endpoint.builder() - .adminURL(URI.create("http://10.0.1.13:3333")) - .internalURL(URI.create("http://10.0.1.13:3333")) - .publicURL(URI.create("http://10.0.1.13:3333")) - .region("RegionOne").build()).build(), - Service.builder().name("Image Service").type("image").endpoints( - Endpoint.builder() - .adminURL(URI.create("http://10.0.1.13:9292")) - .internalURL(URI.create("http://10.0.1.13:9292")) - .publicURL(URI.create("http://10.0.1.13:9292")) - .region("RegionOne").build()).build(), - Service.builder().name("Volume Service").type("volume").endpoints( - Endpoint.builder() - .adminURL(URI.create("http://10.0.1.13:8776/v1/2fdc88ae152948c690b97ba307acae9b")) - .internalURL(URI.create("http://10.0.1.13:8776/v1/2fdc88ae152948c690b97ba307acae9b")) - .publicURL(URI.create("http://10.0.1.13:8776/v1/2fdc88ae152948c690b97ba307acae9b")) - .region("RegionOne").build()).build(), - Service.builder().name("EC2 Service").type("ec2").endpoints( - Endpoint.builder() - .adminURL(URI.create("http://10.0.1.13:8773/services/Admin")) - .internalURL(URI.create("http://10.0.1.13:8773/services/Cloud")) - .publicURL(URI.create("http://10.0.1.13:8773/services/Cloud")) - .region("RegionOne").build()).build(), - Service.builder().name("Identity Service").type("identity").endpoints( - Endpoint.builder() - .adminURL(URI.create("http://10.0.1.13:35357/v2.0")) - .internalURL(URI.create("http://10.0.1.13:5000/v2.0")) - .publicURL(URI.create("http://10.0.1.13:5000/v2.0")) - .region("RegionOne").build()).build() - ).build(); + return Access.builder() + .token(Token.builder() + .expires(new SimpleDateFormatDateService().iso8601SecondsDateParse("2012-08-01T13:08:52Z")) + .id("946b8ad1ede4422f87ab21dcba27896d") + .tenant(Tenant.builder().id("2fdc88ae152948c690b97ba307acae9b").name("admin").build()).build()) + .user(User.builder() + .id("b4d134cfe3cf43ad8ba0c2fc5b5d8f91") + .name("admin") + .role(Role.builder().name("admin").build()) + .role(Role.builder().name("KeystoneServiceAdmin").build()) + .role(Role.builder().name("KeystoneAdmin").build()).build()) + .service(Service.builder().name("Compute Service").type("compute") + .endpoint(Endpoint.builder() + .adminURL("http://10.0.1.13:8774/v2/2fdc88ae152948c690b97ba307acae9b") + .internalURL("http://10.0.1.13:8774/v2/2fdc88ae152948c690b97ba307acae9b") + .publicURL("http://10.0.1.13:8774/v2/2fdc88ae152948c690b97ba307acae9b") + .region("RegionOne").build()).build()) + .service(Service.builder().name("S3 Service").type("s3") + .endpoint(Endpoint.builder() + .adminURL("http://10.0.1.13:3333") + .internalURL("http://10.0.1.13:3333") + .publicURL("http://10.0.1.13:3333") + .region("RegionOne").build()).build()) + .service(Service.builder().name("Image Service").type("image") + .endpoint(Endpoint.builder() + .adminURL("http://10.0.1.13:9292") + .internalURL("http://10.0.1.13:9292") + .publicURL("http://10.0.1.13:9292") + .region("RegionOne").build()).build()) + .service(Service.builder().name("Volume Service").type("volume") + .endpoint(Endpoint.builder() + .adminURL("http://10.0.1.13:8776/v1/2fdc88ae152948c690b97ba307acae9b") + .internalURL("http://10.0.1.13:8776/v1/2fdc88ae152948c690b97ba307acae9b") + .publicURL("http://10.0.1.13:8776/v1/2fdc88ae152948c690b97ba307acae9b") + .region("RegionOne").build()).build()) + .service(Service.builder().name("EC2 Service").type("ec2") + .endpoint(Endpoint.builder() + .adminURL("http://10.0.1.13:8773/services/Admin") + .internalURL("http://10.0.1.13:8773/services/Cloud") + .publicURL("http://10.0.1.13:8773/services/Cloud") + .region("RegionOne").build()).build()) + .service(Service.builder().name("Identity Service").type("identity") + .endpoint(Endpoint.builder() + .adminURL("http://10.0.1.13:35357/v2.0") + .internalURL("http://10.0.1.13:5000/v2.0") + .publicURL("http://10.0.1.13:5000/v2.0") + .region("RegionOne").build()).build()).build(); } } diff --git a/apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/parse/ParseRackspaceAccessTest.java b/apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/parse/ParseRackspaceAccessTest.java index 670b1c5ab7..27b3c8e7e6 100644 --- a/apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/parse/ParseRackspaceAccessTest.java +++ b/apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/parse/ParseRackspaceAccessTest.java @@ -18,8 +18,6 @@ */ package org.jclouds.openstack.keystone.v2_0.parse; -import java.net.URI; - import javax.ws.rs.Consumes; import javax.ws.rs.core.MediaType; @@ -38,7 +36,7 @@ import org.testng.annotations.Test; /** * @author Adrian Cole */ -@Test(groups = "unit", testName = "ParseAccessTest") +@Test(groups = "unit", testName = "ParseRackspaceAccessTest") public class ParseRackspaceAccessTest extends BaseItemParserTest { @Override @@ -50,64 +48,69 @@ public class ParseRackspaceAccessTest extends BaseItemParserTest { @SelectJson("access") @Consumes(MediaType.APPLICATION_JSON) public Access expected() { - return Access.builder().token( - Token.builder().expires(new SimpleDateFormatDateService().iso8601DateParse("2012-06-06T20:56:47.000-05:00")) - .id("Auth_4f173437e4b013bee56d1007").tenant( - Tenant.builder().id("40806637803162").name("40806637803162").build()) - .build()).user( - User.builder().id("54321").name("joe").roles( - Role.builder().id("3").name("identity:user-admin").description("User Admin Role.") - .build()).build()).serviceCatalog( - - Service.builder().name("cloudDatabases").type("rax:database").endpoints( - Endpoint.builder().tenantId("40806637803162").publicURL( - URI.create("https://dfw.databases.api.rackspacecloud.com/v1.0/40806637803162")) - .region("DFW").build(), - Endpoint.builder().tenantId("40806637803162").publicURL( - URI.create("https://ord.databases.api.rackspacecloud.com/v1.0/40806637803162")) - .region("ORD").build()).build(), - - Service.builder().name("cloudServers").type("compute").endpoints( - Endpoint.builder().tenantId("40806637803162").publicURL( - URI.create("https://servers.api.rackspacecloud.com/v1.0/40806637803162")) - .versionId("1.0").versionInfo(URI.create("https://servers.api.rackspacecloud.com/v1.0")) - .versionList(URI.create("https://servers.api.rackspacecloud.com/")).build()).build(), - - Service.builder().name("cloudFiles").type("object-store").endpoints( - Endpoint.builder().tenantId("MossoCloudFS_dc1f419c-5059-4c87-a389-3f2e33a77b22").publicURL( - URI.create("https://storage101.dfw1.clouddrive.com/v1/MossoCloudFS_dc1f419c-5059-4c87-a389-3f2e33a77b22")) - .internalURL( - URI.create("https://snet-storage101.dfw1.clouddrive.com/v1/MossoCloudFS_dc1f419c-5059-4c87-a389-3f2e33a77b22")) - .region("DFW").build()).build(), - - Service.builder().name("cloudServersOpenStack").type("compute").endpoints( - Endpoint.builder().tenantId("40806637803162").publicURL( - URI.create("https://dfw.servers.api.rackspacecloud.com/v2/40806637803162")) - .versionInfo(URI.create("https://dfw.servers.api.rackspacecloud.com/v2")) - .versionList(URI.create("https://dfw.servers.api.rackspacecloud.com/")) - .versionId("2") - .region("DFW").build()).build(), - - Service.builder().name("cloudLoadBalancers").type("rax:load-balancer").endpoints( - Endpoint.builder().tenantId("40806637803162").publicURL( - URI.create("https://ord.loadbalancers.api.rackspacecloud.com/v1.0/40806637803162")) - .region("ORD").build(), - Endpoint.builder().tenantId("40806637803162").publicURL( - URI.create("https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/40806637803162")) - .region("DFW").build()).build(), - - Service.builder().name("cloudMonitoring").type("rax:monitor").endpoints( - Endpoint.builder().tenantId("40806637803162").publicURL( - URI.create("https://monitoring.api.rackspacecloud.com/v1.0/40806637803162")).build()).build(), - - Service.builder().name("cloudDNS").type("dnsextension:dns").endpoints( - Endpoint.builder().tenantId("40806637803162").publicURL( - URI.create("https://dns.api.rackspacecloud.com/v1.0/40806637803162")).build()).build(), - - Service.builder().name("cloudFilesCDN").type("rax:object-cdn").endpoints( - Endpoint.builder().tenantId("MossoCloudFS_dc1f419c-5059-4c87-a389-3f2e33a77b22").publicURL( - URI.create("https://cdn1.clouddrive.com/v1/MossoCloudFS_dc1f419c-5059-4c87-a389-3f2e33a77b22")) - .region("DFW").build()).build() - ).build(); + return Access.builder() + .token(Token.builder() + .expires(new SimpleDateFormatDateService().iso8601DateParse("2012-06-06T20:56:47.000-05:00")) + .id("Auth_4f173437e4b013bee56d1007") + .tenant(Tenant.builder().id("40806637803162").name("40806637803162").build()).build()) + .user(User.builder() + .id("54321") + .name("joe") + .role(Role.builder() + .id("3") + .name("identity:user-admin") + .description("User Admin Role.").build()).build()) + .service(Service.builder().name("cloudDatabases").type("rax:database") + .endpoint(Endpoint.builder() + .tenantId("40806637803162") + .publicURL("https://dfw.databases.api.rackspacecloud.com/v1.0/40806637803162") + .region("DFW").build()) + .endpoint(Endpoint.builder() + .tenantId("40806637803162") + .publicURL("https://ord.databases.api.rackspacecloud.com/v1.0/40806637803162") + .region("ORD").build()).build()) + .service(Service.builder().name("cloudServers").type("compute") + .endpoint(Endpoint.builder() + .tenantId("40806637803162") + .publicURL("https://servers.api.rackspacecloud.com/v1.0/40806637803162") + .versionId("1.0") + .versionInfo("https://servers.api.rackspacecloud.com/v1.0") + .versionList("https://servers.api.rackspacecloud.com/").build()).build()) + .service(Service.builder().name("cloudFiles").type("object-store") + .endpoint(Endpoint.builder() + .tenantId("MossoCloudFS_dc1f419c-5059-4c87-a389-3f2e33a77b22") + .publicURL("https://storage101.dfw1.clouddrive.com/v1/MossoCloudFS_dc1f419c-5059-4c87-a389-3f2e33a77b22") + .internalURL("https://snet-storage101.dfw1.clouddrive.com/v1/MossoCloudFS_dc1f419c-5059-4c87-a389-3f2e33a77b22") + .region("DFW").build()).build()) + .service(Service.builder().name("cloudServersOpenStack").type("compute") + .endpoint(Endpoint.builder() + .tenantId("40806637803162") + .publicURL("https://dfw.servers.api.rackspacecloud.com/v2/40806637803162") + .versionInfo("https://dfw.servers.api.rackspacecloud.com/v2") + .versionList("https://dfw.servers.api.rackspacecloud.com/") + .versionId("2") + .region("DFW").build()).build()) + .service(Service.builder().name("cloudLoadBalancers").type("rax:load-balancer") + .endpoint(Endpoint.builder() + .tenantId("40806637803162") + .publicURL("https://ord.loadbalancers.api.rackspacecloud.com/v1.0/40806637803162") + .region("ORD").build()) + .endpoint(Endpoint.builder() + .tenantId("40806637803162") + .publicURL("https://dfw.loadbalancers.api.rackspacecloud.com/v1.0/40806637803162") + .region("DFW").build()).build()) + .service(Service.builder().name("cloudMonitoring").type("rax:monitor") + .endpoint(Endpoint.builder() + .tenantId("40806637803162") + .publicURL("https://monitoring.api.rackspacecloud.com/v1.0/40806637803162").build()).build()) + .service(Service.builder().name("cloudDNS").type("dnsextension:dns") + .endpoint(Endpoint.builder() + .tenantId("40806637803162") + .publicURL("https://dns.api.rackspacecloud.com/v1.0/40806637803162").build()).build()) + .service(Service.builder().name("cloudFilesCDN").type("rax:object-cdn") + .endpoint(Endpoint.builder() + .tenantId("MossoCloudFS_dc1f419c-5059-4c87-a389-3f2e33a77b22") + .publicURL("https://cdn1.clouddrive.com/v1/MossoCloudFS_dc1f419c-5059-4c87-a389-3f2e33a77b22") + .region("DFW").build()).build()).build(); } } diff --git a/apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/parse/ParseRandomEndpointVersionAccessTest.java b/apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/parse/ParseRandomEndpointVersionAccessTest.java new file mode 100644 index 0000000000..6665a30d55 --- /dev/null +++ b/apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/parse/ParseRandomEndpointVersionAccessTest.java @@ -0,0 +1,112 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.keystone.v2_0.parse; + +import javax.ws.rs.Consumes; +import javax.ws.rs.core.MediaType; + +import org.jclouds.date.internal.SimpleDateFormatDateService; +import org.jclouds.json.BaseItemParserTest; +import org.jclouds.openstack.keystone.v2_0.domain.Access; +import org.jclouds.openstack.keystone.v2_0.domain.Endpoint; +import org.jclouds.openstack.keystone.v2_0.domain.Role; +import org.jclouds.openstack.keystone.v2_0.domain.Service; +import org.jclouds.openstack.keystone.v2_0.domain.Tenant; +import org.jclouds.openstack.keystone.v2_0.domain.Token; +import org.jclouds.openstack.keystone.v2_0.domain.User; +import org.jclouds.rest.annotations.SelectJson; +import org.testng.annotations.Test; + +/** + * @author Adrian Cole + */ +@Test(groups = "unit", testName = "ParseRandomEndpointVersionAccessTest") +public class ParseRandomEndpointVersionAccessTest extends BaseItemParserTest { + + @Override + public String resource() { + return "/access_version_uids.json"; + } + + @Override + @SelectJson("access") + @Consumes(MediaType.APPLICATION_JSON) + public Access expected() { + return Access.builder() + .token(Token.builder() + .expires(new SimpleDateFormatDateService().iso8601SecondsDateParse("2012-09-29T19:53:45Z")) + .id("b267e2e240624b108b1ed5bba6e5882e") + .tenant(Tenant.builder() + // "enabled": true, + .id("82d8d2f865484776a1daf1e2245d3317") + .name("demo").build()).build()) + .service(Service.builder().type("compute").name("nova") + .endpoint(Endpoint.builder() + .adminURL("http://10.10.10.10:8774/v2/82d8d2f865484776a1daf1e2245d3317") + .region("RegionOne") + .internalURL("http://10.10.10.10:8774/v2/82d8d2f865484776a1daf1e2245d3317") + .id("bb3ce9ccdc5045909882688b90cc3ff0") + .publicURL("http://10.10.10.10:8774/v2/82d8d2f865484776a1daf1e2245d3317").build()).build()) + .service(Service.builder().type("s3").name("s3") + .endpoint(Endpoint.builder() + .adminURL("http://10.10.10.10:3333") + .region("RegionOne") + .internalURL("http://10.10.10.10:3333") + .id("9646263f31ea4f499732c5e1370ecf5e") + .publicURL("http://10.10.10.10:3333").build()).build()) + .service(Service.builder().type("image").name("glance") + .endpoint(Endpoint.builder() + .adminURL("http://10.10.10.10:9292") + .region("RegionOne") + .internalURL("http://10.10.10.10:9292") + .id("aa5d0b2574824ba097dc07faacf3be65") + .publicURL("http://10.10.10.10:9292").build()).build()) + .service(Service.builder().type("volume").name("cinder") + .endpoint(Endpoint.builder() + .adminURL("http://10.10.10.10:8776/v1/82d8d2f865484776a1daf1e2245d3317") + .region("RegionOne") + .internalURL("http://10.10.10.10:8776/v1/82d8d2f865484776a1daf1e2245d3317") + .id("7679065b1405447eb5f1a38a6b99ccc0") + .publicURL("http://10.10.10.10:8776/v1/82d8d2f865484776a1daf1e2245d3317").build()).build()) + .service(Service.builder().type("ec2").name("ec2") + .endpoint(Endpoint.builder() + .adminURL("http://10.10.10.10:8773/services/Admin") + .region("RegionOne") + .internalURL("http://10.10.10.10:8773/services/Cloud") + .id("22b007f023fb4c42be094916eb2bf18b") + .publicURL("http://10.10.10.10:8773/services/Cloud").build()).build()) + .service(Service.builder().type("identity").name("keystone") + .endpoint(Endpoint.builder() + .adminURL("http://10.10.10.10:35357/v2.0") + .region("RegionOne") + .internalURL("http://10.10.10.10:5000/v2.0") + .id("57ee5fb4f9a840f3b965909681d0fc53") + .publicURL("http://10.10.10.10:5000/v2.0").build()).build()) + .user(User.builder() + .id("ca248caf55844c14a4876c22112bbbb9") + .name("demo") +// .username("demo") + .role(Role.builder().name("Member").build()).build()).build(); +// "metadata": { +// "is_admin": 0, +// "roles": ["1f697d8e3ace4f5a80f7701e554ee5d9"] +// } + + } +} diff --git a/apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/suppliers/LocationIdToURIFromAccessForTypeAndVersionTest.java b/apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/suppliers/LocationIdToURIFromAccessForTypeAndVersionTest.java new file mode 100644 index 0000000000..bb7af066b7 --- /dev/null +++ b/apis/openstack-keystone/src/test/java/org/jclouds/openstack/keystone/v2_0/suppliers/LocationIdToURIFromAccessForTypeAndVersionTest.java @@ -0,0 +1,131 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.keystone.v2_0.suppliers; + +import static org.testng.Assert.assertEquals; + +import java.net.URI; +import java.util.Map; +import java.util.NoSuchElementException; + +import javax.inject.Singleton; + +import org.jclouds.location.Provider; +import org.jclouds.openstack.keystone.v2_0.domain.Access; +import org.jclouds.openstack.keystone.v2_0.domain.Endpoint; +import org.jclouds.openstack.keystone.v2_0.functions.EndpointToRegion; +import org.jclouds.openstack.keystone.v2_0.parse.ParseAccessTest; +import org.jclouds.openstack.keystone.v2_0.parse.ParseRackspaceAccessTest; +import org.testng.annotations.Test; + +import com.google.common.base.Function; +import com.google.common.base.Supplier; +import com.google.common.base.Suppliers; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Maps; +import com.google.inject.AbstractModule; +import com.google.inject.Guice; +import com.google.inject.Provides; +import com.google.inject.TypeLiteral; +import com.google.inject.assistedinject.FactoryModuleBuilder; + +/** + * @author Adrian Cole + */ +@Test(groups = "unit", testName = "LocationIdToURIFromAccessForTypeAndVersionTest") +public class LocationIdToURIFromAccessForTypeAndVersionTest { + private final LocationIdToURIFromAccessForTypeAndVersion.Factory factory = Guice.createInjector(new AbstractModule() { + + @Override + protected void configure() { + bindConstant().annotatedWith(Provider.class).to("openstack-keystone"); + bind(new TypeLiteral>(){ + }).annotatedWith(Provider.class).toInstance(Suppliers.ofInstance(URI.create("https://identity"))); + bind(new TypeLiteral>(){}).to(EndpointToRegion.class); + install(new FactoryModuleBuilder().implement(LocationIdToURIFromAccessForTypeAndVersion.class, + LocationIdToURIFromAccessForTypeAndVersion.class).build( + LocationIdToURIFromAccessForTypeAndVersion.Factory.class)); + } + + @Provides + @Singleton + public Supplier provide() { + return Suppliers.ofInstance(new ParseAccessTest().expected()); + } + + }).getInstance(LocationIdToURIFromAccessForTypeAndVersion.Factory.class); + + public void testRegionUnmatchesOkWhenNoVersionIdSet() { + assertEquals(Maps.transformValues(factory.createForApiTypeAndVersion("compute", "1.1").get(), Suppliers + . supplierFunction()), ImmutableMap.of("az-1.region-a.geo-1", URI + .create("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456"), "az-2.region-a.geo-1", URI + .create("https://az-2.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456"), "az-3.region-a.geo-1", URI + .create("https://az-3.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456"))); + } + + public void testRegionMatches() { + assertEquals(Maps.transformValues(factory.createForApiTypeAndVersion("compute", "1.1").get(), Suppliers + . supplierFunction()), ImmutableMap.of("az-1.region-a.geo-1", URI + .create("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456"), "az-2.region-a.geo-1", URI + .create("https://az-2.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456"), "az-3.region-a.geo-1", URI + .create("https://az-3.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456"))); + } + + private final LocationIdToURIFromAccessForTypeAndVersion.Factory raxFactory = Guice.createInjector(new AbstractModule() { + + @Override + protected void configure() { + bindConstant().annotatedWith(Provider.class).to("rackspace"); + bind(new TypeLiteral>() { + }).annotatedWith(Provider.class).toInstance(Suppliers.ofInstance(URI.create("https://identity"))); + bind(new TypeLiteral>(){}).to(EndpointToRegion.class); + install(new FactoryModuleBuilder().implement(LocationIdToURIFromAccessForTypeAndVersion.class, + LocationIdToURIFromAccessForTypeAndVersion.class).build( + LocationIdToURIFromAccessForTypeAndVersion.Factory.class)); + } + + @Provides + @Singleton + public Supplier provide() { + return Suppliers.ofInstance(new ParseRackspaceAccessTest().expected()); + } + }).getInstance(LocationIdToURIFromAccessForTypeAndVersion.Factory.class); + + @Test(expectedExceptions = NoSuchElementException.class) + public void testWhenNotInList() { + assertEquals(Maps.transformValues(raxFactory.createForApiTypeAndVersion("goo", "1.0").get(), Suppliers + . supplierFunction()), ImmutableMap.of("rackspace", URI + .create("https://servers.api.rackspacecloud.com/v1.0/40806637803162"))); + } + + public void testProviderWhenNoRegions() { + Map withNoRegions = Maps.transformValues(raxFactory.createForApiTypeAndVersion("compute", "1.0") + .get(), Suppliers. supplierFunction()); + assertEquals(withNoRegions, ImmutableMap.of("rackspace", URI + .create("https://servers.api.rackspacecloud.com/v1.0/40806637803162"))); + } + + public void testOkWithNoVersions() { + assertEquals(Maps.transformValues(raxFactory.createForApiTypeAndVersion("rax:database", null).get(), Suppliers + . supplierFunction()), ImmutableMap.of("DFW", URI + .create("https://dfw.databases.api.rackspacecloud.com/v1.0/40806637803162"), "ORD", URI + .create("https://ord.databases.api.rackspacecloud.com/v1.0/40806637803162"))); + } + +} diff --git a/apis/openstack-keystone/src/test/java/org/jclouds/openstack/v2_0/functions/PresentWhenExtensionAnnotationNamespaceEqualsAnyNamespaceInExtensionsSetTest.java b/apis/openstack-keystone/src/test/java/org/jclouds/openstack/v2_0/functions/PresentWhenExtensionAnnotationNamespaceEqualsAnyNamespaceInExtensionsSetTest.java index 9fa985b1ca..6e74370187 100644 --- a/apis/openstack-keystone/src/test/java/org/jclouds/openstack/v2_0/functions/PresentWhenExtensionAnnotationNamespaceEqualsAnyNamespaceInExtensionsSetTest.java +++ b/apis/openstack-keystone/src/test/java/org/jclouds/openstack/v2_0/functions/PresentWhenExtensionAnnotationNamespaceEqualsAnyNamespaceInExtensionsSetTest.java @@ -5,13 +5,10 @@ import static org.testng.Assert.assertEquals; import java.net.URI; import java.util.Set; -import javax.inject.Named; - import org.jclouds.date.internal.SimpleDateFormatDateService; import org.jclouds.internal.ClassMethodArgsAndReturnVal; import org.jclouds.openstack.v2_0.ServiceType; import org.jclouds.openstack.v2_0.domain.Extension; -import org.jclouds.openstack.v2_0.functions.PresentWhenExtensionAnnotationNamespaceEqualsAnyNamespaceInExtensionsSet; import org.jclouds.rest.annotations.Delegate; import org.testng.annotations.Test; diff --git a/apis/openstack-keystone/src/test/java/org/jclouds/openstack/v2_0/options/BaseListOptionsTest.java b/apis/openstack-keystone/src/test/java/org/jclouds/openstack/v2_0/options/PaginationOptionsTest.java similarity index 56% rename from apis/openstack-keystone/src/test/java/org/jclouds/openstack/v2_0/options/BaseListOptionsTest.java rename to apis/openstack-keystone/src/test/java/org/jclouds/openstack/v2_0/options/PaginationOptionsTest.java index 5387aec178..7e594bdfb4 100644 --- a/apis/openstack-keystone/src/test/java/org/jclouds/openstack/v2_0/options/BaseListOptionsTest.java +++ b/apis/openstack-keystone/src/test/java/org/jclouds/openstack/v2_0/options/PaginationOptionsTest.java @@ -18,9 +18,9 @@ */ package org.jclouds.openstack.v2_0.options; -import static org.jclouds.openstack.v2_0.options.BaseListOptions.Builder.changesSince; -import static org.jclouds.openstack.v2_0.options.BaseListOptions.Builder.maxResults; -import static org.jclouds.openstack.v2_0.options.BaseListOptions.Builder.startAt; +import static org.jclouds.openstack.v2_0.options.PaginationOptions.Builder.changesSince; +import static org.jclouds.openstack.v2_0.options.PaginationOptions.Builder.limit; +import static org.jclouds.openstack.v2_0.options.PaginationOptions.Builder.marker; import static org.testng.Assert.assertEquals; import java.util.Date; @@ -34,44 +34,44 @@ import com.google.common.collect.ImmutableList; * * @author Adrian Cole */ -@Test(groups = "unit") -public class BaseListOptionsTest { +@Test(groups = "unit", testName = "PaginationOptionsTest") +public class PaginationOptionsTest { public void testChangesSince() { Date ifModifiedSince = new Date(); - BaseListOptions options = new BaseListOptions().changesSince(ifModifiedSince); - assertEquals(ImmutableList.of(ifModifiedSince.getTime() / 1000 + ""), options - .buildQueryParameters().get("changes-since")); + PaginationOptions options = new PaginationOptions().changesSince(ifModifiedSince); + assertEquals(ImmutableList.of(ifModifiedSince.getTime() / 1000 + ""), + options.buildQueryParameters().get("changes-since")); } - public void testStartAt() { - long offset = 1; - BaseListOptions options = new BaseListOptions().startAt(offset); - assertEquals(ImmutableList.of("1"), options.buildQueryParameters().get("offset")); + public void testMarker() { + String marker = "52415800-8b69-11e0-9b19-734f6f006e54"; + PaginationOptions options = new PaginationOptions().marker(marker); + assertEquals(ImmutableList.of(marker), options.buildQueryParameters().get("marker")); } public void testMaxResults() { int limit = 1; - BaseListOptions options = new BaseListOptions().maxResults(limit); + PaginationOptions options = new PaginationOptions().limit(limit); assertEquals(ImmutableList.of("1"), options.buildQueryParameters().get("limit")); } public void testChangesSinceStatic() { Date ifModifiedSince = new Date(); - BaseListOptions options = changesSince(ifModifiedSince); - assertEquals(ImmutableList.of(ifModifiedSince.getTime() / 1000 + ""), options - .buildQueryParameters().get("changes-since")); + PaginationOptions options = changesSince(ifModifiedSince); + assertEquals(ImmutableList.of(ifModifiedSince.getTime() / 1000 + ""), + options.buildQueryParameters().get("changes-since")); } - public void testStartAtStatic() { - long offset = 1; - BaseListOptions options = startAt(offset); - assertEquals(ImmutableList.of("1"), options.buildQueryParameters().get("offset")); + public void testMarkerStatic() { + String marker = "52415800-8b69-11e0-9b19-734f6f006e54"; + PaginationOptions options = marker(marker); + assertEquals(ImmutableList.of(marker), options.buildQueryParameters().get("marker")); } public void testMaxResultsStatic() { int limit = 1; - BaseListOptions options = maxResults(limit); + PaginationOptions options = limit(limit); assertEquals(ImmutableList.of("1"), options.buildQueryParameters().get("limit")); } } diff --git a/apis/openstack-keystone/src/test/resources/access_version_uids.json b/apis/openstack-keystone/src/test/resources/access_version_uids.json new file mode 100644 index 0000000000..3349580296 --- /dev/null +++ b/apis/openstack-keystone/src/test/resources/access_version_uids.json @@ -0,0 +1 @@ +{"access": {"token": {"expires": "2012-09-29T19:53:45Z", "id": "b267e2e240624b108b1ed5bba6e5882e", "tenant": {"enabled": true, "description": null, "name": "demo", "id": "82d8d2f865484776a1daf1e2245d3317"}}, "serviceCatalog": [{"endpoints": [{"adminURL": "http://10.10.10.10:8774/v2/82d8d2f865484776a1daf1e2245d3317", "region": "RegionOne", "internalURL": "http://10.10.10.10:8774/v2/82d8d2f865484776a1daf1e2245d3317", "id": "bb3ce9ccdc5045909882688b90cc3ff0", "publicURL": "http://10.10.10.10:8774/v2/82d8d2f865484776a1daf1e2245d3317"}], "endpoints_links": [], "type": "compute", "name": "nova"}, {"endpoints": [{"adminURL": "http://10.10.10.10:3333", "region": "RegionOne", "internalURL": "http://10.10.10.10:3333", "id": "9646263f31ea4f499732c5e1370ecf5e", "publicURL": "http://10.10.10.10:3333"}], "endpoints_links": [], "type": "s3", "name": "s3"}, {"endpoints": [{"adminURL": "http://10.10.10.10:9292", "region": "RegionOne", "internalURL": "http://10.10.10.10:9292", "id": "aa5d0b2574824ba097dc07faacf3be65", "publicURL": "http://10.10.10.10:9292"}], "endpoints_links": [], "type": "image", "name": "glance"}, {"endpoints": [{"adminURL": "http://10.10.10.10:8776/v1/82d8d2f865484776a1daf1e2245d3317", "region": "RegionOne", "internalURL": "http://10.10.10.10:8776/v1/82d8d2f865484776a1daf1e2245d3317", "id": "7679065b1405447eb5f1a38a6b99ccc0", "publicURL": "http://10.10.10.10:8776/v1/82d8d2f865484776a1daf1e2245d3317"}], "endpoints_links": [], "type": "volume", "name": "cinder"}, {"endpoints": [{"adminURL": "http://10.10.10.10:8773/services/Admin", "region": "RegionOne", "internalURL": "http://10.10.10.10:8773/services/Cloud", "id": "22b007f023fb4c42be094916eb2bf18b", "publicURL": "http://10.10.10.10:8773/services/Cloud"}], "endpoints_links": [], "type": "ec2", "name": "ec2"}, {"endpoints": [{"adminURL": "http://10.10.10.10:35357/v2.0", "region": "RegionOne", "internalURL": "http://10.10.10.10:5000/v2.0", "id": "57ee5fb4f9a840f3b965909681d0fc53", "publicURL": "http://10.10.10.10:5000/v2.0"}], "endpoints_links": [], "type": "identity", "name": "keystone"}], "user": {"username": "demo", "roles_links": [], "id": "ca248caf55844c14a4876c22112bbbb9", "roles": [{"name": "Member"}], "name": "demo"}, "metadata": {"is_admin": 0, "roles": ["1f697d8e3ace4f5a80f7701e554ee5d9"]}}} \ No newline at end of file diff --git a/apis/openstack-nova-ec2/pom.xml b/apis/openstack-nova-ec2/pom.xml index 94fba780c2..429954446b 100644 --- a/apis/openstack-nova-ec2/pom.xml +++ b/apis/openstack-nova-ec2/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.api diff --git a/apis/openstack-nova/pom.xml b/apis/openstack-nova/pom.xml index 07c0332e10..d18ab65597 100644 --- a/apis/openstack-nova/pom.xml +++ b/apis/openstack-nova/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.api diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/NovaApi.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/NovaApi.java index 35eb3db0ca..1940faf3e0 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/NovaApi.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/NovaApi.java @@ -25,7 +25,7 @@ import org.jclouds.concurrent.Timeout; import org.jclouds.javax.annotation.Nullable; import org.jclouds.location.Zone; import org.jclouds.location.functions.ZoneToEndpoint; -import org.jclouds.openstack.nova.v2_0.extensions.AdminActionsApi; +import org.jclouds.openstack.nova.v2_0.extensions.ServerAdminApi; import org.jclouds.openstack.nova.v2_0.extensions.FlavorExtraSpecsApi; import org.jclouds.openstack.nova.v2_0.extensions.FloatingIPApi; import org.jclouds.openstack.nova.v2_0.extensions.HostAdministrationApi; @@ -156,7 +156,7 @@ public interface NovaApi { * Provides synchronous access to Server Admin Actions features. */ @Delegate - Optional getAdminActionsExtensionForZone( + Optional getServerAdminExtensionForZone( @EndpointParam(parser = ZoneToEndpoint.class) @Nullable String zone); /** diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/NovaApiMetadata.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/NovaApiMetadata.java index 780eb81706..0445321e51 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/NovaApiMetadata.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/NovaApiMetadata.java @@ -33,6 +33,7 @@ import org.jclouds.openstack.keystone.v2_0.config.CredentialTypes; import org.jclouds.openstack.keystone.v2_0.config.KeystoneAuthenticationModule; import org.jclouds.openstack.keystone.v2_0.config.KeystoneAuthenticationModule.ZoneModule; import org.jclouds.openstack.nova.v2_0.compute.config.NovaComputeServiceContextModule; +import org.jclouds.openstack.nova.v2_0.config.NovaParserModule; import org.jclouds.openstack.nova.v2_0.config.NovaRestClientModule; import org.jclouds.openstack.v2_0.ServiceType; import org.jclouds.rest.RestContext; @@ -101,6 +102,7 @@ public class NovaApiMetadata extends BaseRestApiMetadata { .defaultModules(ImmutableSet.>builder() .add(KeystoneAuthenticationModule.class) .add(ZoneModule.class) + .add(NovaParserModule.class) .add(NovaRestClientModule.class) .add(NovaComputeServiceContextModule.class).build()); } diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/NovaAsyncApi.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/NovaAsyncApi.java index 3e71a78478..09631d323f 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/NovaAsyncApi.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/NovaAsyncApi.java @@ -23,7 +23,7 @@ import java.util.Set; import org.jclouds.javax.annotation.Nullable; import org.jclouds.location.Zone; import org.jclouds.location.functions.ZoneToEndpoint; -import org.jclouds.openstack.nova.v2_0.extensions.AdminActionsAsyncApi; +import org.jclouds.openstack.nova.v2_0.extensions.ServerAdminAsyncApi; import org.jclouds.openstack.nova.v2_0.extensions.FlavorExtraSpecsAsyncApi; import org.jclouds.openstack.nova.v2_0.extensions.FloatingIPAsyncApi; import org.jclouds.openstack.nova.v2_0.extensions.HostAdministrationAsyncApi; @@ -155,7 +155,7 @@ public interface NovaAsyncApi { * Provides asynchronous access to Server Admin Actions features. */ @Delegate - Optional getAdminActionsExtensionForZone( + Optional getServerAdminExtensionForZone( @EndpointParam(parser = ZoneToEndpoint.class) @Nullable String zone); /** diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/binders/BindMetadataToJsonPayload.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/binders/BindMetadataToJsonPayload.java new file mode 100644 index 0000000000..7030261e04 --- /dev/null +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/binders/BindMetadataToJsonPayload.java @@ -0,0 +1,49 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.nova.v2_0.binders; + +import java.util.Map; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.http.HttpRequest; +import org.jclouds.json.Json; +import org.jclouds.rest.binders.BindToJsonPayload; + +import com.google.common.collect.ImmutableMap; + +/** + * + * @author Adrian Cole + */ +@Singleton +public class BindMetadataToJsonPayload extends BindToJsonPayload { + + @Inject + public BindMetadataToJsonPayload(Json jsonBinder) { + super(jsonBinder); + } + + @Override + public R bindToRequest(R request, Map postParams) { + return bindToRequest(request, + (Object) ImmutableMap.of("metadata", ImmutableMap.of(postParams.get("key"), postParams.get("value")))); + } +} \ No newline at end of file diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/NovaComputeService.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/NovaComputeService.java index 211404391e..d219d728f8 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/NovaComputeService.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/NovaComputeService.java @@ -21,6 +21,7 @@ import static com.google.common.base.Preconditions.checkNotNull; import static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_RUNNING; import static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_SUSPENDED; import static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_TERMINATED; +import static org.jclouds.openstack.nova.v2_0.predicates.KeyPairPredicates.nameMatches; import java.util.Map; import java.util.Set; @@ -65,7 +66,6 @@ import org.jclouds.openstack.nova.v2_0.domain.zonescoped.SecurityGroupInZone; import org.jclouds.openstack.nova.v2_0.domain.zonescoped.ZoneAndName; import org.jclouds.openstack.nova.v2_0.extensions.KeyPairApi; import org.jclouds.openstack.nova.v2_0.extensions.SecurityGroupApi; -import org.jclouds.openstack.nova.v2_0.predicates.KeyPairPredicates; import org.jclouds.openstack.nova.v2_0.predicates.SecurityGroupPredicates; import org.jclouds.scriptbuilder.functions.InitAdminAccess; @@ -138,11 +138,11 @@ public class NovaComputeService extends BaseComputeService { Optional securityGroupApi = novaApi.getSecurityGroupExtensionForZone(zoneId); if (securityGroupApi.isPresent()) { for (String group : groups) { - for (SecurityGroup securityGroup : Iterables.filter(securityGroupApi.get().listSecurityGroups(), + for (SecurityGroup securityGroup : Iterables.filter(securityGroupApi.get().list(), SecurityGroupPredicates.nameMatches(namingConvention.create().containsGroup(group)))) { ZoneAndName zoneAndName = ZoneAndName.fromZoneAndName(zoneId, securityGroup.getName()); logger.debug(">> deleting securityGroup(%s)", zoneAndName); - securityGroupApi.get().deleteSecurityGroup(securityGroup.getId()); + securityGroupApi.get().delete(securityGroup.getId()); // TODO: test this clear happens securityGroupMap.invalidate(zoneAndName); logger.debug("<< deleted securityGroup(%s)", zoneAndName); @@ -155,16 +155,13 @@ public class NovaComputeService extends BaseComputeService { Optional keyPairApi = novaApi.getKeyPairExtensionForZone(zoneId); if (keyPairApi.isPresent()) { for (String group : groups) { - for (Map view : keyPairApi.get().listKeyPairs()) { - for (KeyPair pair : Iterables.filter(view.values(), - KeyPairPredicates.nameMatches(namingConvention.create().containsGroup(group)))) { - ZoneAndName zoneAndName = ZoneAndName.fromZoneAndName(zoneId, pair.getName()); - logger.debug(">> deleting keypair(%s)", zoneAndName); - keyPairApi.get().deleteKeyPair(pair.getName()); - // TODO: test this clear happens - keyPairCache.invalidate(zoneAndName); - logger.debug("<< deleted keypair(%s)", zoneAndName); - } + for (KeyPair pair : keyPairApi.get().list().filter(nameMatches(namingConvention.create().containsGroup(group)))) { + ZoneAndName zoneAndName = ZoneAndName.fromZoneAndName(zoneId, pair.getName()); + logger.debug(">> deleting keypair(%s)", zoneAndName); + keyPairApi.get().delete(pair.getName()); + // TODO: test this clear happens + keyPairCache.invalidate(zoneAndName); + logger.debug("<< deleted keypair(%s)", zoneAndName); } keyPairCache.invalidate(ZoneAndName.fromZoneAndName(zoneId, namingConvention.create().sharedNameForGroup(group))); diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/NovaComputeServiceAdapter.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/NovaComputeServiceAdapter.java index f2b51380d5..f934682efe 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/NovaComputeServiceAdapter.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/NovaComputeServiceAdapter.java @@ -124,8 +124,8 @@ public class NovaComputeServiceAdapter implements String flavorId = template.getHardware().getProviderId(); logger.debug(">> creating new server zone(%s) name(%s) image(%s) flavor(%s) options(%s)", zoneId, name, imageId, flavorId, options); - ServerCreated lightweightServer = novaApi.getServerApiForZone(zoneId).createServer(name, imageId, flavorId, options); - Server server = novaApi.getServerApiForZone(zoneId).getServer(lightweightServer.getId()); + ServerCreated lightweightServer = novaApi.getServerApiForZone(zoneId).create(name, imageId, flavorId, options); + Server server = novaApi.getServerApiForZone(zoneId).get(lightweightServer.getId()); logger.trace("<< server(%s)", server.getId()); @@ -140,7 +140,7 @@ public class NovaComputeServiceAdapter implements public Iterable listHardwareProfiles() { Builder builder = ImmutableSet.builder(); for (final String zoneId : zoneIds.get()) { - builder.addAll(transform(novaApi.getFlavorApiForZone(zoneId).listFlavorsInDetail(), + builder.addAll(transform(novaApi.getFlavorApiForZone(zoneId).listInDetail().concat(), new Function() { @Override @@ -159,7 +159,7 @@ public class NovaComputeServiceAdapter implements Set zones = zoneIds.get(); checkState(zones.size() > 0, "no zones found in supplier %s", zoneIds); for (final String zoneId : zones) { - Set images = novaApi.getImageApiForZone(zoneId).listImagesInDetail(); + Set images = novaApi.getImageApiForZone(zoneId).listInDetail().concat().toImmutableSet(); if (images.size() == 0) { logger.debug("no images found in zone %s", zoneId); continue; @@ -194,8 +194,8 @@ public class NovaComputeServiceAdapter implements public Iterable listNodes() { Builder builder = ImmutableSet.builder(); for (final String zoneId : zoneIds.get()) { - builder.addAll(transform(novaApi.getServerApiForZone(zoneId).listServersInDetail(), - new Function() { + builder.addAll(novaApi.getServerApiForZone(zoneId).listInDetail().concat() + .transform(new Function() { @Override public ServerInZone apply(Server arg0) { @@ -216,14 +216,14 @@ public class NovaComputeServiceAdapter implements @Override public ServerInZone getNode(String id) { ZoneAndId zoneAndId = ZoneAndId.fromSlashEncoded(id); - Server server = novaApi.getServerApiForZone(zoneAndId.getZone()).getServer(zoneAndId.getId()); + Server server = novaApi.getServerApiForZone(zoneAndId.getZone()).get(zoneAndId.getId()); return server == null ? null : new ServerInZone(server, zoneAndId.getZone()); } @Override public ImageInZone getImage(String id) { ZoneAndId zoneAndId = ZoneAndId.fromSlashEncoded(id); - Image image = novaApi.getImageApiForZone(zoneAndId.getZone()).getImage(zoneAndId.getId()); + Image image = novaApi.getImageApiForZone(zoneAndId.getZone()).get(zoneAndId.getId()); return image == null ? null : new ImageInZone(image, zoneAndId.getZone()); } @@ -237,20 +237,20 @@ public class NovaComputeServiceAdapter implements logger.warn(e, "<< error removing and deallocating ip from node(%s): %s", id, e.getMessage()); } } - novaApi.getServerApiForZone(zoneAndId.getZone()).deleteServer(zoneAndId.getId()); + novaApi.getServerApiForZone(zoneAndId.getZone()).delete(zoneAndId.getId()); } @Override public void rebootNode(String id) { ZoneAndId zoneAndId = ZoneAndId.fromSlashEncoded(id); - novaApi.getServerApiForZone(zoneAndId.getZone()).rebootServer(zoneAndId.getId(), RebootType.HARD); + novaApi.getServerApiForZone(zoneAndId.getZone()).reboot(zoneAndId.getId(), RebootType.HARD); } @Override public void resumeNode(String id) { ZoneAndId zoneAndId = ZoneAndId.fromSlashEncoded(id); - if (novaApi.getAdminActionsExtensionForZone(zoneAndId.getZone()).isPresent()) { - novaApi.getAdminActionsExtensionForZone(zoneAndId.getZone()).get().resumeServer(zoneAndId.getId()); + if (novaApi.getServerAdminExtensionForZone(zoneAndId.getZone()).isPresent()) { + novaApi.getServerAdminExtensionForZone(zoneAndId.getZone()).get().resume(zoneAndId.getId()); } throw new UnsupportedOperationException("resume requires installation of the Admin Actions extension"); } @@ -258,8 +258,8 @@ public class NovaComputeServiceAdapter implements @Override public void suspendNode(String id) { ZoneAndId zoneAndId = ZoneAndId.fromSlashEncoded(id); - if (novaApi.getAdminActionsExtensionForZone(zoneAndId.getZone()).isPresent()) { - novaApi.getAdminActionsExtensionForZone(zoneAndId.getZone()).get().suspendServer(zoneAndId.getId()); + if (novaApi.getServerAdminExtensionForZone(zoneAndId.getZone()).isPresent()) { + novaApi.getServerAdminExtensionForZone(zoneAndId.getZone()).get().suspend(zoneAndId.getId()); } throw new UnsupportedOperationException("suspend requires installation of the Admin Actions extension"); } diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/extensions/NovaImageExtension.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/extensions/NovaImageExtension.java index 4e71c979bc..7670d54925 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/extensions/NovaImageExtension.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/extensions/NovaImageExtension.java @@ -84,7 +84,7 @@ public class NovaImageExtension implements ImageExtension { @Override public ImageTemplate buildImageTemplateFromNode(String name, final String id) { ZoneAndId zoneAndId = ZoneAndId.fromSlashEncoded(id); - Server server = novaApi.getServerApiForZone(zoneAndId.getZone()).getServer(zoneAndId.getId()); + Server server = novaApi.getServerApiForZone(zoneAndId.getZone()).get(zoneAndId.getId()); if (server == null) throw new NoSuchElementException("Cannot find server with id: " + zoneAndId); CloneImageTemplate template = new ImageTemplateBuilder.CloneImageTemplateBuilder().nodeId(id).name(name).build(); @@ -119,7 +119,7 @@ public class NovaImageExtension implements ImageExtension { public boolean deleteImage(String id) { ZoneAndId zoneAndId = ZoneAndId.fromSlashEncoded(id); try { - this.novaApi.getImageApiForZone(zoneAndId.getZone()).deleteImage(zoneAndId.getId()); + this.novaApi.getImageApiForZone(zoneAndId.getZone()).delete(zoneAndId.getId()); } catch (Exception e) { return false; } diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/functions/AllocateAndAddFloatingIpToNode.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/functions/AllocateAndAddFloatingIpToNode.java index 0e1193d05b..b02650dfd8 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/functions/AllocateAndAddFloatingIpToNode.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/functions/AllocateAndAddFloatingIpToNode.java @@ -82,11 +82,11 @@ public class AllocateAndAddFloatingIpToNode implements FloatingIP ip = null; try { logger.debug(">> allocating or reassigning floating ip for node(%s)", node.getId()); - ip = floatingIpApi.allocate(); + ip = floatingIpApi.create(); } catch (InsufficientResourcesException e) { logger.trace("<< [%s] allocating a new floating ip for node(%s)", e.getMessage(), node.getId()); logger.trace(">> searching for existing, unassigned floating ip for node(%s)", node.getId()); - ArrayList unassignedIps = Lists.newArrayList(Iterables.filter(floatingIpApi.listFloatingIPs(), + ArrayList unassignedIps = Lists.newArrayList(Iterables.filter(floatingIpApi.list(), new Predicate() { @Override @@ -101,7 +101,7 @@ public class AllocateAndAddFloatingIpToNode implements } logger.debug(">> adding floatingIp(%s) to node(%s)", ip.getIp(), node.getId()); - floatingIpApi.addFloatingIPToServer(ip.getIp(), node.getProviderId()); + floatingIpApi.addToServer(ip.getIp(), node.getProviderId()); input.set(NodeMetadataBuilder.fromNodeMetadata(node).publicAddresses(ImmutableSet.of(ip.getIp())).build()); floatingIpCache.invalidate(ZoneAndId.fromSlashEncoded(node.getId())); return input; diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/functions/CreateSecurityGroupIfNeeded.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/functions/CreateSecurityGroupIfNeeded.java index fb9aeb824f..015085105f 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/functions/CreateSecurityGroupIfNeeded.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/functions/CreateSecurityGroupIfNeeded.java @@ -67,17 +67,17 @@ public class CreateSecurityGroupIfNeeded implements Function> creating securityGroup %s", zoneSecurityGroupNameAndPorts); try { - SecurityGroup securityGroup = api.get().createSecurityGroupWithNameAndDescription( + SecurityGroup securityGroup = api.get().createWithDescription( zoneSecurityGroupNameAndPorts.getName(), zoneSecurityGroupNameAndPorts.getName()); logger.debug("<< created securityGroup(%s)", securityGroup); for (int port : zoneSecurityGroupNameAndPorts.getPorts()) { authorizeGroupToItselfAndAllIPsToTCPPort(api.get(), securityGroup, port); } - return new SecurityGroupInZone(api.get().getSecurityGroup(securityGroup.getId()), zoneId); + return new SecurityGroupInZone(api.get().get(securityGroup.getId()), zoneId); } catch (IllegalStateException e) { logger.trace("<< trying to find securityGroup(%s): %s", zoneSecurityGroupNameAndPorts, e.getMessage()); - SecurityGroup group = find(api.get().listSecurityGroups(), nameEquals(zoneSecurityGroupNameAndPorts + SecurityGroup group = find(api.get().list(), nameEquals(zoneSecurityGroupNameAndPorts .getName())); logger.debug("<< reused securityGroup(%s)", group.getId()); return new SecurityGroupInZone(group, zoneId); @@ -88,7 +88,7 @@ public class CreateSecurityGroupIfNeeded implements Function> authorizing securityGroup(%s) permission to 0.0.0.0/0 on port %d", securityGroup, port); - securityGroupApi.createSecurityGroupRuleAllowingCidrBlock(securityGroup.getId(), Ingress.builder().ipProtocol( + securityGroupApi.createRuleAllowingCidrBlock(securityGroup.getId(), Ingress.builder().ipProtocol( IpProtocol.TCP).fromPort(port).toPort(port).build(), "0.0.0.0/0"); logger.debug("<< authorized securityGroup(%s) permission to 0.0.0.0/0 on port %d", securityGroup, port); diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/functions/RemoveFloatingIpFromNodeAndDeallocate.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/functions/RemoveFloatingIpFromNodeAndDeallocate.java index 00f93cbc25..5a81b499d2 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/functions/RemoveFloatingIpFromNodeAndDeallocate.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/functions/RemoveFloatingIpFromNodeAndDeallocate.java @@ -61,9 +61,9 @@ public class RemoveFloatingIpFromNodeAndDeallocate implements Function> removing floatingIp(%s) from node(%s)", ip, id); - floatingIpApi.removeFloatingIPFromServer(ip.getIp(), id.getId()); + floatingIpApi.removeFromServer(ip.getIp(), id.getId()); logger.debug(">> deallocating floatingIp(%s)", ip); - floatingIpApi.deallocate(ip.getId()); + floatingIpApi.delete(ip.getId()); } floatingIpCache.invalidate(id); return id; @@ -71,6 +71,6 @@ public class RemoveFloatingIpFromNodeAndDeallocate implements Function { KeyPair keyPair = null; while (keyPair == null) { try { - keyPair = api.get().createKeyPair(namingConvention.createWithoutPrefix().uniqueNameForGroup(prefix)); + keyPair = api.get().create(namingConvention.createWithoutPrefix().uniqueNameForGroup(prefix)); } catch (IllegalStateException e) { } diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/loaders/LoadFloatingIpsForInstance.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/loaders/LoadFloatingIpsForInstance.java index d773bd5b11..0a8ebb8c80 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/loaders/LoadFloatingIpsForInstance.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/loaders/LoadFloatingIpsForInstance.java @@ -30,7 +30,6 @@ import com.google.common.base.Optional; import com.google.common.base.Predicate; import com.google.common.cache.CacheLoader; import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Iterables; /** * Each zone may or may not have the floating ip function present. In order to safely proceed, we @@ -53,7 +52,7 @@ public class LoadFloatingIpsForInstance extends CacheLoader ipApiOptional = api.getFloatingIPExtensionForZone(zone); if (ipApiOptional.isPresent()) { - return Iterables.filter(ipApiOptional.get().listFloatingIPs(), + return ipApiOptional.get().list().filter( new Predicate() { @Override public boolean apply(FloatingIP input) { diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/options/NovaTemplateOptions.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/options/NovaTemplateOptions.java index 4de15d5408..32aa332546 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/options/NovaTemplateOptions.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/options/NovaTemplateOptions.java @@ -162,7 +162,7 @@ public class NovaTemplateOptions extends TemplateOptions implements Cloneable { /** *

Note

* - * This requires that {@link NovaApi#getFloatingIPExtensionForZone(String)} to return + * This requires that {@link NovaApi#getExtensionForZone(String)} to return * {@link Optional#isPresent present} * * @return true if auto assignment of a floating ip to each vm is enabled diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/predicates/GetImageWhenImageInZoneHasActiveStatusPredicateWithResult.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/predicates/GetImageWhenImageInZoneHasActiveStatusPredicateWithResult.java index 5f2f38d1a7..254b405572 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/predicates/GetImageWhenImageInZoneHasActiveStatusPredicateWithResult.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/predicates/GetImageWhenImageInZoneHasActiveStatusPredicateWithResult.java @@ -35,7 +35,6 @@ import org.jclouds.predicates.PredicateWithResult; import com.google.common.base.Function; import com.google.common.base.Predicate; -import com.google.common.collect.Iterables; /** * @author David Alves @@ -89,7 +88,7 @@ public final class GetImageWhenImageInZoneHasActiveStatusPredicateWithResult imp } public org.jclouds.openstack.nova.v2_0.domain.Image findImage(final ZoneAndId zoneAndId) { - return Iterables.tryFind(api.getImageApiForZone(zoneAndId.getZone()).listImagesInDetail(), + return api.getImageApiForZone(zoneAndId.getZone()).listInDetail().concat().firstMatch( new Predicate() { @Override public boolean apply(org.jclouds.openstack.nova.v2_0.domain.Image input) { diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/strategy/ApplyNovaTemplateOptionsCreateNodesWithGroupEncodedIntoNameThenAddToSet.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/strategy/ApplyNovaTemplateOptionsCreateNodesWithGroupEncodedIntoNameThenAddToSet.java index 4958740560..dbb184117e 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/strategy/ApplyNovaTemplateOptionsCreateNodesWithGroupEncodedIntoNameThenAddToSet.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/compute/strategy/ApplyNovaTemplateOptionsCreateNodesWithGroupEncodedIntoNameThenAddToSet.java @@ -65,7 +65,7 @@ import com.google.common.primitives.Ints; public class ApplyNovaTemplateOptionsCreateNodesWithGroupEncodedIntoNameThenAddToSet extends CreateNodesWithGroupEncodedIntoNameThenAddToSet { - private final AllocateAndAddFloatingIpToNode allocateAndAddFloatingIpToNode; + private final AllocateAndAddFloatingIpToNode createAndAddFloatingIpToNode; private final LoadingCache securityGroupCache; private final LoadingCache keyPairCache; private final NovaApi novaApi; @@ -77,15 +77,15 @@ public class ApplyNovaTemplateOptionsCreateNodesWithGroupEncodedIntoNameThenAddT GroupNamingConvention.Factory namingConvention, CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap.Factory customizeNodeAndAddToGoodMapOrPutExceptionIntoBadMapFactory, @Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor, - AllocateAndAddFloatingIpToNode allocateAndAddFloatingIpToNode, + AllocateAndAddFloatingIpToNode createAndAddFloatingIpToNode, LoadingCache securityGroupCache, LoadingCache keyPairCache, NovaApi novaApi) { super(addNodeWithTagStrategy, listNodesStrategy, namingConvention, executor, customizeNodeAndAddToGoodMapOrPutExceptionIntoBadMapFactory); this.securityGroupCache = checkNotNull(securityGroupCache, "securityGroupCache"); this.keyPairCache = checkNotNull(keyPairCache, "keyPairCache"); - this.allocateAndAddFloatingIpToNode = checkNotNull(allocateAndAddFloatingIpToNode, - "allocateAndAddFloatingIpToNode"); + this.createAndAddFloatingIpToNode = checkNotNull(createAndAddFloatingIpToNode, + "createAndAddFloatingIpToNode"); this.novaApi = checkNotNull(novaApi, "novaApi"); } @@ -153,7 +153,7 @@ public class ApplyNovaTemplateOptionsCreateNodesWithGroupEncodedIntoNameThenAddT NovaTemplateOptions templateOptions = NovaTemplateOptions.class.cast(template.getOptions()); if (templateOptions.shouldAutoAssignFloatingIp()) { - return Futures.compose(future, allocateAndAddFloatingIpToNode, executor); + return Futures.compose(future, createAndAddFloatingIpToNode, executor); } else { return future; } diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/config/NovaProperties.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/config/NovaProperties.java index e8548caebd..3275b62b01 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/config/NovaProperties.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/config/NovaProperties.java @@ -31,10 +31,10 @@ public class NovaProperties { public static final String TIMEOUT_SECURITYGROUP_PRESENT = "jclouds.openstack-nova.timeout.securitygroup-present"; /** - * Whenever a node is created, automatically allocate and assign a floating ip address, also - * deallocate when the node is destroyed. + * Whenever a node is created, automatically create and assign a floating ip address, also + * delete when the node is destroyed. */ - public static final String AUTO_ALLOCATE_FLOATING_IPS = "jclouds.openstack-nova.auto-allocate-floating-ips"; + public static final String AUTO_ALLOCATE_FLOATING_IPS = "jclouds.openstack-nova.auto-create-floating-ips"; /** * Whenever a node is created, automatically generate keypairs for groups, as needed, also diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/config/NovaRestClientModule.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/config/NovaRestClientModule.java index 0bef0894e7..e6b242e20c 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/config/NovaRestClientModule.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/config/NovaRestClientModule.java @@ -32,8 +32,8 @@ import org.jclouds.http.annotation.Redirection; import org.jclouds.http.annotation.ServerError; import org.jclouds.openstack.nova.v2_0.NovaApi; import org.jclouds.openstack.nova.v2_0.NovaAsyncApi; -import org.jclouds.openstack.nova.v2_0.extensions.AdminActionsApi; -import org.jclouds.openstack.nova.v2_0.extensions.AdminActionsAsyncApi; +import org.jclouds.openstack.nova.v2_0.extensions.ServerAdminApi; +import org.jclouds.openstack.nova.v2_0.extensions.ServerAdminAsyncApi; import org.jclouds.openstack.nova.v2_0.extensions.ExtensionNamespaces; import org.jclouds.openstack.nova.v2_0.extensions.FlavorExtraSpecsApi; import org.jclouds.openstack.nova.v2_0.extensions.FlavorExtraSpecsAsyncApi; @@ -106,7 +106,7 @@ public class NovaRestClientModule ext .put(VolumeApi.class, VolumeAsyncApi.class) .put(VirtualInterfaceApi.class, VirtualInterfaceAsyncApi.class) .put(ServerWithSecurityGroupsApi.class, ServerWithSecurityGroupsAsyncApi.class) - .put(AdminActionsApi.class, AdminActionsAsyncApi.class) + .put(ServerAdminApi.class, ServerAdminAsyncApi.class) .put(HostAggregateApi.class, HostAggregateAsyncApi.class) .put(FlavorExtraSpecsApi.class, FlavorExtraSpecsAsyncApi.class) .put(QuotaApi.class, QuotaAsyncApi.class) @@ -114,6 +114,7 @@ public class NovaRestClientModule ext .put(VolumeTypeApi.class, VolumeTypeAsyncApi.class) .build(); + @SuppressWarnings("unchecked") public NovaRestClientModule() { super(TypeToken.class.cast(TypeToken.of(NovaApi.class)), TypeToken.class.cast(TypeToken.of(NovaAsyncApi.class)), DELEGATE_MAP); } @@ -125,7 +126,6 @@ public class NovaRestClientModule ext @Override protected void configure() { - install(new NovaParserModule()); bind(ImplicitOptionalConverter.class).to(PresentWhenExtensionAnnotationNamespaceEqualsAnyNamespaceInExtensionsSet.class); super.configure(); } @@ -172,7 +172,7 @@ public class NovaRestClientModule ext .build(new CacheLoader>() { @Override public Set load(String key) throws Exception { - return novaApi.get().getExtensionApiForZone(key).listExtensions(); + return novaApi.get().getExtensionApiForZone(key).list(); } }); } diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/Flavor.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/Flavor.java index 98137e4318..80e09bd822 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/Flavor.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/Flavor.java @@ -36,7 +36,7 @@ import com.google.common.base.Optional; * * @author Jeremy Daggett * @see */ public class Flavor extends Resource { diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/Quotas.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/Quota.java similarity index 89% rename from apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/Quotas.java rename to apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/Quota.java index 3b0d518008..f52c13708e 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/Quotas.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/Quota.java @@ -32,7 +32,7 @@ import com.google.common.base.Objects.ToStringHelper; * * @see org.jclouds.openstack.nova.v2_0.extensions.QuotaApi */ -public class Quotas { +public class Quota { public static Builder builder() { return new ConcreteBuilder(); @@ -60,7 +60,7 @@ public class Quotas { protected int keyPairs; /** - * @see Quotas#getId() + * @see Quota#getId() */ public T id(String id) { this.id = id; @@ -68,7 +68,7 @@ public class Quotas { } /** - * @see Quotas#getMetadataItems() + * @see Quota#getMetadatas() */ public T metadataItems(int metadataItems) { this.metadataItems = metadataItems; @@ -76,7 +76,7 @@ public class Quotas { } /** - * @see Quotas#getInjectedFileContentBytes() + * @see Quota#getInjectedFileContentBytes() */ public T injectedFileContentBytes(int injectedFileContentBytes) { this.injectedFileContentBytes = injectedFileContentBytes; @@ -84,7 +84,7 @@ public class Quotas { } /** - * @see Quotas#getVolumes() + * @see Quota#getVolumes() */ public T volumes(int volumes) { this.volumes = volumes; @@ -92,7 +92,7 @@ public class Quotas { } /** - * @see Quotas#getGigabytes() + * @see Quota#getGigabytes() */ public T gigabytes(int gigabytes) { this.gigabytes = gigabytes; @@ -100,7 +100,7 @@ public class Quotas { } /** - * @see Quotas#getRam() + * @see Quota#getRam() */ public T ram(int ram) { this.ram = ram; @@ -108,7 +108,7 @@ public class Quotas { } /** - * @see Quotas#getFloatingIps() + * @see Quota#getFloatingIps() */ public T floatingIps(int floatingIps) { this.floatingIps = floatingIps; @@ -116,7 +116,7 @@ public class Quotas { } /** - * @see Quotas#getInstances() + * @see Quota#getInstances() */ public T instances(int instances) { this.instances = instances; @@ -124,7 +124,7 @@ public class Quotas { } /** - * @see Quotas#getInjectedFiles() + * @see Quota#getInjectedFiles() */ public T injectedFiles(int injectedFiles) { this.injectedFiles = injectedFiles; @@ -132,7 +132,7 @@ public class Quotas { } /** - * @see Quotas#getCores() + * @see Quota#getCores() */ public T cores(int cores) { this.cores = cores; @@ -140,7 +140,7 @@ public class Quotas { } /** - * @see Quotas#getSecurityGroups() + * @see Quota#getSecurityGroups() */ public T securityGroups(int securityGroups) { this.securityGroups = securityGroups; @@ -148,7 +148,7 @@ public class Quotas { } /** - * @see Quotas#getSecurityGroupRules() + * @see Quota#getSecurityGroupRules() */ public T securityGroupRules(int securityGroupRules) { this.securityGroupRules = securityGroupRules; @@ -156,21 +156,21 @@ public class Quotas { } /** - * @see Quotas#getKeyPairs() + * @see Quota#getKeyPairs() */ public T keyPairs(int keyPairs) { this.keyPairs = keyPairs; return self(); } - public Quotas build() { - return new Quotas(id, metadataItems, injectedFileContentBytes, volumes, gigabytes, ram, floatingIps, instances, injectedFiles, cores, securityGroups, securityGroupRules, keyPairs); + public Quota build() { + return new Quota(id, metadataItems, injectedFileContentBytes, volumes, gigabytes, ram, floatingIps, instances, injectedFiles, cores, securityGroups, securityGroupRules, keyPairs); } - public T fromQuotas(Quotas in) { + public T fromQuotas(Quota in) { return this .id(in.getId()) - .metadataItems(in.getMetadataItems()) + .metadataItems(in.getMetadatas()) .injectedFileContentBytes(in.getInjectedFileContentBytes()) .volumes(in.getVolumes()) .gigabytes(in.getGigabytes()) @@ -216,7 +216,7 @@ public class Quotas { @ConstructorProperties({ "id", "metadata_items", "injected_file_content_bytes", "volumes", "gigabytes", "ram", "floating_ips", "instances", "injected_files", "cores", "security_groups", "security_group_rules", "key_pairs" }) - protected Quotas(String id, int metadataItems, int injectedFileContentBytes, int volumes, int gigabytes, int ram, int floatingIps, int instances, int injectedFiles, int cores, int securityGroups, int securityGroupRules, int keyPairs) { + protected Quota(String id, int metadataItems, int injectedFileContentBytes, int volumes, int gigabytes, int ram, int floatingIps, int instances, int injectedFiles, int cores, int securityGroups, int securityGroupRules, int keyPairs) { this.id = checkNotNull(id, "id"); this.metadataItems = metadataItems; this.injectedFileContentBytes = injectedFileContentBytes; @@ -242,7 +242,7 @@ public class Quotas { /** * The limit of the number of metadata items for the tenant */ - public int getMetadataItems() { + public int getMetadatas() { return this.metadataItems; } @@ -329,7 +329,7 @@ public class Quotas { public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; - Quotas that = Quotas.class.cast(obj); + Quota that = Quota.class.cast(obj); return Objects.equal(this.id, that.id) && Objects.equal(this.metadataItems, that.metadataItems) && Objects.equal(this.injectedFileContentBytes, that.injectedFileContentBytes) diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/QuotaClass.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/QuotaClass.java index 792805dbca..0c96b81a68 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/QuotaClass.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/domain/QuotaClass.java @@ -25,7 +25,7 @@ import java.beans.ConstructorProperties; * * @see org.jclouds.openstack.nova.v2_0.extensions.QuotaClassApi */ -public class QuotaClass extends Quotas { +public class QuotaClass extends Quota { public static Builder builder() { return new ConcreteBuilder(); @@ -35,7 +35,7 @@ public class QuotaClass extends Quotas { return new ConcreteBuilder().fromQuotaClass(this); } - public static abstract class Builder> extends Quotas.Builder { + public static abstract class Builder> extends Quota.Builder { public QuotaClass build() { return new QuotaClass(id, metadataItems, injectedFileContentBytes, volumes, gigabytes, ram, floatingIps, instances, injectedFiles, cores, securityGroups, securityGroupRules, keyPairs); diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/FlavorExtraSpecsApi.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/FlavorExtraSpecsApi.java index 5e8d19dced..1274c69ce4 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/FlavorExtraSpecsApi.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/FlavorExtraSpecsApi.java @@ -22,10 +22,10 @@ import java.util.Map; import java.util.concurrent.TimeUnit; import org.jclouds.concurrent.Timeout; -import org.jclouds.openstack.keystone.v2_0.filters.AuthenticateRequest; import org.jclouds.openstack.v2_0.ServiceType; import org.jclouds.openstack.v2_0.services.Extension; -import org.jclouds.rest.annotations.RequestFilters; + +import com.google.common.annotations.Beta; /** * Provide access to extra metadata for Nova flavors. @@ -35,9 +35,9 @@ import org.jclouds.rest.annotations.RequestFilters; * @see org.jclouds.openstack.nova.v2_0.features.FlavorApi * @see org.jclouds.openstack.nova.v2_0.extensions.FlavorExtraSpecsAsyncApi */ +@Beta @Extension(of = ServiceType.COMPUTE, namespace = ExtensionNamespaces.FLAVOR_EXTRA_SPECS) @Timeout(duration = 180, timeUnit = TimeUnit.SECONDS) -@RequestFilters(AuthenticateRequest.class) public interface FlavorExtraSpecsApi { /** @@ -45,7 +45,7 @@ public interface FlavorExtraSpecsApi { * * @return the set of extra metadata for the flavor */ - Map getAllExtraSpecs(String flavorId); + Map getMetadata(String flavorId); /** * Creates or updates the extra specs for a given flavor @@ -53,7 +53,7 @@ public interface FlavorExtraSpecsApi { * @param flavorId the id of the flavor to modify * @param specs the extra specs to apply */ - Boolean setAllExtraSpecs(String flavorId, Map specs); + Boolean updateMetadata(String flavorId, Map specs); /** * Return a single extra spec value @@ -61,7 +61,7 @@ public interface FlavorExtraSpecsApi { * @param flavorId the id of the flavor to modify * @param key the extra spec key to retrieve */ - String getExtraSpec(String flavorId, String key); + String getMetadataKey(String flavorId, String key); /** * Creates or updates a single extra spec value @@ -70,7 +70,7 @@ public interface FlavorExtraSpecsApi { * @param key the extra spec key (when creating ensure this does not include whitespace or other difficult characters) * @param value the value to associate with the key */ - Boolean setExtraSpec(String flavorId, String key, String value); + Boolean updateMetadataEntry(String flavorId, String key, String value); /** * Deletes an extra spec @@ -78,6 +78,6 @@ public interface FlavorExtraSpecsApi { * @param flavorId the id of the flavor to modify * @param key the extra spec key to delete */ - Boolean deleteExtraSpec(String flavorId, String key); + Boolean deleteMetadataKey(String flavorId, String key); } diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/FlavorExtraSpecsAsyncApi.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/FlavorExtraSpecsAsyncApi.java index e58ac22fc0..d93342b0d9 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/FlavorExtraSpecsAsyncApi.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/FlavorExtraSpecsAsyncApi.java @@ -19,7 +19,6 @@ package org.jclouds.openstack.nova.v2_0.extensions; import java.util.Map; -import java.util.concurrent.TimeUnit; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; @@ -31,7 +30,6 @@ import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; -import org.jclouds.concurrent.Timeout; import org.jclouds.openstack.keystone.v2_0.filters.AuthenticateRequest; import org.jclouds.openstack.v2_0.ServiceType; import org.jclouds.openstack.v2_0.services.Extension; @@ -47,6 +45,7 @@ import org.jclouds.rest.functions.ReturnEmptyMapOnNotFoundOr404; import org.jclouds.rest.functions.ReturnFalseOnNotFoundOr404; import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; +import com.google.common.annotations.Beta; import com.google.common.util.concurrent.ListenableFuture; /** @@ -57,59 +56,59 @@ import com.google.common.util.concurrent.ListenableFuture; * @see org.jclouds.openstack.nova.v2_0.features.FlavorApi * @see FlavorExtraSpecsApi */ +@Beta @Extension(of = ServiceType.COMPUTE, namespace = ExtensionNamespaces.FLAVOR_EXTRA_SPECS) -@Timeout(duration = 180, timeUnit = TimeUnit.SECONDS) @RequestFilters(AuthenticateRequest.class) @Consumes(MediaType.APPLICATION_JSON) public interface FlavorExtraSpecsAsyncApi { /** - * @see FlavorExtraSpecsApi#getAllExtraSpecs(String) + * @see FlavorExtraSpecsApi#getMetadata(String) */ @GET @SelectJson("extra_specs") @Path("/flavors/{flavor_id}/os-extra_specs") @ExceptionParser(ReturnEmptyMapOnNotFoundOr404.class) - ListenableFuture> getAllExtraSpecs(@PathParam("flavor_id") String flavorId); + ListenableFuture> getMetadata(@PathParam("flavor_id") String flavorId); /** - * @see FlavorExtraSpecsApi#setExtraSpec(String, String, String) + * @see FlavorExtraSpecsApi#updateMetadataEntry(String, String, String) */ @POST @Path("/flavors/{flavor_id}/os-extra_specs") @Produces(MediaType.APPLICATION_JSON) @ExceptionParser(ReturnFalseOnNotFoundOr404.class) @MapBinder(BindToJsonPayload.class) - ListenableFuture setAllExtraSpecs(@PathParam("flavor_id") String flavorId, @PayloadParam("extra_specs") Map specs); + ListenableFuture updateMetadata(@PathParam("flavor_id") String flavorId, @PayloadParam("extra_specs") Map specs); /** - * @see FlavorExtraSpecsApi#getExtraSpec(String, String) + * @see FlavorExtraSpecsApi#getMetadataKey(String, String) */ @GET @Path("/flavors/{flavor_id}/os-extra_specs/{key}") @Unwrap @ExceptionParser(ReturnNullOnNotFoundOr404.class) - ListenableFuture getExtraSpec(@PathParam("flavor_id") String flavorId, @PathParam("key") String key); + ListenableFuture getMetadataKey(@PathParam("flavor_id") String flavorId, @PathParam("key") String key); /** - * @see FlavorExtraSpecsApi#setExtraSpec(String, String, String) + * @see FlavorExtraSpecsApi#updateMetadataEntry(String, String, String) */ @PUT @Path("/flavors/{flavor_id}/os-extra_specs/{key}") @Produces(MediaType.APPLICATION_JSON) @ExceptionParser(ReturnFalseOnNotFoundOr404.class) @Payload("%7B\"{key}\":\"{value}\"%7D") - ListenableFuture setExtraSpec(@PathParam("flavor_id") String flavorId, + ListenableFuture updateMetadataEntry(@PathParam("flavor_id") String flavorId, @PathParam("key") @PayloadParam("key") String key, @PayloadParam("value") String value); /** - * @see FlavorExtraSpecsApi#deleteExtraSpec(String, String) + * @see FlavorExtraSpecsApi#deleteMetadataKey(String, String) */ @DELETE @Path("/flavors/{flavor_id}/os-extra_specs/{key}") @ExceptionParser(ReturnFalseOnNotFoundOr404.class) - ListenableFuture deleteExtraSpec(@PathParam("flavor_id") String flavorId, + ListenableFuture deleteMetadataKey(@PathParam("flavor_id") String flavorId, @PathParam("key") String key); } diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/FloatingIPApi.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/FloatingIPApi.java index 45ee544aad..33987cf9a7 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/FloatingIPApi.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/FloatingIPApi.java @@ -18,7 +18,6 @@ */ package org.jclouds.openstack.nova.v2_0.extensions; -import java.util.Set; import java.util.concurrent.TimeUnit; import org.jclouds.concurrent.Timeout; @@ -26,6 +25,9 @@ import org.jclouds.openstack.nova.v2_0.domain.FloatingIP; import org.jclouds.openstack.v2_0.ServiceType; import org.jclouds.openstack.v2_0.services.Extension; +import com.google.common.annotations.Beta; +import com.google.common.collect.FluentIterable; + /** * Provides synchronous access to Floating IPs. *

@@ -33,6 +35,7 @@ import org.jclouds.openstack.v2_0.services.Extension; * @see FloatingIPAsyncApi * @author Jeremy Daggett */ +@Beta @Extension(of = ServiceType.COMPUTE, namespace = ExtensionNamespaces.FLOATING_IPS) @Timeout(duration = 180, timeUnit = TimeUnit.SECONDS) public interface FloatingIPApi { @@ -42,29 +45,29 @@ public interface FloatingIPApi { * * @return all Floating IPs */ - Set listFloatingIPs(); + FluentIterable list(); /** * Get a specific Floating IP address * * @return all Floating IPs */ - FloatingIP getFloatingIP(String id); + FloatingIP get(String id); /** * Allocate a Floating IP address * - * @return a newly allocated FloatingIP + * @return a newly created FloatingIP */ - FloatingIP allocate(); + FloatingIP create(); /** - * Deallocate a Floating IP address + * Decreate a Floating IP address * * @param id * the Floating IP id */ - void deallocate(String id); + void delete(String id); /** * Add a Floating IP address to a Server @@ -76,7 +79,7 @@ public interface FloatingIPApi { * * NOTE: Possibly move this to ServerApi? */ - void addFloatingIPToServer(String address, String serverId); + void addToServer(String address, String serverId); /** * Remove a Floating IP address from a Server @@ -88,5 +91,5 @@ public interface FloatingIPApi { * * NOTE: Possibly move this to ServerApi? */ - void removeFloatingIPFromServer(String address, String serverId); + void removeFromServer(String address, String serverId); } diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/FloatingIPAsyncApi.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/FloatingIPAsyncApi.java index d0db242d20..391de9fdd2 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/FloatingIPAsyncApi.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/FloatingIPAsyncApi.java @@ -18,8 +18,6 @@ */ package org.jclouds.openstack.nova.v2_0.extensions; -import java.util.Set; - import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; @@ -40,9 +38,11 @@ import org.jclouds.rest.annotations.PayloadParam; import org.jclouds.rest.annotations.RequestFilters; import org.jclouds.rest.annotations.SelectJson; import org.jclouds.rest.annotations.SkipEncoding; -import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404; +import org.jclouds.rest.functions.ReturnEmptyFluentIterableOnNotFoundOr404; import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; +import com.google.common.annotations.Beta; +import com.google.common.collect.FluentIterable; import com.google.common.util.concurrent.ListenableFuture; /** @@ -57,33 +57,34 @@ import com.google.common.util.concurrent.ListenableFuture; * @see * @see */ +@Beta @Extension(of = ServiceType.COMPUTE, namespace = ExtensionNamespaces.FLOATING_IPS) @SkipEncoding( { '/', '=' }) @RequestFilters(AuthenticateRequest.class) public interface FloatingIPAsyncApi { /** - * @see FloatingIPApi#listFloatingIPs + * @see FloatingIPApi#list */ @GET @Path("/os-floating-ips") @SelectJson("floating_ips") @Consumes(MediaType.APPLICATION_JSON) - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> listFloatingIPs(); + @ExceptionParser(ReturnEmptyFluentIterableOnNotFoundOr404.class) + ListenableFuture> list(); /** - * @see FloatingIPApi#getFloatingIP + * @see FloatingIPApi#get */ @GET @Path("/os-floating-ips/{id}") @SelectJson("floating_ip") @Consumes(MediaType.APPLICATION_JSON) @ExceptionParser(ReturnNullOnNotFoundOr404.class) - ListenableFuture getFloatingIP(@PathParam("id") String id); + ListenableFuture get(@PathParam("id") String id); /** - * @see FloatingIPApi#allocate + * @see FloatingIPApi#create */ @POST @Path("/os-floating-ips") @@ -92,37 +93,37 @@ public interface FloatingIPAsyncApi { @Produces(MediaType.APPLICATION_JSON) @ExceptionParser(ReturnNullOnNotFoundOr404.class) @Payload("{}") - ListenableFuture allocate(); + ListenableFuture create(); /** - * @see FloatingIPApi#deallocate + * @see FloatingIPApi#delete */ @DELETE @Consumes(MediaType.APPLICATION_JSON) @ExceptionParser(ReturnNullOnNotFoundOr404.class) @Path("/os-floating-ips/{id}") - ListenableFuture deallocate(@PathParam("id") String id); + ListenableFuture delete(@PathParam("id") String id); /** - * @see FloatingIPApi#addFloatingIPToServer + * @see FloatingIPApi#addToServer */ @POST @Path("/servers/{server}/action") @Consumes @Produces(MediaType.APPLICATION_JSON) @Payload("%7B\"addFloatingIp\":%7B\"address\":\"{address}\"%7D%7D") - ListenableFuture addFloatingIPToServer(@PayloadParam("address") String address, + ListenableFuture addToServer(@PayloadParam("address") String address, @PathParam("server") String serverId); /** - * @see FloatingIPApi#removeFloatingIPFromServer + * @see FloatingIPApi#removeFromServer */ @POST @Path("/servers/{server}/action") @Consumes @Produces(MediaType.APPLICATION_JSON) @Payload("%7B\"removeFloatingIp\":%7B\"address\":\"{address}\"%7D%7D") - ListenableFuture removeFloatingIPFromServer(@PayloadParam("address") String address, + ListenableFuture removeFromServer(@PayloadParam("address") String address, @PathParam("server") String serverId); } diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/HostAdministrationApi.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/HostAdministrationApi.java index 5b1666f7f2..1a9c594baf 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/HostAdministrationApi.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/HostAdministrationApi.java @@ -18,7 +18,6 @@ */ package org.jclouds.openstack.nova.v2_0.extensions; -import java.util.Set; import java.util.concurrent.TimeUnit; import org.jclouds.concurrent.Timeout; @@ -27,6 +26,9 @@ import org.jclouds.openstack.nova.v2_0.domain.HostResourceUsage; import org.jclouds.openstack.v2_0.ServiceType; import org.jclouds.openstack.v2_0.services.Extension; +import com.google.common.annotations.Beta; +import com.google.common.collect.FluentIterable; + /** * Provides asynchronous access to Host Administration features via the REST API. *

@@ -34,6 +36,7 @@ import org.jclouds.openstack.v2_0.services.Extension; * @author Adam Lowe * @see HostAdministrationAsyncApi */ +@Beta @Extension(of = ServiceType.COMPUTE, namespace = ExtensionNamespaces.HOSTS) @Timeout(duration = 180, timeUnit = TimeUnit.SECONDS) public interface HostAdministrationApi { @@ -43,28 +46,28 @@ public interface HostAdministrationApi { * * @return the usage information */ - Set listHosts(); + FluentIterable list(); /** * Retrieves the physical/usage resource on a specific host * * @return the usage information */ - Set getHostResourceUsage(String hostId); + FluentIterable listResourceUsage(String hostId); /** * Allow the specified host to accept new instances. * * @return true if successful */ - Boolean enableHost(String hostId); + boolean enable(String hostId); /** * Prevent the specified host from accepting new instances. * * @return true if successful */ - Boolean disableHost(String hostId); + boolean disable(String hostId); /** * Start host maintenance window. @@ -73,34 +76,34 @@ public interface HostAdministrationApi { * * @return true if successful */ - Boolean startHostMaintenance(String hostId); + boolean startMaintenance(String hostId); /** * Stop host maintenance window. * * @return true if successful */ - Boolean stopHostMaintenance(String hostId); + boolean stopMaintenance(String hostId); /** * Startup a host. * * @return true if successful */ - Boolean startupHost(String hostId); + boolean startup(String hostId); /** * Shutdown a host. * * @return true if successful */ - Boolean shutdownHost(String hostId); + boolean shutdown(String hostId); /** * Reboot a host. * * @return true if successful */ - Boolean rebootHost(String hostId); + boolean reboot(String hostId); } diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/HostAdministrationAsyncApi.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/HostAdministrationAsyncApi.java index 89ea47fa36..dcf9f9f6aa 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/HostAdministrationAsyncApi.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/HostAdministrationAsyncApi.java @@ -18,8 +18,6 @@ */ package org.jclouds.openstack.nova.v2_0.extensions; -import java.util.Set; - import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.PUT; @@ -46,8 +44,10 @@ import org.jclouds.rest.annotations.RequestFilters; import org.jclouds.rest.annotations.ResponseParser; import org.jclouds.rest.annotations.SelectJson; import org.jclouds.rest.annotations.SkipEncoding; -import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404; +import org.jclouds.rest.functions.ReturnEmptyFluentIterableOnNotFoundOr404; +import com.google.common.annotations.Beta; +import com.google.common.collect.FluentIterable; import com.google.common.util.concurrent.ListenableFuture; /** @@ -60,6 +60,7 @@ import com.google.common.util.concurrent.ListenableFuture; * @see * @see */ +@Beta @Extension(of = ServiceType.COMPUTE, namespace = ExtensionNamespaces.HOSTS) @SkipEncoding({'/', '='}) @RequestFilters(AuthenticateRequest.class) @@ -68,83 +69,83 @@ import com.google.common.util.concurrent.ListenableFuture; public interface HostAdministrationAsyncApi { /** - * @see HostAdministrationApi#listHosts() + * @see HostAdministrationApi#list() */ @GET @SelectJson("hosts") - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> listHosts(); + @ExceptionParser(ReturnEmptyFluentIterableOnNotFoundOr404.class) + ListenableFuture> list(); /** - * @see HostAdministrationApi#getHostResourceUsage(String) + * @see HostAdministrationApi#listResourceUsage(String) */ @GET @Path("/{id}") @SelectJson("host") - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> getHostResourceUsage(@PathParam("id") String hostId); + @ExceptionParser(ReturnEmptyFluentIterableOnNotFoundOr404.class) + ListenableFuture> listResourceUsage(@PathParam("id") String hostId); /** - * @see HostAdministrationApi#enableHost(String) + * @see HostAdministrationApi#enable(String) */ @PUT @Produces(MediaType.APPLICATION_JSON) @Path("/{id}") @Payload("{\"status\":\"enable\"}") @ResponseParser(StatusEnabledResponseParser.class) - ListenableFuture enableHost(@PathParam("id") String hostId); + ListenableFuture enable(@PathParam("id") String hostId); /** - * @see HostAdministrationApi#disableHost(String) + * @see HostAdministrationApi#disable(String) */ @PUT @Produces(MediaType.APPLICATION_JSON) @Path("/{id}") @Payload("{\"status\":\"disable\"}") @ResponseParser(StatusDisabledResponseParser.class) - ListenableFuture disableHost(@PathParam("id") String hostId); + ListenableFuture disable(@PathParam("id") String hostId); /** - * @see HostAdministrationApi#startHostMaintenance(String) + * @see HostAdministrationApi#startMaintenance(String) */ @PUT @Produces(MediaType.APPLICATION_JSON) @Path("/{id}") @Payload("{\"maintenance_mode\":\"enable\"}") @ResponseParser(MaintenanceModeEnabledResponseParser.class) - ListenableFuture startHostMaintenance(@PathParam("id") String hostId); + ListenableFuture startMaintenance(@PathParam("id") String hostId); /** - * @see HostAdministrationApi#stopHostMaintenance(String) + * @see HostAdministrationApi#stopMaintenance(String) */ @PUT @Produces(MediaType.APPLICATION_JSON) @Path("/{id}") @Payload("{\"maintenance_mode\":\"disable\"}") @ResponseParser(MaintenanceModeDisabledResponseParser.class) - ListenableFuture stopHostMaintenance(@PathParam("id") String hostId); + ListenableFuture stopMaintenance(@PathParam("id") String hostId); /** - * @see HostAdministrationApi#startupHost(String) + * @see HostAdministrationApi#startup(String) */ @GET @Path("/{id}/startup") @ResponseParser(PowerIsStartupResponseParser.class) - ListenableFuture startupHost(@PathParam("id") String hostId); + ListenableFuture startup(@PathParam("id") String hostId); /** - * @see HostAdministrationApi#shutdownHost(String) + * @see HostAdministrationApi#shutdown(String) */ @GET @Path("/{id}/shutdown") @ResponseParser(PowerIsShutdownResponseParser.class) - ListenableFuture shutdownHost(@PathParam("id") String hostId); + ListenableFuture shutdown(@PathParam("id") String hostId); /** - * @see HostAdministrationApi#rebootHost(String) + * @see HostAdministrationApi#reboot(String) */ @GET @Path("/{id}/reboot") @ResponseParser(PowerIsRebootResponseParser.class) - ListenableFuture rebootHost(@PathParam("id") String hostId); + ListenableFuture reboot(@PathParam("id") String hostId); } diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/HostAggregateApi.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/HostAggregateApi.java index 61bc112032..0d8ecd06f1 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/HostAggregateApi.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/HostAggregateApi.java @@ -19,15 +19,15 @@ package org.jclouds.openstack.nova.v2_0.extensions; import java.util.Map; -import java.util.Set; import java.util.concurrent.TimeUnit; import org.jclouds.concurrent.Timeout; -import org.jclouds.openstack.keystone.v2_0.filters.AuthenticateRequest; import org.jclouds.openstack.nova.v2_0.domain.HostAggregate; import org.jclouds.openstack.v2_0.ServiceType; import org.jclouds.openstack.v2_0.services.Extension; -import org.jclouds.rest.annotations.RequestFilters; + +import com.google.common.annotations.Beta; +import com.google.common.collect.FluentIterable; /** * Provide access to Host Aggregates in Nova (alias "OS-AGGREGATES") @@ -37,29 +37,29 @@ import org.jclouds.rest.annotations.RequestFilters; * @see * @see */ +@Beta @Extension(of = ServiceType.COMPUTE, namespace = ExtensionNamespaces.AGGREGATES) @Timeout(duration = 180, timeUnit = TimeUnit.SECONDS) -@RequestFilters(AuthenticateRequest.class) public interface HostAggregateApi { /** * @return the set of host aggregates. */ - Set listAggregates(); + FluentIterable list(); /** * Retrieves the details of an aggregate, hosts and metadata included. * * @return the details of the aggregate requested. */ - HostAggregate getAggregate(String id); + HostAggregate get(String id); /** * Creates an aggregate, given its name and availability zone. * * @return the newly created Aggregate */ - HostAggregate createAggregate(String name, String availabilityZone); + HostAggregate createInAvailabilityZone(String name, String availabilityZone); /** * Updates the name of an aggregate. @@ -74,7 +74,7 @@ public interface HostAggregateApi { /** * Removes an aggregate. */ - Boolean deleteAggregate(String id); + Boolean delete(String id); /** * Adds a host to an aggregate diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/HostAggregateAsyncApi.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/HostAggregateAsyncApi.java index a964b48e2a..54bd93f8fb 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/HostAggregateAsyncApi.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/HostAggregateAsyncApi.java @@ -19,8 +19,6 @@ package org.jclouds.openstack.nova.v2_0.extensions; import java.util.Map; -import java.util.Set; -import java.util.concurrent.TimeUnit; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; @@ -31,7 +29,6 @@ import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; -import org.jclouds.concurrent.Timeout; import org.jclouds.openstack.keystone.v2_0.filters.AuthenticateRequest; import org.jclouds.openstack.nova.v2_0.domain.HostAggregate; import org.jclouds.openstack.v2_0.ServiceType; @@ -41,10 +38,12 @@ import org.jclouds.rest.annotations.PayloadParam; import org.jclouds.rest.annotations.RequestFilters; import org.jclouds.rest.annotations.SelectJson; import org.jclouds.rest.annotations.WrapWith; -import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404; +import org.jclouds.rest.functions.ReturnEmptyFluentIterableOnNotFoundOr404; import org.jclouds.rest.functions.ReturnFalseOnNotFoundOr404; import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; +import com.google.common.annotations.Beta; +import com.google.common.collect.FluentIterable; import com.google.common.util.concurrent.ListenableFuture; /** @@ -53,40 +52,40 @@ import com.google.common.util.concurrent.ListenableFuture; * @author Adam Lowe * @see HostAggregateApi */ +@Beta @Extension(of = ServiceType.COMPUTE, namespace = ExtensionNamespaces.AGGREGATES) -@Timeout(duration = 180, timeUnit = TimeUnit.SECONDS) @RequestFilters(AuthenticateRequest.class) @Path("/os-aggregates") public interface HostAggregateAsyncApi { /** - * @see HostAggregateApi#listAggregates() + * @see HostAggregateApi#list() */ @GET @SelectJson("aggregates") @Consumes(MediaType.APPLICATION_JSON) - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> listAggregates(); + @ExceptionParser(ReturnEmptyFluentIterableOnNotFoundOr404.class) + ListenableFuture> list(); /** - * @see HostAggregateApi#getAggregate(String) + * @see HostAggregateApi#get(String) */ @GET @Path("/{id}") @SelectJson("aggregate") @Consumes(MediaType.APPLICATION_JSON) @ExceptionParser(ReturnNullOnNotFoundOr404.class) - ListenableFuture getAggregate(@PathParam("id") String id); + ListenableFuture get(@PathParam("id") String id); /** - * @see HostAggregateApi#createAggregate(String, String) + * @see HostAggregateApi#createInAvailabilityZone(String, String) */ @POST @SelectJson("aggregate") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @WrapWith("aggregate") - ListenableFuture createAggregate(@PayloadParam("name") String name, + ListenableFuture createInAvailabilityZone(@PayloadParam("name") String name, @PayloadParam("availability_zone") String availabilityZone); /** @@ -110,13 +109,13 @@ public interface HostAggregateAsyncApi { ListenableFuture updateAvailabilityZone(@PathParam("id") String id, @PayloadParam("availability_zone") String availabilityZone); /** - * @see HostAggregateApi#deleteAggregate(String) + * @see HostAggregateApi#delete(String) */ @DELETE @Path("/{id}") @Consumes(MediaType.APPLICATION_JSON) @ExceptionParser(ReturnFalseOnNotFoundOr404.class) - ListenableFuture deleteAggregate(@PathParam("id") String id); + ListenableFuture delete(@PathParam("id") String id); /** * @see HostAggregateApi#addHost(String,String) diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/KeyPairApi.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/KeyPairApi.java index 1d5ae3c049..a2769399c4 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/KeyPairApi.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/KeyPairApi.java @@ -18,8 +18,6 @@ */ package org.jclouds.openstack.nova.v2_0.extensions; -import java.util.Map; -import java.util.Set; import java.util.concurrent.TimeUnit; import org.jclouds.concurrent.Timeout; @@ -27,6 +25,9 @@ import org.jclouds.openstack.nova.v2_0.domain.KeyPair; import org.jclouds.openstack.v2_0.ServiceType; import org.jclouds.openstack.v2_0.services.Extension; +import com.google.common.annotations.Beta; +import com.google.common.collect.FluentIterable; + /** * Provides synchronous access to Security Groups. *

@@ -34,6 +35,7 @@ import org.jclouds.openstack.v2_0.services.Extension; * @see KeyPairAsyncApi * @author Jeremy Daggett */ +@Beta @Extension(of = ServiceType.COMPUTE, namespace = ExtensionNamespaces.KEYPAIRS) @Timeout(duration = 180, timeUnit = TimeUnit.SECONDS) public interface KeyPairApi { @@ -43,27 +45,27 @@ public interface KeyPairApi { * * @return all Key Pairs */ - Set> listKeyPairs(); + FluentIterable list(); /** * Create a Key Pair. * * @return a Key Pair */ - KeyPair createKeyPair(String name); + KeyPair create(String name); /** * Create a Key Pair with a public key. * * @return a Key Pair with a public key. */ - KeyPair createKeyPairWithPublicKey(String name, String publicKey); + KeyPair createWithPublicKey(String name, String publicKey); /** * Delete a Key Pairs. * * @return */ - Boolean deleteKeyPair(String name); + boolean delete(String name); } diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/KeyPairAsyncApi.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/KeyPairAsyncApi.java index 3fb1056d38..c5b0f69fda 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/KeyPairAsyncApi.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/KeyPairAsyncApi.java @@ -18,9 +18,6 @@ */ package org.jclouds.openstack.nova.v2_0.extensions; -import java.util.Map; -import java.util.Set; - import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; @@ -32,6 +29,7 @@ import javax.ws.rs.core.MediaType; import org.jclouds.openstack.keystone.v2_0.filters.AuthenticateRequest; import org.jclouds.openstack.nova.v2_0.domain.KeyPair; +import org.jclouds.openstack.nova.v2_0.functions.internal.ParseKeyPairs; import org.jclouds.openstack.v2_0.ServiceType; import org.jclouds.openstack.v2_0.features.ExtensionAsyncApi; import org.jclouds.openstack.v2_0.services.Extension; @@ -39,11 +37,14 @@ import org.jclouds.rest.annotations.ExceptionParser; import org.jclouds.rest.annotations.Payload; import org.jclouds.rest.annotations.PayloadParam; import org.jclouds.rest.annotations.RequestFilters; +import org.jclouds.rest.annotations.ResponseParser; import org.jclouds.rest.annotations.SelectJson; import org.jclouds.rest.annotations.SkipEncoding; -import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404; +import org.jclouds.rest.functions.ReturnEmptyFluentIterableOnNotFoundOr404; import org.jclouds.rest.functions.ReturnFalseOnNotFoundOr404; +import com.google.common.annotations.Beta; +import com.google.common.collect.FluentIterable; import com.google.common.util.concurrent.ListenableFuture; /** @@ -59,6 +60,7 @@ import com.google.common.util.concurrent.ListenableFuture; * @see * @see */ +@Beta @Extension(of = ServiceType.COMPUTE, namespace = ExtensionNamespaces.KEYPAIRS) @SkipEncoding({ '/', '=' }) @RequestFilters(AuthenticateRequest.class) @@ -66,10 +68,10 @@ public interface KeyPairAsyncApi { @GET @Path("/os-keypairs") - @SelectJson("keypairs") + @ResponseParser(ParseKeyPairs.class) @Consumes(MediaType.APPLICATION_JSON) - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture>> listKeyPairs(); + @ExceptionParser(ReturnEmptyFluentIterableOnNotFoundOr404.class) + ListenableFuture> list(); @POST @Path("/os-keypairs") @@ -77,7 +79,7 @@ public interface KeyPairAsyncApi { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Payload("%7B\"keypair\":%7B\"name\":\"{name}\"%7D%7D") - ListenableFuture createKeyPair(@PayloadParam("name") String name); + ListenableFuture create(@PayloadParam("name") String name); @POST @Path("/os-keypairs") @@ -85,13 +87,13 @@ public interface KeyPairAsyncApi { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Payload("%7B\"keypair\":%7B\"name\":\"{name}\",\"public_key\":\"{publicKey}\"%7D%7D") - ListenableFuture createKeyPairWithPublicKey(@PayloadParam("name") String name, + ListenableFuture createWithPublicKey(@PayloadParam("name") String name, @PayloadParam("publicKey") String publicKey); @DELETE @Path("/os-keypairs/{name}") @ExceptionParser(ReturnFalseOnNotFoundOr404.class) @Consumes - ListenableFuture deleteKeyPair(@PathParam("name") String name); + ListenableFuture delete(@PathParam("name") String name); } diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/QuotaApi.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/QuotaApi.java index 9a38d1f914..af313b9e90 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/QuotaApi.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/QuotaApi.java @@ -21,11 +21,11 @@ package org.jclouds.openstack.nova.v2_0.extensions; import java.util.concurrent.TimeUnit; import org.jclouds.concurrent.Timeout; -import org.jclouds.openstack.keystone.v2_0.filters.AuthenticateRequest; -import org.jclouds.openstack.nova.v2_0.domain.Quotas; +import org.jclouds.openstack.nova.v2_0.domain.Quota; import org.jclouds.openstack.v2_0.ServiceType; import org.jclouds.openstack.v2_0.services.Extension; -import org.jclouds.rest.annotations.RequestFilters; + +import com.google.common.annotations.Beta; /** * The quotas extension enables limiters placed on the resources used per tenant (project) for virtual instances. It is @@ -38,26 +38,26 @@ import org.jclouds.rest.annotations.RequestFilters; * @see QuotaAsyncApi * @see */ +@Beta @Extension(of = ServiceType.COMPUTE, namespace = ExtensionNamespaces.QUOTAS) @Timeout(duration = 180, timeUnit = TimeUnit.SECONDS) -@RequestFilters(AuthenticateRequest.class) public interface QuotaApi { /** * @return the quota settings for the tenant */ - Quotas getQuotasForTenant(String tenantId); + Quota getByTenant(String tenantId); /** * Update the quotas for a given tenant * * @return true if successful */ - Boolean updateQuotasForTenant(String tenantId, Quotas quotas); + boolean updateQuotaOfTenant(Quota quota, String tenantId); /** * @return the set of default quotas for the tenant */ - Quotas getDefaultQuotasForTenant(String tenantId); + Quota getDefaultsForTenant(String tenantId); } diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/QuotaAsyncApi.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/QuotaAsyncApi.java index b0f6dc7da7..16269867aa 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/QuotaAsyncApi.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/QuotaAsyncApi.java @@ -18,8 +18,6 @@ */ package org.jclouds.openstack.nova.v2_0.extensions; -import java.util.concurrent.TimeUnit; - import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.PUT; @@ -28,9 +26,8 @@ import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; -import org.jclouds.concurrent.Timeout; import org.jclouds.openstack.keystone.v2_0.filters.AuthenticateRequest; -import org.jclouds.openstack.nova.v2_0.domain.Quotas; +import org.jclouds.openstack.nova.v2_0.domain.Quota; import org.jclouds.openstack.v2_0.ServiceType; import org.jclouds.openstack.v2_0.services.Extension; import org.jclouds.rest.annotations.ExceptionParser; @@ -41,48 +38,50 @@ import org.jclouds.rest.annotations.SelectJson; import org.jclouds.rest.binders.BindToJsonPayload; import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; +import com.google.common.annotations.Beta; import com.google.common.util.concurrent.ListenableFuture; /** * Provide access to Quota information for Nova tenants. - * + * * @author Adam Lowe * @see QuotaApi * @see */ +@Beta @Extension(of = ServiceType.COMPUTE, namespace = ExtensionNamespaces.QUOTAS) -@Timeout(duration = 180, timeUnit = TimeUnit.SECONDS) @RequestFilters(AuthenticateRequest.class) @Path("/os-quota-sets") public interface QuotaAsyncApi { /** - * @see QuotaApi#getDefaultQuotasForTenant(String) + * @see QuotaApi#getDefaultsForTenant(String) */ @GET @SelectJson("quota_set") @Consumes(MediaType.APPLICATION_JSON) @Path("/{tenant_id}") @ExceptionParser(ReturnNullOnNotFoundOr404.class) - ListenableFuture getQuotasForTenant(@PathParam("tenant_id") String tenantId); + ListenableFuture getByTenant(@PathParam("tenant_id") String tenantId); /** - * @see QuotaApi#updateQuotasForTenant(String, org.jclouds.openstack.nova.v2_0.domain.Quotas) + * @see QuotaApi#updateQuotaOfTenant */ @PUT @Path("/{tenant_id}") @Produces(MediaType.APPLICATION_JSON) @MapBinder(BindToJsonPayload.class) - ListenableFuture updateQuotasForTenant(@PathParam("tenant_id") String tenantId, @PayloadParam("quota_set") Quotas quotas); + ListenableFuture updateQuotaOfTenant(@PayloadParam("quota_set") Quota quota, + @PathParam("tenant_id") String tenantId); /** - * @see QuotaApi#getDefaultQuotasForTenant(String) + * @see QuotaApi#getDefaultsForTenant(String) */ @GET @SelectJson("quota_set") @Consumes(MediaType.APPLICATION_JSON) @Path("/{tenant_id}/defaults") @ExceptionParser(ReturnNullOnNotFoundOr404.class) - ListenableFuture getDefaultQuotasForTenant(@PathParam("tenant_id") String tenantId); + ListenableFuture getDefaultsForTenant(@PathParam("tenant_id") String tenantId); } diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/QuotaClassApi.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/QuotaClassApi.java index 86922ce492..aed2b37986 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/QuotaClassApi.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/QuotaClassApi.java @@ -21,11 +21,11 @@ package org.jclouds.openstack.nova.v2_0.extensions; import java.util.concurrent.TimeUnit; import org.jclouds.concurrent.Timeout; -import org.jclouds.openstack.keystone.v2_0.filters.AuthenticateRequest; import org.jclouds.openstack.nova.v2_0.domain.QuotaClass; import org.jclouds.openstack.v2_0.ServiceType; import org.jclouds.openstack.v2_0.services.Extension; -import org.jclouds.rest.annotations.RequestFilters; + +import com.google.common.annotations.Beta; /** * Provides synchronous access to Quota Classes via the REST API. @@ -37,21 +37,21 @@ import org.jclouds.rest.annotations.RequestFilters; * @see * @see */ +@Beta @Extension(of = ServiceType.COMPUTE, namespace = ExtensionNamespaces.QUOTA_CLASSES) @Timeout(duration = 180, timeUnit = TimeUnit.SECONDS) -@RequestFilters(AuthenticateRequest.class) public interface QuotaClassApi { /** * @return the quota settings for the tenant */ - QuotaClass getQuotaClass(String id); + QuotaClass get(String id); /** * Update the quotas for a given tenant * * @return true if successful */ - Boolean updateQuotaClass(String id, QuotaClass quotas); + boolean update(String id, QuotaClass quotas); } diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/QuotaClassAsyncApi.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/QuotaClassAsyncApi.java index 41cfe91881..b614bea5cc 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/QuotaClassAsyncApi.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/QuotaClassAsyncApi.java @@ -18,8 +18,6 @@ */ package org.jclouds.openstack.nova.v2_0.extensions; -import java.util.concurrent.TimeUnit; - import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.PUT; @@ -28,7 +26,6 @@ import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; -import org.jclouds.concurrent.Timeout; import org.jclouds.openstack.keystone.v2_0.filters.AuthenticateRequest; import org.jclouds.openstack.nova.v2_0.domain.QuotaClass; import org.jclouds.openstack.v2_0.ServiceType; @@ -41,6 +38,7 @@ import org.jclouds.rest.annotations.SelectJson; import org.jclouds.rest.binders.BindToJsonPayload; import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; +import com.google.common.annotations.Beta; import com.google.common.util.concurrent.ListenableFuture; /** @@ -51,29 +49,29 @@ import com.google.common.util.concurrent.ListenableFuture; * @see * @see */ +@Beta @Extension(of = ServiceType.COMPUTE, namespace = ExtensionNamespaces.QUOTA_CLASSES) -@Timeout(duration = 180, timeUnit = TimeUnit.SECONDS) @RequestFilters(AuthenticateRequest.class) @Path("/os-quota-class-sets") public interface QuotaClassAsyncApi { /** - * @see QuotaClassApi#getQuotaClass + * @see QuotaClassApi#get */ @GET @SelectJson("quota_class_set") @Consumes(MediaType.APPLICATION_JSON) @Path("/{id}") @ExceptionParser(ReturnNullOnNotFoundOr404.class) - ListenableFuture getQuotaClass(@PathParam("id") String id); + ListenableFuture get(@PathParam("id") String id); /** - * @see QuotaClassApi#updateQuotaClass + * @see QuotaClassApi#update */ @PUT @Path("/{id}") @Produces(MediaType.APPLICATION_JSON) @MapBinder(BindToJsonPayload.class) - ListenableFuture updateQuotaClass(@PathParam("id") String id, @PayloadParam("quota_class_set") QuotaClass quotas); + ListenableFuture update(@PathParam("id") String id, @PayloadParam("quota_class_set") QuotaClass quotas); } diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/SecurityGroupApi.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/SecurityGroupApi.java index 8042ad2868..f3811319f0 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/SecurityGroupApi.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/SecurityGroupApi.java @@ -18,7 +18,6 @@ */ package org.jclouds.openstack.nova.v2_0.extensions; -import java.util.Set; import java.util.concurrent.TimeUnit; import org.jclouds.concurrent.Timeout; @@ -28,6 +27,9 @@ import org.jclouds.openstack.nova.v2_0.domain.SecurityGroupRule; import org.jclouds.openstack.v2_0.ServiceType; import org.jclouds.openstack.v2_0.services.Extension; +import com.google.common.annotations.Beta; +import com.google.common.collect.FluentIterable; + /** * Provides synchronous access to Security Groups. *

@@ -35,6 +37,7 @@ import org.jclouds.openstack.v2_0.services.Extension; * @see SecurityGroupAsyncApi * @author Jeremy Daggett */ +@Beta @Extension(of = ServiceType.COMPUTE, namespace = ExtensionNamespaces.SECURITY_GROUPS) @Timeout(duration = 180, timeUnit = TimeUnit.SECONDS) public interface SecurityGroupApi { @@ -42,44 +45,44 @@ public interface SecurityGroupApi { /** * List all Security Groups. * - * @return all Floating IPs + * @return all Security Groups */ - Set listSecurityGroups(); + FluentIterable list(); /** * Get a specific Security Group * * @return a specific Security Group */ - SecurityGroup getSecurityGroup(String id); + SecurityGroup get(String id); /** * Create a Security Group * * @return a new Security Group */ - SecurityGroup createSecurityGroupWithNameAndDescription(String name, String description); + SecurityGroup createWithDescription(String name, String description); /** * Delete a Security Group. * * @return */ - Boolean deleteSecurityGroup(String id); + boolean delete(String id); /** * Create a Security Group Rule. * * @return a new Security Group Rule */ - SecurityGroupRule createSecurityGroupRuleAllowingCidrBlock(String parentGroup, Ingress ingress, String sourceCidr); + SecurityGroupRule createRuleAllowingCidrBlock(String parentGroup, Ingress ingress, String sourceCidr); /** * Create a Security Group Rule. * * @return a new Security Group Rule */ - SecurityGroupRule createSecurityGroupRuleAllowingSecurityGroupId(String parentGroup, Ingress ingress, + SecurityGroupRule createRuleAllowingSecurityGroupId(String parentGroup, Ingress ingress, String sourceCidr); /** @@ -87,6 +90,6 @@ public interface SecurityGroupApi { * * @return */ - Boolean deleteSecurityGroupRule(String id); + Boolean deleteRule(String id); } diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/SecurityGroupAsyncApi.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/SecurityGroupAsyncApi.java index 438c85eeb3..0303ff8270 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/SecurityGroupAsyncApi.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/SecurityGroupAsyncApi.java @@ -18,8 +18,6 @@ */ package org.jclouds.openstack.nova.v2_0.extensions; -import java.util.Set; - import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; @@ -43,10 +41,12 @@ import org.jclouds.rest.annotations.PayloadParam; import org.jclouds.rest.annotations.RequestFilters; import org.jclouds.rest.annotations.SelectJson; import org.jclouds.rest.annotations.SkipEncoding; -import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404; +import org.jclouds.rest.functions.ReturnEmptyFluentIterableOnNotFoundOr404; import org.jclouds.rest.functions.ReturnFalseOnNotFoundOr404; import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; +import com.google.common.annotations.Beta; +import com.google.common.collect.FluentIterable; import com.google.common.util.concurrent.ListenableFuture; /** @@ -60,33 +60,34 @@ import com.google.common.util.concurrent.ListenableFuture; * @see * @see */ +@Beta @Extension(of = ServiceType.COMPUTE, namespace = ExtensionNamespaces.SECURITY_GROUPS) @SkipEncoding( { '/', '=' }) @RequestFilters(AuthenticateRequest.class) public interface SecurityGroupAsyncApi { /** - * @see SecurityGroupApi#listSecurityGroups + * @see SecurityGroupApi#list */ @GET @SelectJson("security_groups") @Consumes(MediaType.APPLICATION_JSON) @Path("/os-security-groups") - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> listSecurityGroups(); + @ExceptionParser(ReturnEmptyFluentIterableOnNotFoundOr404.class) + ListenableFuture> list(); /** - * @see SecurityGroupApi#getSecurityGroup + * @see SecurityGroupApi#get */ @GET @Path("/os-security-groups/{id}") @SelectJson("security_group") @Consumes(MediaType.APPLICATION_JSON) @ExceptionParser(ReturnNullOnNotFoundOr404.class) - ListenableFuture getSecurityGroup(@PathParam("id") String id); + ListenableFuture get(@PathParam("id") String id); /** - * @see SecurityGroupApi#createSecurityGroupWithNameAndDescription + * @see SecurityGroupApi#createWithDescription */ @POST @Path("/os-security-groups") @@ -95,20 +96,20 @@ public interface SecurityGroupAsyncApi { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Payload("%7B\"security_group\":%7B\"name\":\"{name}\",\"description\":\"{description}\"%7D%7D") - ListenableFuture createSecurityGroupWithNameAndDescription(@PayloadParam("name") String name, + ListenableFuture createWithDescription(@PayloadParam("name") String name, @PayloadParam("description") String description); /** - * @see SecurityGroupApi#deleteSecurityGroup + * @see SecurityGroupApi#delete */ @DELETE @Path("/os-security-groups/{id}") @ExceptionParser(ReturnNullOnNotFoundOr404.class) @Consumes(MediaType.APPLICATION_JSON) - ListenableFuture deleteSecurityGroup(@PathParam("id") String id); + ListenableFuture delete(@PathParam("id") String id); /** - * @see SecurityGroupApi#createSecurityGroupRuleAllowingCidrBlock + * @see SecurityGroupApi#createRuleAllowingCidrBlock */ @POST @Path("/os-security-group-rules") @@ -117,7 +118,7 @@ public interface SecurityGroupAsyncApi { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @MapBinder(BindSecurityGroupRuleToJsonPayload.class) - ListenableFuture createSecurityGroupRuleAllowingCidrBlock( + ListenableFuture createRuleAllowingCidrBlock( @PayloadParam("parent_group_id") String parent_group_id, Ingress ip_protocol, @PayloadParam("cidr") String cidr); @@ -131,17 +132,17 @@ public interface SecurityGroupAsyncApi { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @MapBinder(BindSecurityGroupRuleToJsonPayload.class) - ListenableFuture createSecurityGroupRuleAllowingSecurityGroupId( + ListenableFuture createRuleAllowingSecurityGroupId( @PayloadParam("parent_group_id") String parent_group_id, Ingress ip_protocol, @PayloadParam("group_id") String group_id); /** - * @see SecurityGroupApi#deleteSecurityGroupRule + * @see SecurityGroupApi#deleteRule */ @DELETE @Path("/os-security-group-rules/{security_group_rule_ID}") @ExceptionParser(ReturnFalseOnNotFoundOr404.class) @Consumes - ListenableFuture deleteSecurityGroupRule(@PathParam("security_group_rule_ID") String security_group_rule_ID); + ListenableFuture deleteRule(@PathParam("security_group_rule_ID") String security_group_rule_ID); } diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/AdminActionsApi.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/ServerAdminApi.java similarity index 79% rename from apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/AdminActionsApi.java rename to apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/ServerAdminApi.java index aa2e92a7b7..351bb783f8 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/AdminActionsApi.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/ServerAdminApi.java @@ -26,59 +26,62 @@ import org.jclouds.openstack.nova.v2_0.options.CreateBackupOfServerOptions; import org.jclouds.openstack.v2_0.ServiceType; import org.jclouds.openstack.v2_0.services.Extension; +import com.google.common.annotations.Beta; + /** * Provide additional actions for servers: * 'suspend', 'resume', 'migrate', 'lock', 'unlock', 'resetNetwork', 'createBackup', 'pause', 'migrateLive', * 'injectNetworkInfo', 'unpause' * * @author Adam Lowe - * @see org.jclouds.openstack.nova.v2_0.extensions.AdminActionsAsyncApi + * @see org.jclouds.openstack.nova.v2_0.extensions.ServerAdminAsyncApi */ +@Beta @Extension(of = ServiceType.COMPUTE, namespace = ExtensionNamespaces.ADMIN_ACTIONS) @Timeout(duration = 180, timeUnit = TimeUnit.SECONDS) -public interface AdminActionsApi { +public interface ServerAdminApi { /** * Suspend a server. * * @param id id of the server */ - Boolean suspendServer(String id); + Boolean suspend(String id); /** * Resume a server. * * @param id id of the server */ - Boolean resumeServer(String id); + Boolean resume(String id); /** * Migrate a server. * * @param id id of the server */ - Boolean migrateServer(String id); + Boolean migrate(String id); /** * Lock a server. * * @param id id of the server */ - Boolean lockServer(String id); + Boolean lock(String id); /** * Unlock a server. * * @param id id of the server */ - Boolean unlockServer(String id); + Boolean unlock(String id); /** * Reset network of a server. * * @param id id of the server */ - Boolean resetNetworkOfServer(String id); + Boolean resetNetwork(String id); /** * Create backup of a server. @@ -90,21 +93,21 @@ public interface AdminActionsApi { * @param options optional rotation and/or metadata parameters * @return the id of the newly created image */ - String createBackupOfServer(String id, String imageName, BackupType backupType, int rotation, CreateBackupOfServerOptions... options); + String createBackup(String id, String imageName, BackupType backupType, int rotation, CreateBackupOfServerOptions... options); /** * Pause a server. * * @param id id of the server */ - Boolean pauseServer(String id); + Boolean pause(String id); /** * Unpause a server. * * @param id id of the server */ - Boolean unpauseServer(String id); + Boolean unpause(String id); /** @@ -112,12 +115,12 @@ public interface AdminActionsApi { * * @param id id of the server */ - Boolean liveMigrateServer(String id, String host, boolean blockMigration, boolean diskOverCommit); + Boolean liveMigrate(String id, String host, boolean blockMigration, boolean diskOverCommit); /** * Inject network info into a server. * * @param id id of the server */ - Boolean injectNetworkInfoIntoServer(String id); + Boolean injectNetworkInfo(String id); } diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/AdminActionsAsyncApi.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/ServerAdminAsyncApi.java similarity index 76% rename from apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/AdminActionsAsyncApi.java rename to apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/ServerAdminAsyncApi.java index a219e214d0..f6ce679b30 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/AdminActionsAsyncApi.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/ServerAdminAsyncApi.java @@ -41,76 +41,78 @@ import org.jclouds.rest.annotations.WrapWith; import org.jclouds.rest.functions.MapHttp4xxCodesToExceptions; import org.jclouds.rest.functions.ReturnFalseOnNotFoundOr404; +import com.google.common.annotations.Beta; import com.google.common.util.concurrent.ListenableFuture; /** * Provide access to Admin Server Actions via REST API * * @author Adam Lowe - * @see org.jclouds.openstack.nova.v2_0.extensions.AdminActionsApi + * @see org.jclouds.openstack.nova.v2_0.extensions.ServerAdminApi */ +@Beta @Extension(of = ServiceType.COMPUTE, namespace = ExtensionNamespaces.ADMIN_ACTIONS) @SkipEncoding( { '/', '=' }) @RequestFilters(AuthenticateRequest.class) @Path("/servers/{id}/action") -public interface AdminActionsAsyncApi { +public interface ServerAdminAsyncApi { /** - * @see AdminActionsApi#suspendServer(String) + * @see ServerAdminApi#suspend(String) */ @POST @Produces(MediaType.APPLICATION_JSON) @Payload("{\"suspend\":null}") @ExceptionParser(ReturnFalseOnNotFoundOr404.class) - ListenableFuture suspendServer(@PathParam("id") String id); + ListenableFuture suspend(@PathParam("id") String id); /** - * @see AdminActionsApi#resumeServer(String) + * @see ServerAdminApi#resume(String) */ @POST @Produces(MediaType.APPLICATION_JSON) @Payload("{\"resume\":null}") @ExceptionParser(ReturnFalseOnNotFoundOr404.class) - ListenableFuture resumeServer(@PathParam("id") String id); + ListenableFuture resume(@PathParam("id") String id); /** - * @see AdminActionsApi#migrateServer(String) + * @see ServerAdminApi#migrate(String) */ @POST @Produces(MediaType.APPLICATION_JSON) @Payload("{\"migrate\":null}") @ExceptionParser(ReturnFalseOnNotFoundOr404.class) - ListenableFuture migrateServer(@PathParam("id") String id); + ListenableFuture migrate(@PathParam("id") String id); /** - * @see AdminActionsApi#suspendServer(String) + * @see ServerAdminApi#lock(String) */ @POST @Produces(MediaType.APPLICATION_JSON) @Payload("{\"lock\":null}") @ExceptionParser(ReturnFalseOnNotFoundOr404.class) - ListenableFuture lockServer(@PathParam("id") String id); + ListenableFuture lock(@PathParam("id") String id); /** - * @see AdminActionsApi#unlockServer(String) + * @see ServerAdminApi#unlock(String) */ @POST @Produces(MediaType.APPLICATION_JSON) @Payload("{\"unlock\":null}") @ExceptionParser(ReturnFalseOnNotFoundOr404.class) - ListenableFuture unlockServer(@PathParam("id") String id); + ListenableFuture unlock(@PathParam("id") String id); /** - * @see AdminActionsApi#resetNetworkOfServer(String) + * @see ServerAdminApi#resetNetwork(String) */ @POST @Produces(MediaType.APPLICATION_JSON) @Payload("{\"resetNetwork\":null}") @ExceptionParser(ReturnFalseOnNotFoundOr404.class) - ListenableFuture resetNetworkOfServer(@PathParam("id") String id); + ListenableFuture resetNetwork(@PathParam("id") String id); /** - * @see AdminActionsApi#createBackupOfServer + * @see ServerAdminApi#createBackup */ @POST @Consumes(MediaType.APPLICATION_JSON) @@ -118,47 +120,47 @@ public interface AdminActionsAsyncApi { @WrapWith("createBackup") @ExceptionParser(MapHttp4xxCodesToExceptions.class) @ResponseParser(ParseImageIdFromLocationHeader.class) - ListenableFuture createBackupOfServer(@PathParam("id") String id, + ListenableFuture createBackup(@PathParam("id") String id, @PayloadParam("name") String imageName, @PayloadParam("backup_type") BackupType backupType, @PayloadParam("rotation") int rotation, CreateBackupOfServerOptions... options); /** - * @see AdminActionsApi#pauseServer(String) + * @see ServerAdminApi#pause(String) */ @POST @Produces(MediaType.APPLICATION_JSON) @Payload("{\"pause\":null}") @ExceptionParser(ReturnFalseOnNotFoundOr404.class) - ListenableFuture pauseServer(@PathParam("id") String id); + ListenableFuture pause(@PathParam("id") String id); /** - * @see AdminActionsApi#unpauseServer(String) + * @see ServerAdminApi#unpause(String) */ @POST @Produces(MediaType.APPLICATION_JSON) @Payload("{\"unpause\":null}") @ExceptionParser(ReturnFalseOnNotFoundOr404.class) - ListenableFuture unpauseServer(@PathParam("id") String id); + ListenableFuture unpause(@PathParam("id") String id); /** - * @see AdminActionsApi#suspendServer(String) + * @see ServerAdminApi#injectNetworkInfo(String) */ @POST @Produces(MediaType.APPLICATION_JSON) @Payload("{\"injectNetworkInfo\":null}") @ExceptionParser(ReturnFalseOnNotFoundOr404.class) - ListenableFuture injectNetworkInfoIntoServer(@PathParam("id") String id); + ListenableFuture injectNetworkInfo(@PathParam("id") String id); /** - * @see AdminActionsApi#migrateServer(String) + * @see ServerAdminApi#liveMigrate(String) */ @POST @Produces(MediaType.APPLICATION_JSON) @ExceptionParser(ReturnFalseOnNotFoundOr404.class) @WrapWith("os-migrateLive") - ListenableFuture liveMigrateServer(@PathParam("id") String id, + ListenableFuture liveMigrate(@PathParam("id") String id, @PayloadParam("host") String host, @PayloadParam("block_migration") boolean blockMigration, @PayloadParam("disk_over_commit") boolean diskOverCommit); diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/ServerWithSecurityGroupsApi.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/ServerWithSecurityGroupsApi.java index 6910cb263b..c14138c658 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/ServerWithSecurityGroupsApi.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/ServerWithSecurityGroupsApi.java @@ -25,6 +25,8 @@ import org.jclouds.openstack.nova.v2_0.domain.ServerWithSecurityGroups; import org.jclouds.openstack.v2_0.ServiceType; import org.jclouds.openstack.v2_0.services.Extension; +import com.google.common.annotations.Beta; + /** * Provides synchronous access to Server details including security group, referred to as the CREATESERVEREXT extension * in the nova documentation @@ -37,6 +39,7 @@ import org.jclouds.openstack.v2_0.services.Extension; * @see ServerWithSecurityGroupsAsyncApi * @see */ +@Beta @Extension(of = ServiceType.COMPUTE, namespace = ExtensionNamespaces.CREATESERVEREXT) @Timeout(duration = 180, timeUnit = TimeUnit.SECONDS) public interface ServerWithSecurityGroupsApi { @@ -47,6 +50,6 @@ public interface ServerWithSecurityGroupsApi { * @param id id of the server * @return server or null if not found */ - ServerWithSecurityGroups getServer(String id); + ServerWithSecurityGroups get(String id); } diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/ServerWithSecurityGroupsAsyncApi.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/ServerWithSecurityGroupsAsyncApi.java index 30b8375f8f..9585b309ed 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/ServerWithSecurityGroupsAsyncApi.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/ServerWithSecurityGroupsAsyncApi.java @@ -34,6 +34,7 @@ import org.jclouds.rest.annotations.SelectJson; import org.jclouds.rest.annotations.SkipEncoding; import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; +import com.google.common.annotations.Beta; import com.google.common.util.concurrent.ListenableFuture; /** @@ -44,19 +45,20 @@ import com.google.common.util.concurrent.ListenableFuture; * @see ServerWithSecurityGroupsApi * @see */ +@Beta @Extension(of = ServiceType.COMPUTE, namespace = ExtensionNamespaces.CREATESERVEREXT) @SkipEncoding({'/', '='}) @RequestFilters(AuthenticateRequest.class) public interface ServerWithSecurityGroupsAsyncApi { /** - * @see ServerWithSecurityGroupsApi#getServer(String) + * @see ServerWithSecurityGroupsApi#get(String) */ @GET @SelectJson("server") @Consumes(MediaType.APPLICATION_JSON) @Path("/os-create-server-ext/{id}") @ExceptionParser(ReturnNullOnNotFoundOr404.class) - ListenableFuture getServer(@PathParam("id") String id); + ListenableFuture get(@PathParam("id") String id); } diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/SimpleTenantUsageApi.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/SimpleTenantUsageApi.java index d17eb19e03..a28c4ec727 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/SimpleTenantUsageApi.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/SimpleTenantUsageApi.java @@ -18,7 +18,6 @@ */ package org.jclouds.openstack.nova.v2_0.extensions; -import java.util.Set; import java.util.concurrent.TimeUnit; import org.jclouds.concurrent.Timeout; @@ -26,6 +25,9 @@ import org.jclouds.openstack.nova.v2_0.domain.SimpleTenantUsage; import org.jclouds.openstack.v2_0.ServiceType; import org.jclouds.openstack.v2_0.services.Extension; +import com.google.common.annotations.Beta; +import com.google.common.collect.FluentIterable; + /** * Provides asynchronous access to Simple Tenant Usage via the REST API. *

@@ -33,6 +35,7 @@ import org.jclouds.openstack.v2_0.services.Extension; * @author Adam Lowe * @see SimpleTenantUsageAsyncApi */ +@Beta @Extension(of = ServiceType.COMPUTE, namespace = ExtensionNamespaces.SIMPLE_TENANT_USAGE) @Timeout(duration = 180, timeUnit = TimeUnit.SECONDS) public interface SimpleTenantUsageApi { @@ -42,12 +45,12 @@ public interface SimpleTenantUsageApi { * * @return the set of TenantUsage reports */ - Set listTenantUsages(); + FluentIterable list(); /** * Retrieve tenant_usage for a specified tenant * * @return the requested tenant usage */ - SimpleTenantUsage getTenantUsage(String tenantId); + SimpleTenantUsage get(String tenantId); } diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/SimpleTenantUsageAsyncApi.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/SimpleTenantUsageAsyncApi.java index 729f50e99e..ea14d37d7b 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/SimpleTenantUsageAsyncApi.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/SimpleTenantUsageAsyncApi.java @@ -18,8 +18,6 @@ */ package org.jclouds.openstack.nova.v2_0.extensions; -import java.util.Set; - import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.Path; @@ -34,9 +32,11 @@ import org.jclouds.rest.annotations.ExceptionParser; import org.jclouds.rest.annotations.RequestFilters; import org.jclouds.rest.annotations.SelectJson; import org.jclouds.rest.annotations.SkipEncoding; -import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404; +import org.jclouds.rest.functions.ReturnEmptyFluentIterableOnNotFoundOr404; import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; +import com.google.common.annotations.Beta; +import com.google.common.collect.FluentIterable; import com.google.common.util.concurrent.ListenableFuture; /** @@ -49,29 +49,30 @@ import com.google.common.util.concurrent.ListenableFuture; * @see * @see */ +@Beta @Extension(of = ServiceType.COMPUTE, namespace = ExtensionNamespaces.SIMPLE_TENANT_USAGE) @SkipEncoding({'/', '='}) @RequestFilters(AuthenticateRequest.class) public interface SimpleTenantUsageAsyncApi { /** - * @see SimpleTenantUsageApi#listTenantUsages() + * @see SimpleTenantUsageApi#list() */ @GET @Path("/os-simple-tenant-usage") @SelectJson("tenant_usages") @Consumes(MediaType.APPLICATION_JSON) - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> listTenantUsages(); + @ExceptionParser(ReturnEmptyFluentIterableOnNotFoundOr404.class) + ListenableFuture> list(); /** - * @see SimpleTenantUsageApi#getTenantUsage(String) + * @see SimpleTenantUsageApi#get(String) */ @GET @Path("/os-simple-tenant-usage/{id}") @SelectJson("tenant_usage") @Consumes(MediaType.APPLICATION_JSON) @ExceptionParser(ReturnNullOnNotFoundOr404.class) - ListenableFuture getTenantUsage(@PathParam("id") String tenantId); + ListenableFuture get(@PathParam("id") String tenantId); } diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/VirtualInterfaceApi.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/VirtualInterfaceApi.java index 257dea3e3c..b3c1027cc2 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/VirtualInterfaceApi.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/VirtualInterfaceApi.java @@ -18,7 +18,6 @@ */ package org.jclouds.openstack.nova.v2_0.extensions; -import java.util.Set; import java.util.concurrent.TimeUnit; import org.jclouds.concurrent.Timeout; @@ -26,12 +25,16 @@ import org.jclouds.openstack.nova.v2_0.domain.VirtualInterface; import org.jclouds.openstack.v2_0.ServiceType; import org.jclouds.openstack.v2_0.services.Extension; +import com.google.common.annotations.Beta; +import com.google.common.collect.FluentIterable; + /** * Provides synchronous access to Virtual Interface features (VIFs). * * @see VirtualInterfaceAsyncApi * @author Adam Lowe */ +@Beta @Extension(of = ServiceType.COMPUTE, namespace = ExtensionNamespaces.VIRTUAL_INTERFACES) @Timeout(duration = 180, timeUnit = TimeUnit.SECONDS) public interface VirtualInterfaceApi { @@ -41,6 +44,6 @@ public interface VirtualInterfaceApi { * * @return the list of snapshots */ - Set listVirtualInterfacesForServer(String serverId); + FluentIterable listOnServer(String serverId); } diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/VirtualInterfaceAsyncApi.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/VirtualInterfaceAsyncApi.java index f37bf6904e..de94545adf 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/VirtualInterfaceAsyncApi.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/VirtualInterfaceAsyncApi.java @@ -18,8 +18,6 @@ */ package org.jclouds.openstack.nova.v2_0.extensions; -import java.util.Set; - import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.Path; @@ -34,8 +32,10 @@ import org.jclouds.rest.annotations.ExceptionParser; import org.jclouds.rest.annotations.RequestFilters; import org.jclouds.rest.annotations.SelectJson; import org.jclouds.rest.annotations.SkipEncoding; -import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404; +import org.jclouds.rest.functions.ReturnEmptyFluentIterableOnNotFoundOr404; +import com.google.common.annotations.Beta; +import com.google.common.collect.FluentIterable; import com.google.common.util.concurrent.ListenableFuture; /** @@ -44,17 +44,18 @@ import com.google.common.util.concurrent.ListenableFuture; * @see VirtualInterfaceApi * @author Adam Lowe */ +@Beta @Extension(of = ServiceType.COMPUTE, namespace = ExtensionNamespaces.VIRTUAL_INTERFACES) @SkipEncoding({'/', '='}) @RequestFilters(AuthenticateRequest.class) public interface VirtualInterfaceAsyncApi { /** - * @see VirtualInterfaceApi#listVirtualInterfacesForServer(String) + * @see VirtualInterfaceApi#listOnServer(String) */ @GET @SelectJson("virtual_interfaces") @Consumes(MediaType.APPLICATION_JSON) @Path("/servers/{server_id}/os-virtual-interfaces") - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> listVirtualInterfacesForServer(@PathParam("server_id") String serverId); + @ExceptionParser(ReturnEmptyFluentIterableOnNotFoundOr404.class) + ListenableFuture> listOnServer(@PathParam("server_id") String serverId); } diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/VolumeApi.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/VolumeApi.java index 3e3af64ccf..30f509fd90 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/VolumeApi.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/VolumeApi.java @@ -18,7 +18,6 @@ */ package org.jclouds.openstack.nova.v2_0.extensions; -import java.util.Set; import java.util.concurrent.TimeUnit; import org.jclouds.concurrent.Timeout; @@ -30,13 +29,18 @@ import org.jclouds.openstack.nova.v2_0.options.CreateVolumeSnapshotOptions; import org.jclouds.openstack.v2_0.ServiceType; import org.jclouds.openstack.v2_0.services.Extension; +import com.google.common.annotations.Beta; +import com.google.common.collect.FluentIterable; + /** * Provides synchronous access to Volumes. *

* + * @see VolumeAsyncApi * @see org.jclouds.openstack.nova.v2_0.extensions.VolumeAsyncApi * @author Adam Lowe */ +@Beta @Extension(of = ServiceType.COMPUTE, namespace = ExtensionNamespaces.VOLUMES) @Timeout(duration = 180, timeUnit = TimeUnit.SECONDS) public interface VolumeApi { @@ -45,42 +49,42 @@ public interface VolumeApi { * * @return the list of snapshots */ - Set listVolumes(); + FluentIterable list(); /** * Returns a detailed list of volumes. * * @return the list of volumes. */ - Set listVolumesInDetail(); + FluentIterable listInDetail(); /** * Return data about the given volume. * * @return details of a specific snapshot. */ - Volume getVolume(String volumeId); + Volume get(String volumeId); /** * Creates a new Snapshot * * @return the new Snapshot */ - Volume createVolume(int sizeGB, CreateVolumeOptions... options); + Volume create(int sizeGB, CreateVolumeOptions... options); /** * Delete a snapshot. * * @return true if successful */ - Boolean deleteVolume(String volumeId); + boolean delete(String volumeId); /** * List volume attachments for a given instance. * * @return all Floating IPs */ - Set listAttachmentsOnServer(String serverId); + FluentIterable listAttachmentsOnServer(String serverId); /** * Get a specific attached volume. @@ -108,14 +112,14 @@ public interface VolumeApi { * * @return the list of snapshots */ - Set listSnapshots(); + FluentIterable listSnapshots(); /** * Returns a summary list of snapshots. * * @return the list of snapshots */ - Set listSnapshotsInDetail(); + FluentIterable listSnapshotsInDetail(); /** * Return data about the given snapshot. @@ -136,6 +140,6 @@ public interface VolumeApi { * * @return true if successful */ - Boolean deleteSnapshot(String snapshotId); + boolean deleteSnapshot(String snapshotId); } diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/VolumeAsyncApi.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/VolumeAsyncApi.java index 412183aca3..d85bf687cc 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/VolumeAsyncApi.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/VolumeAsyncApi.java @@ -18,8 +18,6 @@ */ package org.jclouds.openstack.nova.v2_0.extensions; -import java.util.Set; - import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; @@ -44,10 +42,12 @@ import org.jclouds.rest.annotations.RequestFilters; import org.jclouds.rest.annotations.SelectJson; import org.jclouds.rest.annotations.SkipEncoding; import org.jclouds.rest.annotations.WrapWith; -import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404; +import org.jclouds.rest.functions.ReturnEmptyFluentIterableOnNotFoundOr404; import org.jclouds.rest.functions.ReturnFalseOnNotFoundOr404; import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; +import com.google.common.annotations.Beta; +import com.google.common.collect.FluentIterable; import com.google.common.util.concurrent.ListenableFuture; /** @@ -57,6 +57,7 @@ import com.google.common.util.concurrent.ListenableFuture; * @see org.jclouds.openstack.nova.v2_0.extensions.VolumeAsyncApi * @author Adam Lowe */ +@Beta @Extension(of = ServiceType.COMPUTE, namespace = ExtensionNamespaces.VOLUMES) @SkipEncoding({'/', '='}) @RequestFilters(AuthenticateRequest.class) @@ -70,8 +71,8 @@ public interface VolumeAsyncApi { @Path("/os-volumes") @SelectJson("volumes") @Consumes(MediaType.APPLICATION_JSON) - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> listVolumes(); + @ExceptionParser(ReturnEmptyFluentIterableOnNotFoundOr404.class) + ListenableFuture> list(); /** * Returns a detailed list of volumes. @@ -82,8 +83,8 @@ public interface VolumeAsyncApi { @Path("/os-volumes/detail") @SelectJson("volumes") @Consumes(MediaType.APPLICATION_JSON) - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> listVolumesInDetail(); + @ExceptionParser(ReturnEmptyFluentIterableOnNotFoundOr404.class) + ListenableFuture> listInDetail(); /** * Return data about the given volume. @@ -95,7 +96,7 @@ public interface VolumeAsyncApi { @SelectJson("volume") @Consumes(MediaType.APPLICATION_JSON) @ExceptionParser(ReturnNullOnNotFoundOr404.class) - ListenableFuture getVolume(@PathParam("id") String volumeId); + ListenableFuture get(@PathParam("id") String volumeId); /** * Creates a new volume @@ -108,7 +109,7 @@ public interface VolumeAsyncApi { @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @MapBinder(CreateVolumeOptions.class) - ListenableFuture createVolume(@PayloadParam("size") int sizeGB, CreateVolumeOptions... options); + ListenableFuture create(@PayloadParam("size") int sizeGB, CreateVolumeOptions... options); /** * Delete a volume. @@ -119,7 +120,7 @@ public interface VolumeAsyncApi { @Path("/os-volumes/{id}") @Consumes(MediaType.APPLICATION_JSON) @ExceptionParser(ReturnFalseOnNotFoundOr404.class) - ListenableFuture deleteVolume(@PathParam("id") String volumeId); + ListenableFuture delete(@PathParam("id") String volumeId); /** * List volume attachments for a given instance. @@ -130,8 +131,8 @@ public interface VolumeAsyncApi { @Path("/servers/{server_id}/os-volume_attachments") @SelectJson("volumeAttachments") @Consumes(MediaType.APPLICATION_JSON) - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> listAttachmentsOnServer(@PathParam("server_id") String serverId); + @ExceptionParser(ReturnEmptyFluentIterableOnNotFoundOr404.class) + ListenableFuture> listAttachmentsOnServer(@PathParam("server_id") String serverId); /** * Get a specific attached volume. @@ -180,8 +181,8 @@ public interface VolumeAsyncApi { @Path("/os-snapshots") @SelectJson("snapshots") @Consumes(MediaType.APPLICATION_JSON) - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> listSnapshots(); + @ExceptionParser(ReturnEmptyFluentIterableOnNotFoundOr404.class) + ListenableFuture> listSnapshots(); /** * Returns a summary list of snapshots. @@ -192,8 +193,8 @@ public interface VolumeAsyncApi { @Path("/os-snapshots/detail") @SelectJson("snapshots") @Consumes(MediaType.APPLICATION_JSON) - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> listSnapshotsInDetail(); + @ExceptionParser(ReturnEmptyFluentIterableOnNotFoundOr404.class) + ListenableFuture> listSnapshotsInDetail(); /** * Return data about the given snapshot. diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/VolumeTypeApi.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/VolumeTypeApi.java index b1225c3d0a..16d2950785 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/VolumeTypeApi.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/VolumeTypeApi.java @@ -19,16 +19,16 @@ package org.jclouds.openstack.nova.v2_0.extensions; import java.util.Map; -import java.util.Set; import java.util.concurrent.TimeUnit; import org.jclouds.concurrent.Timeout; -import org.jclouds.openstack.keystone.v2_0.filters.AuthenticateRequest; import org.jclouds.openstack.nova.v2_0.domain.VolumeType; import org.jclouds.openstack.nova.v2_0.options.CreateVolumeTypeOptions; import org.jclouds.openstack.v2_0.ServiceType; import org.jclouds.openstack.v2_0.services.Extension; -import org.jclouds.rest.annotations.RequestFilters; + +import com.google.common.annotations.Beta; +import com.google.common.collect.FluentIterable; /** * Provides synchronous access to Volume Type features @@ -39,21 +39,21 @@ import org.jclouds.rest.annotations.RequestFilters; * @see * @see */ +@Beta @Extension(of = ServiceType.COMPUTE, namespace = ExtensionNamespaces.VOLUME_TYPES) @Timeout(duration = 180, timeUnit = TimeUnit.SECONDS) -@RequestFilters(AuthenticateRequest.class) public interface VolumeTypeApi { /** * @return set of all volume types */ - Set listVolumeTypes(); + FluentIterable list(); /** * @param id the id of the volume type to retrieve * @return the requested volume type */ - VolumeType getVolumeType(String id); + VolumeType get(String id); /** * Creates a new volume type @@ -62,23 +62,23 @@ public interface VolumeTypeApi { * @param options optional settings for the new volume type * @return the new volume type */ - VolumeType createVolumeType(String name, CreateVolumeTypeOptions... options); + VolumeType create(String name, CreateVolumeTypeOptions... options); /** * Deletes a volume type */ - Boolean deleteVolumeType(String id); + boolean delete(String id); /** * @param id the id of the volume type * @return the set of extra metadata for the flavor */ - Map getAllExtraSpecs(String id); + Map getExtraSpecs(String id); /** * Creates or updates the extra metadata for a given flavor */ - Boolean setAllExtraSpecs(String id, Map specs); + boolean updateExtraSpecs(String id, Map specs); /** * Retrieve a single extra spec value @@ -95,7 +95,7 @@ public interface VolumeTypeApi { * @param key the extra spec key (when creating ensure this does not include whitespace or other difficult characters) * @param value the new value to store associate with the key */ - Boolean setExtraSpec(String id, String key, String value); + boolean updateExtraSpec(String id, String key, String value); /** * Deletes an existing extra spec @@ -103,5 +103,5 @@ public interface VolumeTypeApi { * @param id the id of the volume type * @param key the key of the extra spec to delete */ - Boolean deleteExtraSpec(String id, String key); + boolean deleteExtraSpec(String id, String key); } diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/VolumeTypeAsyncApi.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/VolumeTypeAsyncApi.java index e50e172a8f..8dc6061ecf 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/VolumeTypeAsyncApi.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/extensions/VolumeTypeAsyncApi.java @@ -19,7 +19,6 @@ package org.jclouds.openstack.nova.v2_0.extensions; import java.util.Map; -import java.util.Set; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; @@ -46,11 +45,13 @@ import org.jclouds.rest.annotations.SkipEncoding; import org.jclouds.rest.annotations.Unwrap; import org.jclouds.rest.annotations.WrapWith; import org.jclouds.rest.binders.BindToJsonPayload; +import org.jclouds.rest.functions.ReturnEmptyFluentIterableOnNotFoundOr404; import org.jclouds.rest.functions.ReturnEmptyMapOnNotFoundOr404; -import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404; import org.jclouds.rest.functions.ReturnFalseOnNotFoundOr404; import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; +import com.google.common.annotations.Beta; +import com.google.common.collect.FluentIterable; import com.google.common.util.concurrent.ListenableFuture; /** @@ -59,6 +60,7 @@ import com.google.common.util.concurrent.ListenableFuture; * @author Adam Lowe * @see VolumeTypeApi */ +@Beta @Extension(of = ServiceType.COMPUTE, namespace = ExtensionNamespaces.VOLUME_TYPES) @SkipEncoding({'/', '='}) @RequestFilters(AuthenticateRequest.class) @@ -67,58 +69,58 @@ import com.google.common.util.concurrent.ListenableFuture; public interface VolumeTypeAsyncApi { /** - * @see VolumeTypeApi#listVolumeTypes + * @see VolumeTypeApi#list */ @GET @SelectJson("volume_types") - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> listVolumeTypes(); + @ExceptionParser(ReturnEmptyFluentIterableOnNotFoundOr404.class) + ListenableFuture> list(); /** - * @see VolumeTypeApi#getVolumeType + * @see VolumeTypeApi#get */ @GET @Path("/{id}") @SelectJson("volume_type") @ExceptionParser(ReturnNullOnNotFoundOr404.class) - ListenableFuture getVolumeType(@PathParam("id") String id); + ListenableFuture get(@PathParam("id") String id); /** - * @see VolumeTypeApi#createVolumeType + * @see VolumeTypeApi#create */ @POST @SelectJson("volume_type") @Produces(MediaType.APPLICATION_JSON) @WrapWith("volume_type") - ListenableFuture createVolumeType(@PayloadParam("name") String name, CreateVolumeTypeOptions... options); + ListenableFuture create(@PayloadParam("name") String name, CreateVolumeTypeOptions... options); /** - * @see VolumeTypeApi#deleteVolumeType + * @see VolumeTypeApi#delete */ @DELETE @Path("/{id}") @ExceptionParser(ReturnFalseOnNotFoundOr404.class) - ListenableFuture deleteVolumeType(@PathParam("id") String id); + ListenableFuture delete(@PathParam("id") String id); /** - * @see VolumeTypeApi#getAllExtraSpecs(String) + * @see VolumeTypeApi#getExtraSpecs(String) */ @GET @SelectJson("extra_specs") @Path("/{id}/extra_specs") @ExceptionParser(ReturnEmptyMapOnNotFoundOr404.class) - ListenableFuture> getAllExtraSpecs(@PathParam("id") String id); + ListenableFuture> getExtraSpecs(@PathParam("id") String id); /** - * @see VolumeTypeApi#setAllExtraSpecs(String, java.util.Map) + * @see VolumeTypeApi#updateExtraSpecs(String, java.util.Map) */ @POST @Path("/{id}/extra_specs") @Produces(MediaType.APPLICATION_JSON) @ExceptionParser(ReturnFalseOnNotFoundOr404.class) @MapBinder(BindToJsonPayload.class) - ListenableFuture setAllExtraSpecs(@PathParam("id") String id, @PayloadParam("extra_specs") Map specs); + ListenableFuture updateExtraSpecs(@PathParam("id") String id, @PayloadParam("extra_specs") Map specs); /** * @see VolumeTypeApi#getExtraSpec(String, String) @@ -130,14 +132,14 @@ public interface VolumeTypeAsyncApi { ListenableFuture getExtraSpec(@PathParam("id") String id, @PathParam("key") String key); /** - * @see VolumeTypeApi#setExtraSpec(String, String, String) + * @see VolumeTypeApi#updateExtraSpec(String, String, String) */ @PUT @Path("/{id}/extra_specs/{key}") @Produces(MediaType.APPLICATION_JSON) @Payload("%7B\"{key}\":\"{value}\"%7D") @ExceptionParser(ReturnFalseOnNotFoundOr404.class) - ListenableFuture setExtraSpec(@PathParam("id") String id, + ListenableFuture updateExtraSpec(@PathParam("id") String id, @PathParam("key") @PayloadParam("key") String key, @PayloadParam("value") String value); diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/features/FlavorApi.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/features/FlavorApi.java index 5eb5cc69ed..bfda028a9d 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/features/FlavorApi.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/features/FlavorApi.java @@ -18,20 +18,22 @@ */ package org.jclouds.openstack.nova.v2_0.features; -import java.util.Set; import java.util.concurrent.TimeUnit; +import org.jclouds.collect.PagedIterable; import org.jclouds.concurrent.Timeout; +import org.jclouds.openstack.keystone.v2_0.domain.PaginatedCollection; import org.jclouds.openstack.nova.v2_0.domain.Flavor; import org.jclouds.openstack.v2_0.domain.Resource; +import org.jclouds.openstack.v2_0.options.PaginationOptions; /** * Provides asynchronous access to Flavors via their REST API. *

* - * @see FlavorApi + * @see FlavorAsyncApi * @see * @author Jeremy Daggett */ @@ -43,14 +45,18 @@ public interface FlavorApi { * * @return all flavors (IDs, names, links) */ - Set listFlavors(); + PagedIterable list(); + + PaginatedCollection list(PaginationOptions options); /** * List all flavors (all details) * * @return all flavors (all details) */ - Set listFlavorsInDetail(); + PagedIterable listInDetail(); + + PaginatedCollection listInDetail(PaginationOptions options); /** * List details of the specified flavor @@ -59,6 +65,6 @@ public interface FlavorApi { * id of the flavor * @return flavor or null if not found */ - Flavor getFlavor(String id); + Flavor get(String id); } diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/features/FlavorAsyncApi.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/features/FlavorAsyncApi.java index 632f888668..411acb5cd8 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/features/FlavorAsyncApi.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/features/FlavorAsyncApi.java @@ -18,22 +18,28 @@ */ package org.jclouds.openstack.nova.v2_0.features; -import java.util.Set; - import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.core.MediaType; +import org.jclouds.collect.PagedIterable; +import org.jclouds.openstack.keystone.v2_0.domain.PaginatedCollection; import org.jclouds.openstack.keystone.v2_0.filters.AuthenticateRequest; +import org.jclouds.openstack.keystone.v2_0.functions.ReturnEmptyPaginatedCollectionOnNotFoundOr404; import org.jclouds.openstack.nova.v2_0.domain.Flavor; +import org.jclouds.openstack.nova.v2_0.functions.internal.ParseFlavorDetails; +import org.jclouds.openstack.nova.v2_0.functions.internal.ParseFlavors; import org.jclouds.openstack.v2_0.domain.Resource; +import org.jclouds.openstack.v2_0.options.PaginationOptions; import org.jclouds.rest.annotations.ExceptionParser; import org.jclouds.rest.annotations.RequestFilters; +import org.jclouds.rest.annotations.ResponseParser; import org.jclouds.rest.annotations.SelectJson; import org.jclouds.rest.annotations.SkipEncoding; -import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404; +import org.jclouds.rest.annotations.Transform; +import org.jclouds.rest.functions.ReturnEmptyPagedIterableOnNotFoundOr404; import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; import com.google.common.util.concurrent.ListenableFuture; @@ -44,43 +50,65 @@ import com.google.common.util.concurrent.ListenableFuture; * * @see FlavorApi * @see - * @author Jeremy Daggett TODO: Need a ListFlavorOptions class - * minDisk=minDiskInGB& minRam=minRamInMB& marker=markerID&limit=int + * "http://docs.openstack.org/api/openstack-compute/2/content/List_Flavors-d1e4188.html" + * >docs + * @author Jeremy Daggett TODO: Need a ListFlavorOptions class minDisk=minDiskInGB& + * minRam=minRamInMB& marker=markerID&limit=int */ @SkipEncoding({ '/', '=' }) @RequestFilters(AuthenticateRequest.class) public interface FlavorAsyncApi { /** - * @see FlavorApi#listFlavors + * @see FlavorApi#list() */ @GET - @SelectJson("flavors") @Consumes(MediaType.APPLICATION_JSON) @Path("/flavors") - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> listFlavors(); + @RequestFilters(AuthenticateRequest.class) + @ResponseParser(ParseFlavors.class) + @Transform(ParseFlavors.ToPagedIterable.class) + @ExceptionParser(ReturnEmptyPagedIterableOnNotFoundOr404.class) + ListenableFuture> list(); + + /** @see FlavorApi#list(PaginationOptions) */ + @GET + @Consumes(MediaType.APPLICATION_JSON) + @Path("/flavors") + @RequestFilters(AuthenticateRequest.class) + @ResponseParser(ParseFlavors.class) + @ExceptionParser(ReturnEmptyPaginatedCollectionOnNotFoundOr404.class) + ListenableFuture> list(PaginationOptions options); /** - * @see FlavorApi#listFlavorsInDetail + * @see FlavorApi#listInDetail() */ @GET - @SelectJson("flavors") @Consumes(MediaType.APPLICATION_JSON) @Path("/flavors/detail") - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> listFlavorsInDetail(); + @RequestFilters(AuthenticateRequest.class) + @ResponseParser(ParseFlavorDetails.class) + @Transform(ParseFlavorDetails.ToPagedIterable.class) + @ExceptionParser(ReturnEmptyPagedIterableOnNotFoundOr404.class) + ListenableFuture> listInDetail(); + + /** @see FlavorApi#listInDetail(PaginationOptions) */ + @GET + @Consumes(MediaType.APPLICATION_JSON) + @Path("/flavors/detail") + @RequestFilters(AuthenticateRequest.class) + @ResponseParser(ParseFlavorDetails.class) + @ExceptionParser(ReturnEmptyPaginatedCollectionOnNotFoundOr404.class) + ListenableFuture> listInDetail(PaginationOptions options); /** - * @see FlavorApi#getFlavor + * @see FlavorApi#get */ @GET @SelectJson("flavor") @Consumes(MediaType.APPLICATION_JSON) @Path("/flavors/{id}") @ExceptionParser(ReturnNullOnNotFoundOr404.class) - ListenableFuture getFlavor(@PathParam("id") String id); + ListenableFuture get(@PathParam("id") String id); } diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/features/ImageApi.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/features/ImageApi.java index 89fe3e38d5..5afb755fee 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/features/ImageApi.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/features/ImageApi.java @@ -18,12 +18,16 @@ */ package org.jclouds.openstack.nova.v2_0.features; -import java.util.Set; +import java.util.Map; import java.util.concurrent.TimeUnit; +import org.jclouds.collect.PagedIterable; import org.jclouds.concurrent.Timeout; +import org.jclouds.javax.annotation.Nullable; +import org.jclouds.openstack.keystone.v2_0.domain.PaginatedCollection; import org.jclouds.openstack.nova.v2_0.domain.Image; import org.jclouds.openstack.v2_0.domain.Resource; +import org.jclouds.openstack.v2_0.options.PaginationOptions; /** * Provides synchronous access to Images. @@ -43,14 +47,18 @@ public interface ImageApi { * * @return all images (IDs, names, links) */ - Set listImages(); + PagedIterable list(); + + PaginatedCollection list(PaginationOptions options); /** * List all images (all details) * * @return all images (all details) */ - Set listImagesInDetail(); + PagedIterable listInDetail(); + + PaginatedCollection listInDetail(PaginationOptions options); /** * List details of the specified image @@ -59,7 +67,7 @@ public interface ImageApi { * id of the server * @return server or null if not found */ - Image getImage(String id); + Image get(String id); /** * Delete the specified image @@ -68,6 +76,73 @@ public interface ImageApi { * id of the image * @return server or null if not found */ - void deleteImage(String id); + void delete(String id); + + /** + * List all metadata for an image. + * + * @param id + * id of the image + * @return the metadata as a Map + */ + Map getMetadata(String id); + + /** + * Sets the metadata for an image. + * + * @param id + * id of the image + * @param metadata + * a Map containing the metadata + * @return the metadata as a Map + */ + Map setMetadata(String id, Map metadata); + + /** + * Update the metadata for a server. + * + * @param id + * id of the image + * @param metadata + * a Map containing the metadata + * @return the metadata as a Map + */ + Map updateMetadata(String id, Map metadata); + + /** + * Update the metadata for an image. + * + * @param id + * id of the image + * @param metadata + * a Map containing the metadata + * @return the value or null if not present + */ + @Nullable + String getMetadata(String id, String key); + + + /** + * Set a metadata item for an image. + * + * @param id + * id of the image + * @param key + * the name of the metadata item + * @param value + * the value of the metadata item + * @return the value you updated + */ + String updateMetadata(String id, String key, String value); + + /** + * Delete a metadata item from an image. + * + * @param id + * id of the image + * @param key + * the name of the metadata item + */ + void deleteMetadata(String id, String key); } diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/features/ImageAsyncApi.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/features/ImageAsyncApi.java index 40fbc949b6..0d69ab3402 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/features/ImageAsyncApi.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/features/ImageAsyncApi.java @@ -18,23 +18,40 @@ */ package org.jclouds.openstack.nova.v2_0.features; -import java.util.Set; +import java.util.Map; 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 javax.ws.rs.core.MediaType; +import org.jclouds.collect.PagedIterable; +import org.jclouds.openstack.keystone.v2_0.domain.PaginatedCollection; import org.jclouds.openstack.keystone.v2_0.filters.AuthenticateRequest; +import org.jclouds.openstack.keystone.v2_0.functions.ReturnEmptyPaginatedCollectionOnNotFoundOr404; +import org.jclouds.openstack.nova.v2_0.binders.BindMetadataToJsonPayload; import org.jclouds.openstack.nova.v2_0.domain.Image; +import org.jclouds.openstack.nova.v2_0.functions.internal.OnlyMetadataValueOrNull; +import org.jclouds.openstack.nova.v2_0.functions.internal.ParseImageDetails; +import org.jclouds.openstack.nova.v2_0.functions.internal.ParseImages; import org.jclouds.openstack.v2_0.domain.Resource; +import org.jclouds.openstack.v2_0.options.PaginationOptions; import org.jclouds.rest.annotations.ExceptionParser; +import org.jclouds.rest.annotations.MapBinder; +import org.jclouds.rest.annotations.PayloadParam; import org.jclouds.rest.annotations.RequestFilters; +import org.jclouds.rest.annotations.ResponseParser; import org.jclouds.rest.annotations.SelectJson; import org.jclouds.rest.annotations.SkipEncoding; -import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404; +import org.jclouds.rest.annotations.Transform; +import org.jclouds.rest.binders.BindToJsonPayload; +import org.jclouds.rest.functions.ReturnEmptyMapOnNotFoundOr404; +import org.jclouds.rest.functions.ReturnEmptyPagedIterableOnNotFoundOr404; import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; import org.jclouds.rest.functions.ReturnVoidOnNotFoundOr404; @@ -52,42 +69,129 @@ import com.google.common.util.concurrent.ListenableFuture; public interface ImageAsyncApi { /** - * @see ImageApi#listImages + * @see ImageApi#list() */ @GET - @SelectJson("images") @Consumes(MediaType.APPLICATION_JSON) @Path("/images") - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> listImages(); + @RequestFilters(AuthenticateRequest.class) + @ResponseParser(ParseImages.class) + @Transform(ParseImages.ToPagedIterable.class) + @ExceptionParser(ReturnEmptyPagedIterableOnNotFoundOr404.class) + ListenableFuture> list(); + + /** @see ImageApi#list(PaginationOptions) */ + @GET + @Consumes(MediaType.APPLICATION_JSON) + @Path("/images") + @RequestFilters(AuthenticateRequest.class) + @ResponseParser(ParseImages.class) + @ExceptionParser(ReturnEmptyPaginatedCollectionOnNotFoundOr404.class) + ListenableFuture> list(PaginationOptions options); /** - * @see ImageApi#listImagesInDetail + * @see ImageApi#listInDetail() */ @GET - @SelectJson("images") @Consumes(MediaType.APPLICATION_JSON) @Path("/images/detail") - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> listImagesInDetail(); + @RequestFilters(AuthenticateRequest.class) + @ResponseParser(ParseImageDetails.class) + @Transform(ParseImageDetails.ToPagedIterable.class) + @ExceptionParser(ReturnEmptyPagedIterableOnNotFoundOr404.class) + ListenableFuture> listInDetail(); + + /** @see ImageApi#listInDetail(PaginationOptions) */ + @GET + @Consumes(MediaType.APPLICATION_JSON) + @Path("/images/detail") + @RequestFilters(AuthenticateRequest.class) + @ResponseParser(ParseImageDetails.class) + @ExceptionParser(ReturnEmptyPaginatedCollectionOnNotFoundOr404.class) + ListenableFuture> listInDetail(PaginationOptions options); /** - * @see ImageApi#getImage + * @see ImageApi#get */ @GET @SelectJson("image") @Consumes(MediaType.APPLICATION_JSON) @Path("/images/{id}") @ExceptionParser(ReturnNullOnNotFoundOr404.class) - ListenableFuture getImage(@PathParam("id") String id); + ListenableFuture get(@PathParam("id") String id); /** - * @see ImageApi#deleteImage + * @see ImageApi#delete */ @DELETE @Consumes(MediaType.APPLICATION_JSON) @Path("/images/{id}") @ExceptionParser(ReturnVoidOnNotFoundOr404.class) - ListenableFuture deleteImage(@PathParam("id") String id); + ListenableFuture delete(@PathParam("id") String id); + + /** + * @see ImageApi#getMetadata + */ + @GET + @SelectJson("metadata") + @Path("/images/{id}/metadata") + @Consumes(MediaType.APPLICATION_JSON) + @ExceptionParser(ReturnEmptyMapOnNotFoundOr404.class) + ListenableFuture> getMetadata(@PathParam("id") String id); + /** + * @see ImageApi#setMetadata + */ + @PUT + @SelectJson("metadata") + @Path("/images/{id}/metadata") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ExceptionParser(ReturnEmptyMapOnNotFoundOr404.class) + @MapBinder(BindToJsonPayload.class) + ListenableFuture> setMetadata(@PathParam("id") String id, @PayloadParam("metadata") Map metadata); + + /** + * @see ImageApi#updateMetadata + */ + @POST + @SelectJson("metadata") + @Path("/images/{id}/metadata") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ExceptionParser(ReturnEmptyMapOnNotFoundOr404.class) + @MapBinder(BindToJsonPayload.class) + ListenableFuture> updateMetadata(@PathParam("id") String id, @PayloadParam("metadata") Map metadata); + + /** + * @see ImageApi#getMetadata + */ + @GET + @Path("/images/{id}/metadata/{key}") + @Consumes(MediaType.APPLICATION_JSON) + @ResponseParser(OnlyMetadataValueOrNull.class) + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + ListenableFuture getMetadata(@PathParam("id") String id, @PathParam("key") String key); + + /** + * @see ImageApi#updateMetadata + */ + @PUT + @Path("/images/{id}/metadata/{key}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ResponseParser(OnlyMetadataValueOrNull.class) + @MapBinder(BindMetadataToJsonPayload.class) + ListenableFuture updateMetadata(@PathParam("id") String id, + @PathParam("key") @PayloadParam("key") String key, @PathParam("value") @PayloadParam("value") String value); + + + /** + * @see ImageApi#deleteMetadata + */ + @DELETE + @Consumes + @Path("/images/{id}/metadata/{key}") + @ExceptionParser(ReturnVoidOnNotFoundOr404.class) + ListenableFuture deleteMetadata(@PathParam("id") String id, @PathParam("key") String key); } diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/features/ServerApi.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/features/ServerApi.java index 1378b18856..f7ea8b251d 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/features/ServerApi.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/features/ServerApi.java @@ -18,16 +18,20 @@ */ package org.jclouds.openstack.nova.v2_0.features; -import java.util.Set; +import java.util.Map; import java.util.concurrent.TimeUnit; +import org.jclouds.collect.PagedIterable; import org.jclouds.concurrent.Timeout; +import org.jclouds.javax.annotation.Nullable; +import org.jclouds.openstack.keystone.v2_0.domain.PaginatedCollection; import org.jclouds.openstack.nova.v2_0.domain.RebootType; import org.jclouds.openstack.nova.v2_0.domain.Server; import org.jclouds.openstack.nova.v2_0.domain.ServerCreated; import org.jclouds.openstack.nova.v2_0.options.CreateServerOptions; import org.jclouds.openstack.nova.v2_0.options.RebuildServerOptions; import org.jclouds.openstack.v2_0.domain.Resource; +import org.jclouds.openstack.v2_0.options.PaginationOptions; /** * Provides synchronous access to Server. @@ -47,14 +51,18 @@ public interface ServerApi { * * @return all servers (IDs, names, links) */ - Set listServers(); + PagedIterable list(); + + PaginatedCollection list(PaginationOptions options); /** * List all servers (all details) * * @return all servers (all details) */ - Set listServersInDetail(); + PagedIterable listInDetail(); + + PaginatedCollection listInDetail(PaginationOptions options); /** * List details of the specified server @@ -63,7 +71,7 @@ public interface ServerApi { * id of the server * @return server or null if not found */ - Server getServer(String id); + Server get(String id); /** * Create a new server @@ -81,7 +89,7 @@ public interface ServerApi { */ // blocking call @Timeout(duration = 10, timeUnit = TimeUnit.MINUTES) - ServerCreated createServer(String name, String imageRef, String flavorRef, CreateServerOptions... options); + ServerCreated create(String name, String imageRef, String flavorRef, CreateServerOptions... options); /** * Terminate and delete a server. @@ -90,7 +98,7 @@ public interface ServerApi { * id of the server * @return True if successful, False otherwise */ - Boolean deleteServer(String id); + boolean delete(String id); /** * Start a server @@ -98,7 +106,7 @@ public interface ServerApi { * @param id * id of the server */ - void startServer(String id); + void start(String id); /** * Stop a server @@ -106,7 +114,7 @@ public interface ServerApi { * @param id * id of the server */ - void stopServer(String id); + void stop(String id); /** * Reboot a server. @@ -116,7 +124,7 @@ public interface ServerApi { * @param rebootType * The type of reboot to perform (Hard/Soft) */ - void rebootServer(String id, RebootType rebootType); + void reboot(String id, RebootType rebootType); /** * Resize a server to a new flavor size. @@ -126,7 +134,7 @@ public interface ServerApi { * @param flavorId * id of the new flavor to use */ - void resizeServer(String id, String flavorId); + void resize(String id, String flavorId); /** * Confirm a resize operation. @@ -134,7 +142,7 @@ public interface ServerApi { * @param id * id of the server */ - void confirmResizeServer(String id); + void confirmResize(String id); /** * Revert a resize operation. @@ -142,7 +150,7 @@ public interface ServerApi { * @param id * id of the server */ - void revertResizeServer(String id); + void revertResize(String id); /** * Rebuild a server. @@ -152,7 +160,7 @@ public interface ServerApi { * @param options * Optional parameters to the rebuilding operation. */ - void rebuildServer(String id, RebuildServerOptions... options); + void rebuild(String id, RebuildServerOptions... options); /** * Change the administrative password to a server. @@ -172,7 +180,7 @@ public interface ServerApi { * @param newName * The new name for the server */ - void renameServer(String id, String newName); + void rename(String id, String newName); /** * Create an image from a server. @@ -185,5 +193,72 @@ public interface ServerApi { * @return ID of the new / updated image */ String createImageFromServer(String name, String id); + + /** + * List all metadata for a server. + * + * @param id + * id of the server + * + * @return the metadata as a Map + */ + Map getMetadata(String id); + + /** + * Set the metadata for a server. + * + * @param id + * id of the server + * @param metadata + * a Map containing the metadata + * @return the metadata as a Map + */ + Map setMetadata(String id, Map metadata); + + /** + * Update the metadata for a server. + * + * @param id + * id of the server + * @param metadata + * a Map containing the metadata + * @return the metadata as a Map + */ + Map updateMetadata(String id, Map metadata); + + /** + * Update the metadata for a server. + * + * @param id + * id of the image + * @param metadata + * a Map containing the metadata + * @return the value or null if not present + */ + @Nullable + String getMetadata(String id, String key); + + /** + * Set a metadata item for a server. + * + * @param id + * id of the image + * @param key + * the name of the metadata item + * @param value + * the value of the metadata item + * @return the value you updated + */ + String updateMetadata(String id, String key, String value); + + /** + * Delete a metadata item from a server. + * + * @param id + * id of the image + * @param key + * the name of the metadata item + */ + void deleteMetadata(String id, String key); } diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/features/ServerAsyncApi.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/features/ServerAsyncApi.java index c1d7a7b79b..ef3070728b 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/features/ServerAsyncApi.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/features/ServerAsyncApi.java @@ -18,7 +18,7 @@ */ package org.jclouds.openstack.nova.v2_0.features; -import java.util.Set; +import java.util.Map; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; @@ -30,14 +30,22 @@ import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; +import org.jclouds.collect.PagedIterable; +import org.jclouds.openstack.keystone.v2_0.domain.PaginatedCollection; import org.jclouds.openstack.keystone.v2_0.filters.AuthenticateRequest; +import org.jclouds.openstack.keystone.v2_0.functions.ReturnEmptyPaginatedCollectionOnNotFoundOr404; +import org.jclouds.openstack.nova.v2_0.binders.BindMetadataToJsonPayload; import org.jclouds.openstack.nova.v2_0.domain.RebootType; import org.jclouds.openstack.nova.v2_0.domain.Server; import org.jclouds.openstack.nova.v2_0.domain.ServerCreated; import org.jclouds.openstack.nova.v2_0.functions.ParseImageIdFromLocationHeader; +import org.jclouds.openstack.nova.v2_0.functions.internal.OnlyMetadataValueOrNull; +import org.jclouds.openstack.nova.v2_0.functions.internal.ParseServerDetails; +import org.jclouds.openstack.nova.v2_0.functions.internal.ParseServers; import org.jclouds.openstack.nova.v2_0.options.CreateServerOptions; import org.jclouds.openstack.nova.v2_0.options.RebuildServerOptions; import org.jclouds.openstack.v2_0.domain.Resource; +import org.jclouds.openstack.v2_0.options.PaginationOptions; import org.jclouds.rest.annotations.ExceptionParser; import org.jclouds.rest.annotations.MapBinder; import org.jclouds.rest.annotations.Payload; @@ -46,11 +54,15 @@ import org.jclouds.rest.annotations.RequestFilters; import org.jclouds.rest.annotations.ResponseParser; import org.jclouds.rest.annotations.SelectJson; import org.jclouds.rest.annotations.SkipEncoding; +import org.jclouds.rest.annotations.Transform; import org.jclouds.rest.annotations.Unwrap; +import org.jclouds.rest.binders.BindToJsonPayload; import org.jclouds.rest.functions.MapHttp4xxCodesToExceptions; -import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404; +import org.jclouds.rest.functions.ReturnEmptyMapOnNotFoundOr404; +import org.jclouds.rest.functions.ReturnEmptyPagedIterableOnNotFoundOr404; import org.jclouds.rest.functions.ReturnFalseOnNotFoundOr404; import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; +import org.jclouds.rest.functions.ReturnVoidOnNotFoundOr404; import com.google.common.util.concurrent.ListenableFuture; @@ -59,8 +71,7 @@ import com.google.common.util.concurrent.ListenableFuture; *

* * @see ServerApi - * @see * @author Adrian Cole */ @@ -69,123 +80,145 @@ import com.google.common.util.concurrent.ListenableFuture; public interface ServerAsyncApi { /** - * @see ServerApi#listServers + * @see ServerApi#list() */ @GET - @SelectJson("servers") @Consumes(MediaType.APPLICATION_JSON) @Path("/servers") - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> listServers(); + @RequestFilters(AuthenticateRequest.class) + @ResponseParser(ParseServers.class) + @Transform(ParseServers.ToPagedIterable.class) + @ExceptionParser(ReturnEmptyPagedIterableOnNotFoundOr404.class) + ListenableFuture> list(); + + /** @see ServerApi#list(PaginationOptions) */ + @GET + @Consumes(MediaType.APPLICATION_JSON) + @Path("/servers") + @RequestFilters(AuthenticateRequest.class) + @ResponseParser(ParseServers.class) + @ExceptionParser(ReturnEmptyPaginatedCollectionOnNotFoundOr404.class) + ListenableFuture> list(PaginationOptions options); /** - * @see ServerApi#listServersInDetail + * @see ServerApi#listInDetail() */ @GET - @SelectJson("servers") @Consumes(MediaType.APPLICATION_JSON) @Path("/servers/detail") - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> listServersInDetail(); + @RequestFilters(AuthenticateRequest.class) + @ResponseParser(ParseServerDetails.class) + @Transform(ParseServerDetails.ToPagedIterable.class) + @ExceptionParser(ReturnEmptyPagedIterableOnNotFoundOr404.class) + ListenableFuture> listInDetail(); + + /** @see ServerApi#listInDetail(PaginationOptions) */ + @GET + @Consumes(MediaType.APPLICATION_JSON) + @Path("/servers/detail") + @RequestFilters(AuthenticateRequest.class) + @ResponseParser(ParseServerDetails.class) + @ExceptionParser(ReturnEmptyPaginatedCollectionOnNotFoundOr404.class) + ListenableFuture> listInDetail(PaginationOptions options); /** - * @see ServerApi#getServer + * @see ServerApi#get */ @GET @SelectJson("server") @Consumes(MediaType.APPLICATION_JSON) @Path("/servers/{id}") @ExceptionParser(ReturnNullOnNotFoundOr404.class) - ListenableFuture getServer(@PathParam("id") String id); + ListenableFuture get(@PathParam("id") String id); /** - * @see ServerApi#deleteServer + * @see ServerApi#delete */ @DELETE @Consumes @ExceptionParser(ReturnFalseOnNotFoundOr404.class) @Path("/servers/{id}") - ListenableFuture deleteServer(@PathParam("id") String id); + ListenableFuture delete(@PathParam("id") String id); /** - * @see ServerApi#startServer + * @see ServerApi#start */ @POST @Path("/servers/{id}/action") @Consumes @Produces(MediaType.APPLICATION_JSON) @Payload("{\"os-start\":null}") - ListenableFuture startServer(@PathParam("id") String id); + ListenableFuture start(@PathParam("id") String id); /** - * @see ServerApi#stopServer + * @see ServerApi#stop */ @POST @Path("/servers/{id}/action") @Consumes @Produces(MediaType.APPLICATION_JSON) @Payload("{\"os-stop\":null}") - ListenableFuture stopServer(@PathParam("id") String id); - + ListenableFuture stop(@PathParam("id") String id); + /** - * @see ServerApi#rebootServer + * @see ServerApi#reboot */ @POST @Path("/servers/{id}/action") @Consumes @Produces(MediaType.APPLICATION_JSON) @Payload("%7B\"reboot\":%7B\"type\":\"{type}\"%7D%7D") - ListenableFuture rebootServer(@PathParam("id") String id, @PayloadParam("type") RebootType rebootType); + ListenableFuture reboot(@PathParam("id") String id, @PayloadParam("type") RebootType rebootType); /** - * @see ServerApi#resizeServer + * @see ServerApi#resize */ @POST @Path("/servers/{id}/action") @Consumes @Produces(MediaType.APPLICATION_JSON) @Payload("%7B\"resize\":%7B\"flavorRef\":{flavorId}%7D%7D") - ListenableFuture resizeServer(@PathParam("id") String id, @PayloadParam("flavorId") String flavorId); + ListenableFuture resize(@PathParam("id") String id, @PayloadParam("flavorId") String flavorId); /** - * @see ServerApi#confirmResizeServer + * @see ServerApi#confirmResize */ @POST @Path("/servers/{id}/action") @Consumes @Produces(MediaType.APPLICATION_JSON) @Payload("{\"confirmResize\":null}") - ListenableFuture confirmResizeServer(@PathParam("id") String id); + ListenableFuture confirmResize(@PathParam("id") String id); /** - * @see ServerApi#revertResizeServer + * @see ServerApi#revertResize */ @POST @Path("/servers/{id}/action") @Consumes @Produces(MediaType.APPLICATION_JSON) @Payload("{\"revertResize\":null}") - ListenableFuture revertResizeServer(@PathParam("id") String id); + ListenableFuture revertResize(@PathParam("id") String id); /** - * @see ServerApi#createServer + * @see ServerApi#create */ @POST @Unwrap @Consumes(MediaType.APPLICATION_JSON) @Path("/servers") @MapBinder(CreateServerOptions.class) - ListenableFuture createServer(@PayloadParam("name") String name, @PayloadParam("imageRef") String imageRef, - @PayloadParam("flavorRef") String flavorRef, CreateServerOptions... options); + ListenableFuture create(@PayloadParam("name") String name, @PayloadParam("imageRef") String imageRef, + @PayloadParam("flavorRef") String flavorRef, CreateServerOptions... options); /** - * @see ServerApi#rebuildServer + * @see ServerApi#rebuild */ @POST @Path("/servers/{id}/action") @Consumes @MapBinder(RebuildServerOptions.class) - ListenableFuture rebuildServer(@PathParam("id") String id, RebuildServerOptions... options); + ListenableFuture rebuild(@PathParam("id") String id, RebuildServerOptions... options); /** * @see ServerApi#changeAdminPass @@ -198,14 +231,14 @@ public interface ServerAsyncApi { ListenableFuture changeAdminPass(@PathParam("id") String id, @PayloadParam("adminPass") String adminPass); /** - * @see ServerApi#renameServer + * @see ServerApi#rename */ @PUT @Path("/servers/{id}") @Consumes @Produces(MediaType.APPLICATION_JSON) @Payload("%7B\"server\":%7B\"name\":\"{name}\"%7D%7D") - ListenableFuture renameServer(@PathParam("id") String id, @PayloadParam("name") String newName); + ListenableFuture rename(@PathParam("id") String id, @PayloadParam("name") String newName); /** * @see ServerApi#createImageFromServer @@ -219,4 +252,71 @@ public interface ServerAsyncApi { @ResponseParser(ParseImageIdFromLocationHeader.class) ListenableFuture createImageFromServer(@PayloadParam("name") String name, @PathParam("id") String id); + /** + * @see ServerApi#getMetadata + */ + @GET + @SelectJson("metadata") + @Path("/servers/{id}/metadata") + @Consumes(MediaType.APPLICATION_JSON) + @ExceptionParser(ReturnEmptyMapOnNotFoundOr404.class) + ListenableFuture> getMetadata(@PathParam("id") String id); + + /** + * @see ServerApi#setMetadata + */ + @PUT + @SelectJson("metadata") + @Path("/servers/{id}/metadata") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ExceptionParser(ReturnEmptyMapOnNotFoundOr404.class) + @MapBinder(BindToJsonPayload.class) + ListenableFuture> setMetadata(@PathParam("id") String id, + @PayloadParam("metadata") Map metadata); + + /** + * @see ServerApi#updateMetadata + */ + @POST + @SelectJson("metadata") + @Path("/servers/{id}/metadata") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ExceptionParser(ReturnEmptyMapOnNotFoundOr404.class) + @MapBinder(BindToJsonPayload.class) + ListenableFuture> updateMetadata(@PathParam("id") String id, + @PayloadParam("metadata") Map metadata); + + /** + * @see ServerApi#getMetadata + */ + @GET + @Path("/servers/{id}/metadata/{key}") + @Consumes(MediaType.APPLICATION_JSON) + @ResponseParser(OnlyMetadataValueOrNull.class) + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + ListenableFuture getMetadata(@PathParam("id") String id, @PathParam("key") String key); + + /** + * @see ServerApi#updateMetadata + */ + @PUT + @Path("/servers/{id}/metadata/{key}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ResponseParser(OnlyMetadataValueOrNull.class) + @MapBinder(BindMetadataToJsonPayload.class) + ListenableFuture updateMetadata(@PathParam("id") String id, + @PathParam("key") @PayloadParam("key") String key, @PathParam("value") @PayloadParam("value") String value); + + /** + * @see ServerApi#deleteMetadata + */ + @DELETE + @Consumes + @Path("/servers/{id}/metadata/{key}") + @ExceptionParser(ReturnVoidOnNotFoundOr404.class) + ListenableFuture deleteMetadata(@PathParam("id") String id, @PathParam("key") String key); + } diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/functions/internal/OnlyMetadataValueOrNull.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/functions/internal/OnlyMetadataValueOrNull.java new file mode 100644 index 0000000000..d00c2e7ea6 --- /dev/null +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/functions/internal/OnlyMetadataValueOrNull.java @@ -0,0 +1,65 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.nova.v2_0.functions.internal; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.Map; + +import javax.inject.Singleton; + +import org.jclouds.http.HttpResponse; +import org.jclouds.http.functions.ParseJson; +import org.jclouds.json.internal.GsonWrapper; + +import com.google.common.base.Function; +import com.google.common.base.Supplier; +import com.google.common.collect.Iterables; +import com.google.inject.Inject; +import com.google.inject.TypeLiteral; + +/** + * + * @author Adrian Cole + */ +@Singleton +public class OnlyMetadataValueOrNull implements Function { + private final ParseJson parser; + + private static class Wrapper implements Supplier { + private Map metadata; + + @Override + public String get() { + return metadata == null ? null : Iterables.get(metadata.values(), 0, null); + } + + } + + @Inject + public OnlyMetadataValueOrNull(GsonWrapper gsonView) { + this.parser = new ParseJson(checkNotNull(gsonView, "gsonView"), new TypeLiteral() { + }); + } + + public String apply(HttpResponse response) { + checkNotNull(response, "response"); + return parser.apply(response).get(); + } +} diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/functions/internal/ParseFlavorDetails.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/functions/internal/ParseFlavorDetails.java new file mode 100644 index 0000000000..45354e057b --- /dev/null +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/functions/internal/ParseFlavorDetails.java @@ -0,0 +1,96 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.nova.v2_0.functions.internal; + +import static com.google.common.base.Preconditions.checkNotNull; +import static org.jclouds.openstack.v2_0.options.PaginationOptions.Builder.marker; + +import java.beans.ConstructorProperties; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.collect.IterableWithMarker; +import org.jclouds.collect.internal.CallerArg0ToPagedIterable; +import org.jclouds.http.functions.ParseJson; +import org.jclouds.json.Json; +import org.jclouds.openstack.keystone.v2_0.domain.PaginatedCollection; +import org.jclouds.openstack.nova.v2_0.NovaApi; +import org.jclouds.openstack.nova.v2_0.domain.Flavor; +import org.jclouds.openstack.nova.v2_0.features.FlavorApi; +import org.jclouds.openstack.nova.v2_0.functions.internal.ParseFlavorDetails.Flavors; +import org.jclouds.openstack.v2_0.domain.Link; + +import com.google.common.annotations.Beta; +import com.google.common.base.Function; +import com.google.inject.TypeLiteral; + +/** + * boiler plate until we determine a better way + * + * @author Adrian Cole + */ +@Beta +@Singleton +public class ParseFlavorDetails extends ParseJson> { + static class Flavors extends PaginatedCollection { + + @ConstructorProperties({ "flavors", "flavors_links" }) + protected Flavors(Iterable flavors, Iterable flavors_links) { + super(flavors, flavors_links); + } + + } + + @Inject + public ParseFlavorDetails(Json json) { + super(json, new TypeLiteral>() { + }); + } + + public static class ToPagedIterable extends CallerArg0ToPagedIterable { + + private final NovaApi api; + + @Inject + protected ToPagedIterable(NovaApi api) { + this.api = checkNotNull(api, "api"); + } + + @Override + protected Function> markerToNextForCallingArg0(final String zone) { + final FlavorApi flavorApi = api.getFlavorApiForZone(zone); + return new Function>() { + + @SuppressWarnings("unchecked") + @Override + public IterableWithMarker apply(Object input) { + return IterableWithMarker.class.cast(flavorApi.listInDetail(marker(input.toString()))); + } + + @Override + public String toString() { + return "listFlavorsInDetail()"; + } + }; + } + + } + +} diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/functions/internal/ParseFlavors.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/functions/internal/ParseFlavors.java new file mode 100644 index 0000000000..fd28914d88 --- /dev/null +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/functions/internal/ParseFlavors.java @@ -0,0 +1,96 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.nova.v2_0.functions.internal; + +import static com.google.common.base.Preconditions.checkNotNull; +import static org.jclouds.openstack.v2_0.options.PaginationOptions.Builder.marker; + +import java.beans.ConstructorProperties; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.collect.IterableWithMarker; +import org.jclouds.collect.internal.CallerArg0ToPagedIterable; +import org.jclouds.http.functions.ParseJson; +import org.jclouds.json.Json; +import org.jclouds.openstack.keystone.v2_0.domain.PaginatedCollection; +import org.jclouds.openstack.nova.v2_0.NovaApi; +import org.jclouds.openstack.nova.v2_0.features.FlavorApi; +import org.jclouds.openstack.nova.v2_0.functions.internal.ParseFlavors.Flavors; +import org.jclouds.openstack.v2_0.domain.Link; +import org.jclouds.openstack.v2_0.domain.Resource; + +import com.google.common.annotations.Beta; +import com.google.common.base.Function; +import com.google.inject.TypeLiteral; + +/** + * boiler plate until we determine a better way + * + * @author Adrian Cole + */ +@Beta +@Singleton +public class ParseFlavors extends ParseJson> { + static class Flavors extends PaginatedCollection { + + @ConstructorProperties({ "flavors", "flavors_links" }) + protected Flavors(Iterable flavors, Iterable flavors_links) { + super(flavors, flavors_links); + } + + } + + @Inject + public ParseFlavors(Json json) { + super(json, new TypeLiteral>() { + }); + } + + public static class ToPagedIterable extends CallerArg0ToPagedIterable { + + private final NovaApi api; + + @Inject + protected ToPagedIterable(NovaApi api) { + this.api = checkNotNull(api, "api"); + } + + @Override + protected Function> markerToNextForCallingArg0(final String zone) { + final FlavorApi flavorApi = api.getFlavorApiForZone(zone); + return new Function>() { + + @SuppressWarnings("unchecked") + @Override + public IterableWithMarker apply(Object input) { + return IterableWithMarker.class.cast(flavorApi.list(marker(input.toString()))); + } + + @Override + public String toString() { + return "listFlavors()"; + } + }; + } + + } + +} diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/functions/internal/ParseImageDetails.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/functions/internal/ParseImageDetails.java new file mode 100644 index 0000000000..225e9f15e7 --- /dev/null +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/functions/internal/ParseImageDetails.java @@ -0,0 +1,96 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.nova.v2_0.functions.internal; + +import static com.google.common.base.Preconditions.checkNotNull; +import static org.jclouds.openstack.v2_0.options.PaginationOptions.Builder.marker; + +import java.beans.ConstructorProperties; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.collect.IterableWithMarker; +import org.jclouds.collect.internal.CallerArg0ToPagedIterable; +import org.jclouds.http.functions.ParseJson; +import org.jclouds.json.Json; +import org.jclouds.openstack.keystone.v2_0.domain.PaginatedCollection; +import org.jclouds.openstack.nova.v2_0.NovaApi; +import org.jclouds.openstack.nova.v2_0.domain.Image; +import org.jclouds.openstack.nova.v2_0.features.ImageApi; +import org.jclouds.openstack.nova.v2_0.functions.internal.ParseImageDetails.Images; +import org.jclouds.openstack.v2_0.domain.Link; + +import com.google.common.annotations.Beta; +import com.google.common.base.Function; +import com.google.inject.TypeLiteral; + +/** + * boiler plate until we determine a better way + * + * @author Adrian Cole + */ +@Beta +@Singleton +public class ParseImageDetails extends ParseJson> { + static class Images extends PaginatedCollection { + + @ConstructorProperties({ "images", "images_links" }) + protected Images(Iterable images, Iterable images_links) { + super(images, images_links); + } + + } + + @Inject + public ParseImageDetails(Json json) { + super(json, new TypeLiteral>() { + }); + } + + public static class ToPagedIterable extends CallerArg0ToPagedIterable { + + private final NovaApi api; + + @Inject + protected ToPagedIterable(NovaApi api) { + this.api = checkNotNull(api, "api"); + } + + @Override + protected Function> markerToNextForCallingArg0(final String zone) { + final ImageApi imageApi = api.getImageApiForZone(zone); + return new Function>() { + + @SuppressWarnings("unchecked") + @Override + public IterableWithMarker apply(Object input) { + return IterableWithMarker.class.cast(imageApi.listInDetail(marker(input.toString()))); + } + + @Override + public String toString() { + return "listInDetail()"; + } + }; + } + + } + +} diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/functions/internal/ParseImages.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/functions/internal/ParseImages.java new file mode 100644 index 0000000000..51680f72c4 --- /dev/null +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/functions/internal/ParseImages.java @@ -0,0 +1,96 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.nova.v2_0.functions.internal; + +import static com.google.common.base.Preconditions.checkNotNull; +import static org.jclouds.openstack.v2_0.options.PaginationOptions.Builder.marker; + +import java.beans.ConstructorProperties; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.collect.IterableWithMarker; +import org.jclouds.collect.internal.CallerArg0ToPagedIterable; +import org.jclouds.http.functions.ParseJson; +import org.jclouds.json.Json; +import org.jclouds.openstack.keystone.v2_0.domain.PaginatedCollection; +import org.jclouds.openstack.nova.v2_0.NovaApi; +import org.jclouds.openstack.nova.v2_0.features.ImageApi; +import org.jclouds.openstack.nova.v2_0.functions.internal.ParseImages.Images; +import org.jclouds.openstack.v2_0.domain.Link; +import org.jclouds.openstack.v2_0.domain.Resource; + +import com.google.common.annotations.Beta; +import com.google.common.base.Function; +import com.google.inject.TypeLiteral; + +/** + * boiler plate until we determine a better way + * + * @author Adrian Cole + */ +@Beta +@Singleton +public class ParseImages extends ParseJson> { + static class Images extends PaginatedCollection { + + @ConstructorProperties({ "images", "images_links" }) + protected Images(Iterable images, Iterable images_links) { + super(images, images_links); + } + + } + + @Inject + public ParseImages(Json json) { + super(json, new TypeLiteral>() { + }); + } + + public static class ToPagedIterable extends CallerArg0ToPagedIterable { + + private final NovaApi api; + + @Inject + protected ToPagedIterable(NovaApi api) { + this.api = checkNotNull(api, "api"); + } + + @Override + protected Function> markerToNextForCallingArg0(final String zone) { + final ImageApi imageApi = api.getImageApiForZone(zone); + return new Function>() { + + @SuppressWarnings("unchecked") + @Override + public IterableWithMarker apply(Object input) { + return IterableWithMarker.class.cast(imageApi.list(marker(input.toString()))); + } + + @Override + public String toString() { + return "list()"; + } + }; + } + + } + +} diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/functions/internal/ParseKeyPairs.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/functions/internal/ParseKeyPairs.java new file mode 100644 index 0000000000..1f4d54ab3c --- /dev/null +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/functions/internal/ParseKeyPairs.java @@ -0,0 +1,66 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.nova.v2_0.functions.internal; + +import static com.google.common.base.Preconditions.checkNotNull; + +import javax.inject.Singleton; + +import org.jclouds.http.HttpResponse; +import org.jclouds.http.functions.ParseFirstJsonValueNamed; +import org.jclouds.json.internal.GsonWrapper; +import org.jclouds.openstack.nova.v2_0.domain.KeyPair; + +import com.google.common.base.Function; +import com.google.common.base.Supplier; +import com.google.common.base.Suppliers; +import com.google.common.collect.FluentIterable; +import com.google.inject.Inject; +import com.google.inject.TypeLiteral; + +/** + * + * @author Adrian Cole + */ +@Singleton +public class ParseKeyPairs implements Function> { + private final ParseFirstJsonValueNamed> parser; + + private static class Wrapper implements Supplier { + private KeyPair keypair; + + @Override + public KeyPair get() { + return keypair; + } + + } + + @Inject + public ParseKeyPairs(GsonWrapper gsonView) { + this.parser = new ParseFirstJsonValueNamed>(checkNotNull(gsonView, "gsonView"), + new TypeLiteral>() { + }, "keypairs"); + } + + public FluentIterable apply(HttpResponse response) { + checkNotNull(response, "response"); + return parser.apply(response).transform(Suppliers. supplierFunction()); + } +} diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/functions/internal/ParseServerDetails.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/functions/internal/ParseServerDetails.java new file mode 100644 index 0000000000..588d99d4e3 --- /dev/null +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/functions/internal/ParseServerDetails.java @@ -0,0 +1,96 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.nova.v2_0.functions.internal; + +import static com.google.common.base.Preconditions.checkNotNull; +import static org.jclouds.openstack.v2_0.options.PaginationOptions.Builder.marker; + +import java.beans.ConstructorProperties; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.collect.IterableWithMarker; +import org.jclouds.collect.internal.CallerArg0ToPagedIterable; +import org.jclouds.http.functions.ParseJson; +import org.jclouds.json.Json; +import org.jclouds.openstack.keystone.v2_0.domain.PaginatedCollection; +import org.jclouds.openstack.nova.v2_0.NovaApi; +import org.jclouds.openstack.nova.v2_0.domain.Server; +import org.jclouds.openstack.nova.v2_0.features.ServerApi; +import org.jclouds.openstack.nova.v2_0.functions.internal.ParseServerDetails.Servers; +import org.jclouds.openstack.v2_0.domain.Link; + +import com.google.common.annotations.Beta; +import com.google.common.base.Function; +import com.google.inject.TypeLiteral; + +/** + * boiler plate until we determine a better way + * + * @author Adrian Cole + */ +@Beta +@Singleton +public class ParseServerDetails extends ParseJson> { + static class Servers extends PaginatedCollection { + + @ConstructorProperties({ "servers", "servers_links" }) + protected Servers(Iterable servers, Iterable servers_links) { + super(servers, servers_links); + } + + } + + @Inject + public ParseServerDetails(Json json) { + super(json, new TypeLiteral>() { + }); + } + + public static class ToPagedIterable extends CallerArg0ToPagedIterable { + + private final NovaApi api; + + @Inject + protected ToPagedIterable(NovaApi api) { + this.api = checkNotNull(api, "api"); + } + + @Override + protected Function> markerToNextForCallingArg0(final String zone) { + final ServerApi serverApi = api.getServerApiForZone(zone); + return new Function>() { + + @SuppressWarnings("unchecked") + @Override + public IterableWithMarker apply(Object input) { + return IterableWithMarker.class.cast(serverApi.listInDetail(marker(input.toString()))); + } + + @Override + public String toString() { + return "listInDetail()"; + } + }; + } + + } + +} diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/functions/internal/ParseServers.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/functions/internal/ParseServers.java new file mode 100644 index 0000000000..fb8d05d69f --- /dev/null +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/functions/internal/ParseServers.java @@ -0,0 +1,96 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.nova.v2_0.functions.internal; + +import static com.google.common.base.Preconditions.checkNotNull; +import static org.jclouds.openstack.v2_0.options.PaginationOptions.Builder.marker; + +import java.beans.ConstructorProperties; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.collect.IterableWithMarker; +import org.jclouds.collect.internal.CallerArg0ToPagedIterable; +import org.jclouds.http.functions.ParseJson; +import org.jclouds.json.Json; +import org.jclouds.openstack.keystone.v2_0.domain.PaginatedCollection; +import org.jclouds.openstack.nova.v2_0.NovaApi; +import org.jclouds.openstack.nova.v2_0.features.ServerApi; +import org.jclouds.openstack.nova.v2_0.functions.internal.ParseServers.Servers; +import org.jclouds.openstack.v2_0.domain.Link; +import org.jclouds.openstack.v2_0.domain.Resource; + +import com.google.common.annotations.Beta; +import com.google.common.base.Function; +import com.google.inject.TypeLiteral; + +/** + * boiler plate until we determine a better way + * + * @author Adrian Cole + */ +@Beta +@Singleton +public class ParseServers extends ParseJson> { + static class Servers extends PaginatedCollection { + + @ConstructorProperties({ "servers", "servers_links" }) + protected Servers(Iterable servers, Iterable servers_links) { + super(servers, servers_links); + } + + } + + @Inject + public ParseServers(Json json) { + super(json, new TypeLiteral>() { + }); + } + + public static class ToPagedIterable extends CallerArg0ToPagedIterable { + + private final NovaApi api; + + @Inject + protected ToPagedIterable(NovaApi api) { + this.api = checkNotNull(api, "api"); + } + + @Override + protected Function> markerToNextForCallingArg0(final String zone) { + final ServerApi serverApi = api.getServerApiForZone(zone); + return new Function>() { + + @SuppressWarnings("unchecked") + @Override + public IterableWithMarker apply(Object input) { + return IterableWithMarker.class.cast(serverApi.list(marker(input.toString()))); + } + + @Override + public String toString() { + return "list()"; + } + }; + } + + } + +} diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/options/CreateBackupOfServerOptions.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/options/CreateBackupOfServerOptions.java index 93ed7563a3..b56eea2749 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/options/CreateBackupOfServerOptions.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/options/CreateBackupOfServerOptions.java @@ -55,7 +55,7 @@ public class CreateBackupOfServerOptions implements MapBinder { @Override public R bindToRequest(R request, Object toBind) { - throw new IllegalStateException("createBackupOfServer is a POST operation"); + throw new IllegalStateException("createBackup is a POST operation"); } @Override diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/options/CreateServerOptions.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/options/CreateServerOptions.java index 4acf3594bb..db2bbed3ee 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/options/CreateServerOptions.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/options/CreateServerOptions.java @@ -152,7 +152,7 @@ public class CreateServerOptions implements MapBinder { return string().toString(); } - private class ServerRequest { + static class ServerRequest { final String name; final String imageRef; final String flavorRef; diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/options/ListOptions.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/options/ListOptions.java index 8cd271c3ae..4d8fa91b04 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/options/ListOptions.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/options/ListOptions.java @@ -20,16 +20,16 @@ package org.jclouds.openstack.nova.v2_0.options; import java.util.Date; -import org.jclouds.openstack.v2_0.options.BaseListOptions; +import org.jclouds.openstack.v2_0.options.PaginationOptions; /** * Options used to control the amount of detail in the request. * - * @see BaseListOptions + * @see PaginationOptions * @see * @author Adrian Cole */ -public class ListOptions extends BaseListOptions { +public class ListOptions extends PaginationOptions { public static final ListOptions NONE = new ListOptions(); @@ -56,8 +56,8 @@ public class ListOptions extends BaseListOptions { * {@inheritDoc} */ @Override - public ListOptions maxResults(int limit) { - super.maxResults(limit); + public ListOptions limit(int limit) { + super.limit(limit); return this; } @@ -66,8 +66,8 @@ public class ListOptions extends BaseListOptions { * {@inheritDoc} */ @Override - public ListOptions startAt(long offset) { - super.startAt(offset); + public ListOptions marker(String marker) { + super.marker(marker); return this; } @@ -82,23 +82,23 @@ public class ListOptions extends BaseListOptions { } /** - * @see BaseListOptions#startAt(long) + * @see PaginationOptions#marker(String) */ - public static ListOptions startAt(long prefix) { + public static ListOptions marker(String marker) { ListOptions options = new ListOptions(); - return options.startAt(prefix); + return options.marker(marker); } /** - * @see BaseListOptions#maxResults(long) + * @see PaginationOptions#limit(long) */ public static ListOptions maxResults(int maxKeys) { ListOptions options = new ListOptions(); - return options.maxResults(maxKeys); + return options.limit(maxKeys); } /** - * @see BaseListOptions#changesSince(Date) + * @see PaginationOptions#changesSince(Date) */ public static ListOptions changesSince(Date since) { ListOptions options = new ListOptions(); diff --git a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/predicates/FindSecurityGroupWithNameAndReturnTrue.java b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/predicates/FindSecurityGroupWithNameAndReturnTrue.java index 0c435e3c61..bf4f1ad2ac 100644 --- a/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/predicates/FindSecurityGroupWithNameAndReturnTrue.java +++ b/apis/openstack-nova/src/main/java/org/jclouds/openstack/nova/v2_0/predicates/FindSecurityGroupWithNameAndReturnTrue.java @@ -67,7 +67,7 @@ public class FindSecurityGroupWithNameAndReturnTrue implements Predicate() { + SecurityGroup returnVal = Iterables.find(api.get().list(), new Predicate() { @Override public boolean apply(SecurityGroup input) { diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/AccessKeyAndSecretKeyAndTenantIdAuthenticationExpectTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/AccessKeyAndSecretKeyAndTenantIdAuthenticationExpectTest.java index 41ec1504a5..4a599b3dc5 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/AccessKeyAndSecretKeyAndTenantIdAuthenticationExpectTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/AccessKeyAndSecretKeyAndTenantIdAuthenticationExpectTest.java @@ -68,9 +68,9 @@ public class AccessKeyAndSecretKeyAndTenantIdAuthenticationExpectTest extends Ba NovaApi apiWhenServersExist = requestsSendResponses(keystoneAuthWithAccessKeyAndSecretKeyAndTenantId, responseWithKeystoneAccess, listServers, listServersResponse); - assertEquals(apiWhenServersExist.getConfiguredZones(), ImmutableSet.of("az-1.region-a.geo-1")); + assertEquals(apiWhenServersExist.getConfiguredZones(), ImmutableSet.of("az-1.region-a.geo-1", "az-2.region-a.geo-1", "az-3.region-a.geo-1")); - assertEquals(apiWhenServersExist.getServerApiForZone("az-1.region-a.geo-1").listServers().toString(), + assertEquals(apiWhenServersExist.getServerApiForZone("az-1.region-a.geo-1").list().concat().toString(), new ParseServerListTest().expected().toString()); } diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/AccessKeyAndSecretKeyAndTenantNamePropertyAuthenticationExpectTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/AccessKeyAndSecretKeyAndTenantNamePropertyAuthenticationExpectTest.java index 0c113d0b10..6c8b2b9610 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/AccessKeyAndSecretKeyAndTenantNamePropertyAuthenticationExpectTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/AccessKeyAndSecretKeyAndTenantNamePropertyAuthenticationExpectTest.java @@ -37,7 +37,7 @@ import com.google.common.collect.ImmutableSet; * @see KeystoneProperties#CREDENTIAL_TYPE * @author Adrian Cole */ -@Test(groups = "unit", testName = "AccessKeyAndSecretKeyAndTenantIdAuthenticationExpectTest") +@Test(groups = "unit", testName = "AccessKeyAndSecretKeyAndTenantNamePropertyAuthenticationExpectTest") public class AccessKeyAndSecretKeyAndTenantNamePropertyAuthenticationExpectTest extends BaseNovaApiExpectTest { public AccessKeyAndSecretKeyAndTenantNamePropertyAuthenticationExpectTest() { identity = "identity"; @@ -68,9 +68,9 @@ public class AccessKeyAndSecretKeyAndTenantNamePropertyAuthenticationExpectTest NovaApi apiWhenServersExist = requestsSendResponses(keystoneAuthWithAccessKeyAndSecretKeyAndTenantName, responseWithKeystoneAccess, listServers, listServersResponse); - assertEquals(apiWhenServersExist.getConfiguredZones(), ImmutableSet.of("az-1.region-a.geo-1")); + assertEquals(apiWhenServersExist.getConfiguredZones(), ImmutableSet.of("az-1.region-a.geo-1", "az-2.region-a.geo-1", "az-3.region-a.geo-1")); - assertEquals(apiWhenServersExist.getServerApiForZone("az-1.region-a.geo-1").listServers().toString(), + assertEquals(apiWhenServersExist.getServerApiForZone("az-1.region-a.geo-1").list().concat().toString(), new ParseServerListTest().expected().toString()); } diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/AccessKeyAndSecretKeyAuthenticationExpectTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/AccessKeyAndSecretKeyAuthenticationExpectTest.java index 3e737e0fa7..eaba80fd59 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/AccessKeyAndSecretKeyAuthenticationExpectTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/AccessKeyAndSecretKeyAuthenticationExpectTest.java @@ -63,9 +63,9 @@ public class AccessKeyAndSecretKeyAuthenticationExpectTest extends BaseNovaApiEx NovaApi apiWhenServersExist = requestsSendResponses(keystoneAuthWithAccessKeyAndSecretKeyAndTenantName, responseWithKeystoneAccess, listServers, listServersResponse); - assertEquals(apiWhenServersExist.getConfiguredZones(), ImmutableSet.of("az-1.region-a.geo-1")); + assertEquals(apiWhenServersExist.getConfiguredZones(), ImmutableSet.of("az-1.region-a.geo-1", "az-2.region-a.geo-1", "az-3.region-a.geo-1")); - assertEquals(apiWhenServersExist.getServerApiForZone("az-1.region-a.geo-1").listServers().toString(), + assertEquals(apiWhenServersExist.getServerApiForZone("az-1.region-a.geo-1").list().concat().toString(), new ParseServerListTest().expected().toString()); } diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/EndpointIdIsRandomExpectTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/EndpointIdIsRandomExpectTest.java new file mode 100644 index 0000000000..d58db693a4 --- /dev/null +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/EndpointIdIsRandomExpectTest.java @@ -0,0 +1,74 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.nova.v2_0; + +import static org.jclouds.Constants.PROPERTY_ENDPOINT; +import static org.testng.Assert.assertEquals; + +import java.util.Properties; + +import org.jclouds.http.HttpRequest; +import org.jclouds.http.HttpResponse; +import org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiExpectTest; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableSet; + +/** + * Tests to ensure that we can pick the only endpoint of a service + * + * @author Adrian Cole + */ +@Test(groups = "unit", testName = "EndpointIdIsRandomExpectTest") +public class EndpointIdIsRandomExpectTest extends BaseNovaApiExpectTest { + + public EndpointIdIsRandomExpectTest() { + this.identity = "demo:demo"; + this.credential = "password"; + } + + @Override + protected Properties setupProperties() { + Properties overrides = super.setupProperties(); + overrides.setProperty(PROPERTY_ENDPOINT, "http://10.10.10.10:5000/v2.0/"); + return overrides; + } + + public void testVersionMatchOnConfiguredZonesWhenResponseIs2xx() { + + HttpRequest authenticate = HttpRequest + .builder() + .method("POST") + .endpoint("http://10.10.10.10:5000/v2.0/tokens") + .addHeader("Accept", "application/json") + .payload( + payloadFromStringWithContentType( + "{\"auth\":{\"passwordCredentials\":{\"username\":\"demo\",\"password\":\"password\"},\"tenantName\":\"demo\"}}", + "application/json")).build(); + + HttpResponse authenticationResponse = HttpResponse.builder().statusCode(200) + .payload(payloadFromResourceWithContentType("/access_version_uids.json", "application/json")).build(); + + NovaApi whenNovaRegionExists = requestSendsResponse(authenticate, authenticationResponse); + + assertEquals(whenNovaRegionExists.getConfiguredZones(), ImmutableSet.of("RegionOne")); + + } + +} diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/NovaErrorHandlerTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/NovaErrorHandlerTest.java index ec16e85c08..2691715488 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/NovaErrorHandlerTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/NovaErrorHandlerTest.java @@ -81,7 +81,7 @@ public class NovaErrorHandlerTest { URI.create("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/37936628937291/os-floating-ips"), 400, "HTTP/1.1 400 Bad Request", - "{\"badRequest\": {\"message\": \"AddressLimitExceeded: Address quota exceeded. You cannot allocate any more addresses\", \"code\": 400}}", + "{\"badRequest\": {\"message\": \"AddressLimitExceeded: Address quota exceeded. You cannot create any more addresses\", \"code\": 400}}", InsufficientResourcesException.class); } diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/PasswordAuthenticationExpectTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/PasswordAuthenticationExpectTest.java index 51c6815af6..1e5e8dba5e 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/PasswordAuthenticationExpectTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/PasswordAuthenticationExpectTest.java @@ -54,9 +54,9 @@ public class PasswordAuthenticationExpectTest extends BaseNovaApiExpectTest { NovaApi apiWhenServersExist = requestsSendResponses(keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, listServers, listServersResponse); - assertEquals(apiWhenServersExist.getConfiguredZones(), ImmutableSet.of("az-1.region-a.geo-1")); + assertEquals(apiWhenServersExist.getConfiguredZones(), ImmutableSet.of("az-1.region-a.geo-1", "az-2.region-a.geo-1", "az-3.region-a.geo-1")); - assertEquals(apiWhenServersExist.getServerApiForZone("az-1.region-a.geo-1").listServers().toString(), + assertEquals(apiWhenServersExist.getServerApiForZone("az-1.region-a.geo-1").list().concat().toString(), new ParseServerListTest().expected().toString()); } diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/PasswordAuthenticationWithTenantNameExpectTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/PasswordAuthenticationWithTenantNameExpectTest.java index ad19ef2864..0e37d9d356 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/PasswordAuthenticationWithTenantNameExpectTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/PasswordAuthenticationWithTenantNameExpectTest.java @@ -63,9 +63,9 @@ public class PasswordAuthenticationWithTenantNameExpectTest extends BaseNovaApiE NovaApi apiWhenServersExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess, listServers, listServersResponse); - assertEquals(apiWhenServersExist.getConfiguredZones(), ImmutableSet.of("az-1.region-a.geo-1")); + assertEquals(apiWhenServersExist.getConfiguredZones(), ImmutableSet.of("az-1.region-a.geo-1", "az-2.region-a.geo-1", "az-3.region-a.geo-1")); - assertEquals(apiWhenServersExist.getServerApiForZone("az-1.region-a.geo-1").listServers().toString(), + assertEquals(apiWhenServersExist.getServerApiForZone("az-1.region-a.geo-1").list().concat().toString(), new ParseServerListTest().expected().toString()); } diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/compute/NovaComputeServiceAdapterExpectTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/compute/NovaComputeServiceAdapterExpectTest.java index 3b2e6f4a2d..d103060bfb 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/compute/NovaComputeServiceAdapterExpectTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/compute/NovaComputeServiceAdapterExpectTest.java @@ -22,6 +22,7 @@ import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import java.util.Map; +import java.util.Properties; import org.jclouds.compute.ComputeServiceAdapter.NodeAndInitialCredentials; import org.jclouds.compute.ComputeServiceContext; @@ -79,7 +80,7 @@ public class NovaComputeServiceAdapterExpectTest extends BaseNovaComputeServiceC Map requestResponseMap = ImmutableMap. builder() .put(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess) .put(extensionsOfNovaRequest, extensionsOfNovaResponse) - .put(listImagesDetail, listImagesDetailResponse) + .put(listDetail, listDetailResponse) .put(listFlavorsDetail, listFlavorsDetailResponse) .put(createServer, createServerResponse) .put(serverDetail, serverDetailResponse).build(); @@ -131,7 +132,7 @@ public class NovaComputeServiceAdapterExpectTest extends BaseNovaComputeServiceC Map requestResponseMap = ImmutableMap. builder() .put(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess) .put(extensionsOfNovaRequest, extensionsOfNovaResponse) - .put(listImagesDetail, listImagesDetailResponse) + .put(listDetail, listDetailResponse) .put(listFlavorsDetail, listFlavorsDetailResponse) .put(createServer, createServerResponse) .put(serverDetail, serverDetailResponse).build(); @@ -160,4 +161,12 @@ public class NovaComputeServiceAdapterExpectTest extends BaseNovaComputeServiceC public Injector apply(ComputeServiceContext input) { return input.utils().injector(); } + + @Override + protected Properties setupProperties() { + Properties overrides = super.setupProperties(); + // only specify one zone so that we don't have to configure requests for multiple zones + overrides.setProperty("jclouds.zones", "az-1.region-a.geo-1"); + return overrides; + } } diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/compute/NovaComputeServiceExpectTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/compute/NovaComputeServiceExpectTest.java index b29a11f371..94ae928f06 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/compute/NovaComputeServiceExpectTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/compute/NovaComputeServiceExpectTest.java @@ -26,6 +26,7 @@ import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import java.util.Map; +import java.util.Properties; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; @@ -52,12 +53,22 @@ import com.google.inject.TypeLiteral; */ @Test(groups = "unit", testName = "NovaComputeServiceExpectTest") public class NovaComputeServiceExpectTest extends BaseNovaComputeServiceExpectTest { - + + @Override + protected Properties setupProperties() { + Properties overrides = super.setupProperties(); + // only specify limited zones so that we don't have to configure requests for multiple zones. + // since we are doing tests with keystone responses from hpcloud and also trystack, we have + // to whitelist one zone from each + overrides.setProperty("jclouds.zones", "az-1.region-a.geo-1,RegionOne"); + return overrides; + } + public void testListLocationsWhenResponseIs2xx() throws Exception { Map requestResponseMap = ImmutableMap. builder() .put(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess) - .put(extensionsOfNovaRequest, extensionsOfNovaResponse).put(listImagesDetail, listImagesDetailResponse) + .put(extensionsOfNovaRequest, extensionsOfNovaResponse).put(listDetail, listDetailResponse) .put(listServers, listServersResponse).put(listFlavorsDetail, listFlavorsDetailResponse).build(); ComputeService apiWhenServersExist = requestsSendResponses(requestResponseMap); @@ -88,7 +99,7 @@ public class NovaComputeServiceExpectTest extends BaseNovaComputeServiceExpectTe .endpoint("https://nova-api.trystack.org:9774/v1.1/3456/extensions").build(), HttpResponse.builder().statusCode(200).payload(payloadFromResource("/extension_list_trystack.json")) .build()) - .put(listImagesDetail.toBuilder() + .put(listDetail.toBuilder() .endpoint("https://nova-api.trystack.org:9774/v1.1/3456/images/detail").build(), HttpResponse.builder().statusCode(200).payload(payloadFromResource("/image_list_detail_trystack.json")) .build()) @@ -135,7 +146,7 @@ public class NovaComputeServiceExpectTest extends BaseNovaComputeServiceExpectTe assertTrue(apiWhenNoServersExist.listNodes().isEmpty()); } - HttpRequest listSecurityGroups = HttpRequest + HttpRequest list = HttpRequest .builder() .method("GET") .endpoint("https://nova-api.trystack.org:9774/v1.1/3456/os-security-groups") @@ -144,7 +155,7 @@ public class NovaComputeServiceExpectTest extends BaseNovaComputeServiceExpectTe HttpResponse notFound = HttpResponse.builder().statusCode(404).build(); - HttpRequest createSecurityGroupWithPrefixOnGroup = HttpRequest + HttpRequest createWithPrefixOnGroup = HttpRequest .builder() .method("POST") .endpoint("https://nova-api.trystack.org:9774/v1.1/3456/os-security-groups") @@ -158,7 +169,7 @@ public class NovaComputeServiceExpectTest extends BaseNovaComputeServiceExpectTe HttpResponse securityGroupCreated = HttpResponse.builder().statusCode(200) .payload(payloadFromResource("/securitygroup_created.json")).build(); - HttpRequest createSecurityGroupRuleForDefaultPort22 = HttpRequest + HttpRequest createRuleForDefaultPort22 = HttpRequest .builder() .method("POST") .endpoint("https://nova-api.trystack.org:9774/v1.1/3456/os-security-group-rules") @@ -182,7 +193,7 @@ public class NovaComputeServiceExpectTest extends BaseNovaComputeServiceExpectTe HttpResponse securityGroupWithPort22 = HttpResponse.builder().statusCode(200) .payload(payloadFromResource("/securitygroup_details_port22.json")).build(); - HttpRequest createKeyPair = HttpRequest + HttpRequest create = HttpRequest .builder() .method("POST") .endpoint("https://nova-api.trystack.org:9774/v1.1/3456/os-keypairs") @@ -210,15 +221,15 @@ public class NovaComputeServiceExpectTest extends BaseNovaComputeServiceExpectTe public void testCreateNodeWithGeneratedKeyPair() throws Exception { Builder requestResponseMap = ImmutableMap. builder() .putAll(defaultTemplateTryStack); - requestResponseMap.put(listSecurityGroups, notFound); + requestResponseMap.put(list, notFound); - requestResponseMap.put(createSecurityGroupWithPrefixOnGroup, securityGroupCreated); + requestResponseMap.put(createWithPrefixOnGroup, securityGroupCreated); - requestResponseMap.put(createSecurityGroupRuleForDefaultPort22, securityGroupRuleCreated); + requestResponseMap.put(createRuleForDefaultPort22, securityGroupRuleCreated); requestResponseMap.put(getSecurityGroup, securityGroupWithPort22); - requestResponseMap.put(createKeyPair, keyPairWithPrivateKey); + requestResponseMap.put(create, keyPairWithPrivateKey); requestResponseMap.put(serverDetail, serverDetailResponse); @@ -266,11 +277,11 @@ public class NovaComputeServiceExpectTest extends BaseNovaComputeServiceExpectTe public void testCreateNodeWhileUserSpecifiesKeyPair() throws Exception { Builder requestResponseMap = ImmutableMap. builder() .putAll(defaultTemplateTryStack); - requestResponseMap.put(listSecurityGroups, notFound); + requestResponseMap.put(list, notFound); - requestResponseMap.put(createSecurityGroupWithPrefixOnGroup, securityGroupCreated); + requestResponseMap.put(createWithPrefixOnGroup, securityGroupCreated); - requestResponseMap.put(createSecurityGroupRuleForDefaultPort22, securityGroupRuleCreated); + requestResponseMap.put(createRuleForDefaultPort22, securityGroupRuleCreated); requestResponseMap.put(getSecurityGroup, securityGroupWithPort22); @@ -316,4 +327,5 @@ public class NovaComputeServiceExpectTest extends BaseNovaComputeServiceExpectTe // we don't have access to this private key assertEquals(node.getCredentials().getPrivateKey(), null); } + } diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/compute/functions/AllocateAndAddFloatingIpToNodeExpectTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/compute/functions/AllocateAndAddFloatingIpToNodeExpectTest.java index ebd632b13d..97f763de2d 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/compute/functions/AllocateAndAddFloatingIpToNodeExpectTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/compute/functions/AllocateAndAddFloatingIpToNodeExpectTest.java @@ -57,7 +57,7 @@ public class AllocateAndAddFloatingIpToNodeExpectTest extends BaseNovaComputeSer host).name("Server 71592").status(Status.RUNNING).privateAddresses(ImmutableSet.of("10.4.27.237")) .credentials(LoginCredentials.builder().password("foo").build()).build(); - HttpRequest allocateFloatingIP = HttpRequest.builder().method("POST").endpoint( + HttpRequest createFloatingIP = HttpRequest.builder().method("POST").endpoint( URI.create("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/os-floating-ips")).headers( ImmutableMultimap. builder().put("Accept", "application/json").put("X-Auth-Token", authToken).build()).payload(payloadFromStringWithContentType("{}", "application/json")).build(); @@ -65,7 +65,7 @@ public class AllocateAndAddFloatingIpToNodeExpectTest extends BaseNovaComputeSer HttpResponse addFloatingIPResponse = HttpResponse.builder().statusCode(200).build(); public void testAllocateWhenAllocationReturnsIpIsAddedToServerAndUpdatesNodeMetadataButSavesCredentials() throws Exception { - HttpResponse allocateFloatingIPResponse = HttpResponse.builder().statusCode(200).payload( + HttpResponse createFloatingIPResponse = HttpResponse.builder().statusCode(200).payload( payloadFromResource("/floatingip_details.json")).build(); HttpRequest addFloatingIPRequest = addFloatingIPForAddress("10.0.0.3"); @@ -73,7 +73,7 @@ public class AllocateAndAddFloatingIpToNodeExpectTest extends BaseNovaComputeSer AllocateAndAddFloatingIpToNode fn = requestsSendResponses( ImmutableMap. builder().put(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess).put(extensionsOfNovaRequest, extensionsOfNovaResponse).put( - allocateFloatingIP, allocateFloatingIPResponse) + createFloatingIP, createFloatingIPResponse) .put(addFloatingIPRequest, addFloatingIPResponse).build()).getContext().utils().injector() .getInstance(AllocateAndAddFloatingIpToNode.class); @@ -98,20 +98,20 @@ public class AllocateAndAddFloatingIpToNodeExpectTest extends BaseNovaComputeSer } public void testAllocateWhenAllocationFailsLookupUnusedIpAddToServerAndUpdatesNodeMetadata() throws Exception { - HttpResponse allocateFloatingIPResponse = HttpResponse + HttpResponse createFloatingIPResponse = HttpResponse .builder() .statusCode(400) .payload( payloadFromStringWithContentType( - "{\"badRequest\": {\"message\": \"AddressLimitExceeded: Address quota exceeded. You cannot allocate any more addresses\", \"code\": 400}}", + "{\"badRequest\": {\"message\": \"AddressLimitExceeded: Address quota exceeded. You cannot create any more addresses\", \"code\": 400}}", "application/json")).build(); - HttpRequest listFloatingIPs = HttpRequest.builder().method("GET").endpoint( + HttpRequest list = HttpRequest.builder().method("GET").endpoint( URI.create("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/os-floating-ips")).headers( ImmutableMultimap. builder().put("Accept", "application/json").put("X-Auth-Token", authToken).build()).build(); - HttpResponse listFloatingIPsResponseForUnassigned = HttpResponse.builder().statusCode(200).payload( + HttpResponse listResponseForUnassigned = HttpResponse.builder().statusCode(200).payload( payloadFromResource("/floatingip_list.json")).build(); HttpRequest addFloatingIPRequest = addFloatingIPForAddress("10.0.0.5"); @@ -119,9 +119,9 @@ public class AllocateAndAddFloatingIpToNodeExpectTest extends BaseNovaComputeSer AllocateAndAddFloatingIpToNode fn = requestsSendResponses( ImmutableMap. builder().put(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess).put(extensionsOfNovaRequest, extensionsOfNovaResponse).put( - allocateFloatingIP, allocateFloatingIPResponse) - .put(addFloatingIPRequest, addFloatingIPResponse).put(listFloatingIPs, - listFloatingIPsResponseForUnassigned).build()).getContext().utils().injector() + createFloatingIP, createFloatingIPResponse) + .put(addFloatingIPRequest, addFloatingIPResponse).put(list, + listResponseForUnassigned).build()).getContext().utils().injector() .getInstance(AllocateAndAddFloatingIpToNode.class); AtomicReference nodeRef = new AtomicReference(node); diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/compute/loaders/CreateUniqueKeyPairTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/compute/loaders/CreateUniqueKeyPairTest.java index c2de758b67..b7552a392a 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/compute/loaders/CreateUniqueKeyPairTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/compute/loaders/CreateUniqueKeyPairTest.java @@ -56,7 +56,7 @@ public class CreateUniqueKeyPairTest { expect(api.getKeyPairExtensionForZone("zone")).andReturn(optKeyApi).atLeastOnce(); - expect(keyApi.createKeyPair("group-1")).andReturn(pair); + expect(keyApi.create("group-1")).andReturn(pair); replay(api, keyApi); @@ -88,9 +88,9 @@ public class CreateUniqueKeyPairTest { expect(api.getKeyPairExtensionForZone("zone")).andReturn((Optional) Optional.of(keyApi)).atLeastOnce(); expect(uniqueIdSupplier.get()).andReturn("1"); - expect(keyApi.createKeyPair("group-1")).andThrow(new IllegalStateException()); + expect(keyApi.create("group-1")).andThrow(new IllegalStateException()); expect(uniqueIdSupplier.get()).andReturn("2"); - expect(keyApi.createKeyPair("group-2")).andReturn(pair); + expect(keyApi.create("group-2")).andReturn(pair); replay(api, keyApi, uniqueIdSupplier); diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/compute/loaders/LoadFloatingIpsForInstanceTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/compute/loaders/LoadFloatingIpsForInstanceTest.java index 291d89ecbb..f4afb77b63 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/compute/loaders/LoadFloatingIpsForInstanceTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/compute/loaders/LoadFloatingIpsForInstanceTest.java @@ -34,6 +34,7 @@ import org.jclouds.openstack.nova.v2_0.extensions.FloatingIPApi; import org.testng.annotations.Test; import com.google.common.base.Optional; +import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableSet; /** @@ -49,7 +50,8 @@ public class LoadFloatingIpsForInstanceTest { FloatingIP testIp = FloatingIP.builder().id("1").ip("1.1.1.1").fixedIp("10.1.1.1").instanceId("i-blah").build(); expect(api.getFloatingIPExtensionForZone("Zone")).andReturn((Optional) Optional.of(ipApi)).atLeastOnce(); - expect(ipApi.listFloatingIPs()).andReturn((Set) ImmutableSet.of(testIp)).atLeastOnce(); + expect(ipApi.list()).andReturn((FluentIterable) FluentIterable.from(ImmutableSet. of(testIp))) + .atLeastOnce(); replay(api); replay(ipApi); @@ -69,7 +71,8 @@ public class LoadFloatingIpsForInstanceTest { expect(api.getFloatingIPExtensionForZone("Zone")).andReturn((Optional) Optional.of(ipApi)).atLeastOnce(); - expect(ipApi.listFloatingIPs()).andReturn((Set) ImmutableSet.of()).atLeastOnce(); + expect(ipApi.list()).andReturn((FluentIterable) FluentIterable.from(ImmutableSet. of())) + .atLeastOnce(); replay(api); replay(ipApi); @@ -90,9 +93,8 @@ public class LoadFloatingIpsForInstanceTest { expect(api.getFloatingIPExtensionForZone("Zone")).andReturn((Optional) Optional.of(ipApi)).atLeastOnce(); - expect(ipApi.listFloatingIPs()).andReturn( - (Set) ImmutableSet.of(FloatingIP.builder().id("1").ip("1.1.1.1").build())) - .atLeastOnce(); + expect(ipApi.list()).andReturn((FluentIterable) FluentIterable.from(ImmutableSet. of(FloatingIP.builder().id("1").ip("1.1.1.1").build()))) + .atLeastOnce(); replay(api); replay(ipApi); diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/compute/predicates/GetImageWhenImageInZoneHasActiveStatusPredicateWithResultExpectTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/compute/predicates/GetImageWhenImageInZoneHasActiveStatusPredicateWithResultExpectTest.java index 8be5dd21a1..f9da95ef1a 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/compute/predicates/GetImageWhenImageInZoneHasActiveStatusPredicateWithResultExpectTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/compute/predicates/GetImageWhenImageInZoneHasActiveStatusPredicateWithResultExpectTest.java @@ -45,12 +45,12 @@ import com.google.inject.Injector; public class GetImageWhenImageInZoneHasActiveStatusPredicateWithResultExpectTest extends BaseNovaComputeServiceContextExpectTest { - private final HttpResponse listImagesDetailImageExtensionResponse = HttpResponse.builder().statusCode(200) + private final HttpResponse listDetailImageExtensionResponse = HttpResponse.builder().statusCode(200) .payload(payloadFromResource("/image_list_detail_imageextension.json")).build(); private Map requestResponseMap = ImmutableMap. builder() .put(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess) - .put(listImagesDetail, listImagesDetailImageExtensionResponse).build(); + .put(listDetail, listDetailImageExtensionResponse).build(); public void testReturnsFalseOnImageStatusSavingAndTrueOnActive() { Injector injector = requestsSendResponses(requestResponseMap); diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/AdminActionsApiExpectTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/AdminActionsApiExpectTest.java index 6980ab1613..e2906f77d7 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/AdminActionsApiExpectTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/AdminActionsApiExpectTest.java @@ -47,298 +47,298 @@ public class AdminActionsApiExpectTest extends BaseNovaApiExpectTest { public void testSuspend() { URI endpoint = URI.create("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/servers/1/action"); - AdminActionsApi api = requestsSendResponses( + ServerAdminApi api = requestsSendResponses( keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, standardActionRequestBuilderVoidResponse(endpoint, "suspend").build(), HttpResponse.builder().statusCode(202).build() - ).getAdminActionsExtensionForZone("az-1.region-a.geo-1").get(); + ).getServerAdminExtensionForZone("az-1.region-a.geo-1").get(); - assertTrue(api.suspendServer("1")); + assertTrue(api.suspend("1")); } public void testSuspendFailsNotFound() { URI endpoint = URI.create("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/servers/1/action"); - AdminActionsApi api = requestsSendResponses( + ServerAdminApi api = requestsSendResponses( keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, standardActionRequestBuilderVoidResponse(endpoint, "suspend").build(), HttpResponse.builder().statusCode(404).build() - ).getAdminActionsExtensionForZone("az-1.region-a.geo-1").get(); + ).getServerAdminExtensionForZone("az-1.region-a.geo-1").get(); - assertFalse(api.suspendServer("1")); + assertFalse(api.suspend("1")); } @Test(expectedExceptions = AuthorizationException.class) public void testSuspendFailsNotAuthorized() { URI endpoint = URI.create("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/servers/1/action"); - AdminActionsApi api = requestsSendResponses( + ServerAdminApi api = requestsSendResponses( keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, standardActionRequestBuilderVoidResponse(endpoint, "suspend").build(), HttpResponse.builder().statusCode(403).build() - ).getAdminActionsExtensionForZone("az-1.region-a.geo-1").get(); + ).getServerAdminExtensionForZone("az-1.region-a.geo-1").get(); - api.suspendServer("1"); + api.suspend("1"); } public void testResume() { URI endpoint = URI.create("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/servers/1/action"); - AdminActionsApi api = requestsSendResponses( + ServerAdminApi api = requestsSendResponses( keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, standardActionRequestBuilderVoidResponse(endpoint, "resume").build(), HttpResponse.builder().statusCode(202).build() - ).getAdminActionsExtensionForZone("az-1.region-a.geo-1").get(); + ).getServerAdminExtensionForZone("az-1.region-a.geo-1").get(); - assertTrue(api.resumeServer("1")); + assertTrue(api.resume("1")); } public void testResumeFailsNotFound() { URI endpoint = URI.create("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/servers/1/action"); - AdminActionsApi api = requestsSendResponses( + ServerAdminApi api = requestsSendResponses( keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, standardActionRequestBuilderVoidResponse(endpoint, "resume").build(), HttpResponse.builder().statusCode(404).build() - ).getAdminActionsExtensionForZone("az-1.region-a.geo-1").get(); + ).getServerAdminExtensionForZone("az-1.region-a.geo-1").get(); - assertFalse(api.resumeServer("1")); + assertFalse(api.resume("1")); } @Test(expectedExceptions = AuthorizationException.class) public void testResumeFailsNotAuthorized() { URI endpoint = URI.create("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/servers/1/action"); - AdminActionsApi api = requestsSendResponses( + ServerAdminApi api = requestsSendResponses( keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, standardActionRequestBuilderVoidResponse(endpoint, "resume").build(), HttpResponse.builder().statusCode(403).build() - ).getAdminActionsExtensionForZone("az-1.region-a.geo-1").get(); + ).getServerAdminExtensionForZone("az-1.region-a.geo-1").get(); - api.resumeServer("1"); + api.resume("1"); } public void testLock() { URI endpoint = URI.create("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/servers/1/action"); - AdminActionsApi api = requestsSendResponses( + ServerAdminApi api = requestsSendResponses( keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, standardActionRequestBuilderVoidResponse(endpoint, "lock").build(), HttpResponse.builder().statusCode(202).build() - ).getAdminActionsExtensionForZone("az-1.region-a.geo-1").get(); + ).getServerAdminExtensionForZone("az-1.region-a.geo-1").get(); - assertTrue(api.lockServer("1")); + assertTrue(api.lock("1")); } public void testLockFailsNotFound() { URI endpoint = URI.create("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/servers/1/action"); - AdminActionsApi api = requestsSendResponses( + ServerAdminApi api = requestsSendResponses( keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, standardActionRequestBuilderVoidResponse(endpoint, "lock").build(), HttpResponse.builder().statusCode(404).build() - ).getAdminActionsExtensionForZone("az-1.region-a.geo-1").get(); + ).getServerAdminExtensionForZone("az-1.region-a.geo-1").get(); - assertFalse(api.lockServer("1")); + assertFalse(api.lock("1")); } public void testUnlock() { URI endpoint = URI.create("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/servers/1/action"); - AdminActionsApi api = requestsSendResponses( + ServerAdminApi api = requestsSendResponses( keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, standardActionRequestBuilderVoidResponse(endpoint, "unlock").build(), HttpResponse.builder().statusCode(202).build() - ).getAdminActionsExtensionForZone("az-1.region-a.geo-1").get(); + ).getServerAdminExtensionForZone("az-1.region-a.geo-1").get(); - assertTrue(api.unlockServer("1")); + assertTrue(api.unlock("1")); } public void testUnlockFailsNotFound() { URI endpoint = URI.create("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/servers/1/action"); - AdminActionsApi api = requestsSendResponses( + ServerAdminApi api = requestsSendResponses( keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, standardActionRequestBuilderVoidResponse(endpoint, "unlock").build(), HttpResponse.builder().statusCode(404).build() - ).getAdminActionsExtensionForZone("az-1.region-a.geo-1").get(); + ).getServerAdminExtensionForZone("az-1.region-a.geo-1").get(); - assertFalse(api.unlockServer("1")); + assertFalse(api.unlock("1")); } public void testPause() { URI endpoint = URI.create("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/servers/1/action"); - AdminActionsApi api = requestsSendResponses( + ServerAdminApi api = requestsSendResponses( keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, standardActionRequestBuilderVoidResponse(endpoint, "pause").build(), HttpResponse.builder().statusCode(202).build() - ).getAdminActionsExtensionForZone("az-1.region-a.geo-1").get(); + ).getServerAdminExtensionForZone("az-1.region-a.geo-1").get(); - assertTrue(api.pauseServer("1")); + assertTrue(api.pause("1")); } public void testPauseFailsNotFound() { URI endpoint = URI.create("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/servers/1/action"); - AdminActionsApi api = requestsSendResponses( + ServerAdminApi api = requestsSendResponses( keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, standardActionRequestBuilderVoidResponse(endpoint, "pause").build(), HttpResponse.builder().statusCode(404).build() - ).getAdminActionsExtensionForZone("az-1.region-a.geo-1").get(); + ).getServerAdminExtensionForZone("az-1.region-a.geo-1").get(); - assertFalse(api.pauseServer("1")); + assertFalse(api.pause("1")); } public void testUnpause() { URI endpoint = URI.create("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/servers/1/action"); - AdminActionsApi api = requestsSendResponses( + ServerAdminApi api = requestsSendResponses( keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, standardActionRequestBuilderVoidResponse(endpoint, "unpause").build(), HttpResponse.builder().statusCode(202).build() - ).getAdminActionsExtensionForZone("az-1.region-a.geo-1").get(); + ).getServerAdminExtensionForZone("az-1.region-a.geo-1").get(); - assertTrue(api.unpauseServer("1")); + assertTrue(api.unpause("1")); } public void testUnpauseFailsNotFound() { URI endpoint = URI.create("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/servers/1/action"); - AdminActionsApi api = requestsSendResponses( + ServerAdminApi api = requestsSendResponses( keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, standardActionRequestBuilderVoidResponse(endpoint, "unpause").build(), HttpResponse.builder().statusCode(404).build() - ).getAdminActionsExtensionForZone("az-1.region-a.geo-1").get(); + ).getServerAdminExtensionForZone("az-1.region-a.geo-1").get(); - assertFalse(api.unpauseServer("1")); + assertFalse(api.unpause("1")); } public void testMigrateServer() { URI endpoint = URI.create("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/servers/1/action"); - AdminActionsApi api = requestsSendResponses( + ServerAdminApi api = requestsSendResponses( keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, standardActionRequestBuilderVoidResponse(endpoint, "migrate").build(), HttpResponse.builder().statusCode(202).build() - ).getAdminActionsExtensionForZone("az-1.region-a.geo-1").get(); + ).getServerAdminExtensionForZone("az-1.region-a.geo-1").get(); - assertTrue(api.migrateServer("1")); + assertTrue(api.migrate("1")); } public void testMigrateServerFailsNotFound() { URI endpoint = URI.create("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/servers/1/action"); - AdminActionsApi api = requestsSendResponses( + ServerAdminApi api = requestsSendResponses( keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, standardActionRequestBuilderVoidResponse(endpoint, "migrate").build(), HttpResponse.builder().statusCode(404).build() - ).getAdminActionsExtensionForZone("az-1.region-a.geo-1").get(); + ).getServerAdminExtensionForZone("az-1.region-a.geo-1").get(); - assertFalse(api.migrateServer("1")); + assertFalse(api.migrate("1")); } public void testResetNetworkOfServer() { URI endpoint = URI.create("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/servers/1/action"); - AdminActionsApi api = requestsSendResponses( + ServerAdminApi api = requestsSendResponses( keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, standardActionRequestBuilderVoidResponse(endpoint, "resetNetwork").build(), HttpResponse.builder().statusCode(202).build() - ).getAdminActionsExtensionForZone("az-1.region-a.geo-1").get(); + ).getServerAdminExtensionForZone("az-1.region-a.geo-1").get(); - assertTrue(api.resetNetworkOfServer("1")); + assertTrue(api.resetNetwork("1")); } public void testResetNetworkOfServerFailsNotFound() { URI endpoint = URI.create("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/servers/1/action"); - AdminActionsApi api = requestsSendResponses( + ServerAdminApi api = requestsSendResponses( keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, standardActionRequestBuilderVoidResponse(endpoint, "resetNetwork").build(), HttpResponse.builder().statusCode(404).build() - ).getAdminActionsExtensionForZone("az-1.region-a.geo-1").get(); + ).getServerAdminExtensionForZone("az-1.region-a.geo-1").get(); - assertFalse(api.resetNetworkOfServer("1")); + assertFalse(api.resetNetwork("1")); } public void testInjectNetworkInfoIntoServer() { URI endpoint = URI.create("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/servers/1/action"); - AdminActionsApi api = requestsSendResponses( + ServerAdminApi api = requestsSendResponses( keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, standardActionRequestBuilderVoidResponse(endpoint, "injectNetworkInfo").build(), HttpResponse.builder().statusCode(202).build() - ).getAdminActionsExtensionForZone("az-1.region-a.geo-1").get(); + ).getServerAdminExtensionForZone("az-1.region-a.geo-1").get(); - assertTrue(api.injectNetworkInfoIntoServer("1")); + assertTrue(api.injectNetworkInfo("1")); } public void testInjectNetworkInfoIntoServerFailsNotFound() { URI endpoint = URI.create("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/servers/1/action"); - AdminActionsApi api = requestsSendResponses( + ServerAdminApi api = requestsSendResponses( keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, standardActionRequestBuilderVoidResponse(endpoint, "injectNetworkInfo").build(), HttpResponse.builder().statusCode(404).build() - ).getAdminActionsExtensionForZone("az-1.region-a.geo-1").get(); + ).getServerAdminExtensionForZone("az-1.region-a.geo-1").get(); - assertFalse(api.injectNetworkInfoIntoServer("1")); + assertFalse(api.injectNetworkInfo("1")); } public void testBackupServer() { - AdminActionsApi api = requestsSendResponses( + ServerAdminApi api = requestsSendResponses( keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, authenticatedGET().endpoint("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/servers/1/action").method("POST") .payload(payloadFromStringWithContentType("{\"createBackup\":{\"backup_type\":\"weekly\",\"rotation\":3,\"name\":\"mybackup\",\"metadata\":{\"some\":\"data or other\"}}}", MediaType.APPLICATION_JSON)).build(), HttpResponse.builder().statusCode(202).addHeader("Location", "http://172.16.89.149:8774/v2/images/1976b3b3-409a-468d-b16c-a9172c341b46").build() - ).getAdminActionsExtensionForZone("az-1.region-a.geo-1").get(); + ).getServerAdminExtensionForZone("az-1.region-a.geo-1").get(); - String imageId = api.createBackupOfServer("1", "mybackup", BackupType.WEEKLY, 3, CreateBackupOfServerOptions.Builder.metadata(ImmutableMap.of("some", "data or other"))); + String imageId = api.createBackup("1", "mybackup", BackupType.WEEKLY, 3, CreateBackupOfServerOptions.Builder.metadata(ImmutableMap.of("some", "data or other"))); assertEquals(imageId, "1976b3b3-409a-468d-b16c-a9172c341b46"); } @Test(expectedExceptions = ResourceNotFoundException.class) public void testBackupServerFailNotFound() { URI endpoint = URI.create("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/servers/1/action"); - AdminActionsApi api = requestsSendResponses( + ServerAdminApi api = requestsSendResponses( keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, authenticatedGET().endpoint(endpoint).method("POST") .payload(payloadFromStringWithContentType("{\"createBackup\":{\"backup_type\":\"weekly\",\"rotation\":3,\"name\":\"mybackup\",\"metadata\":{\"some\":\"data or other\"}}}", MediaType.APPLICATION_JSON)).build(), HttpResponse.builder().statusCode(404).build() - ).getAdminActionsExtensionForZone("az-1.region-a.geo-1").get(); + ).getServerAdminExtensionForZone("az-1.region-a.geo-1").get(); - api.createBackupOfServer("1", "mybackup", BackupType.WEEKLY, 3, CreateBackupOfServerOptions.Builder.metadata(ImmutableMap.of("some", "data or other"))); + api.createBackup("1", "mybackup", BackupType.WEEKLY, 3, CreateBackupOfServerOptions.Builder.metadata(ImmutableMap.of("some", "data or other"))); } public void testLiveMigrateServer() { URI endpoint = URI.create("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/servers/1/action"); - AdminActionsApi api = requestsSendResponses( + ServerAdminApi api = requestsSendResponses( keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, standardActionRequestBuilderVoidResponse(endpoint, "GONNAOVERWRITE") .payload(payloadFromStringWithContentType("{\"os-migrateLive\":{\"host\":\"bighost\",\"block_migration\":true,\"disk_over_commit\":false}}", MediaType.APPLICATION_JSON)).build(), HttpResponse.builder().statusCode(202).build() - ).getAdminActionsExtensionForZone("az-1.region-a.geo-1").get(); + ).getServerAdminExtensionForZone("az-1.region-a.geo-1").get(); - assertTrue(api.liveMigrateServer("1", "bighost", true, false)); + assertTrue(api.liveMigrate("1", "bighost", true, false)); } public void testLiveMigrateServerFailsNotFound() { URI endpoint = URI.create("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/servers/1/action"); - AdminActionsApi api = requestsSendResponses( + ServerAdminApi api = requestsSendResponses( keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, standardActionRequestBuilderVoidResponse(endpoint, "GONNAOVERWRITE") .payload(payloadFromStringWithContentType("{\"os-migrateLive\":{\"host\":\"bighost\",\"block_migration\":true,\"disk_over_commit\":false}}", MediaType.APPLICATION_JSON)).build(), HttpResponse.builder().statusCode(404).build() - ).getAdminActionsExtensionForZone("az-1.region-a.geo-1").get(); + ).getServerAdminExtensionForZone("az-1.region-a.geo-1").get(); - assertFalse(api.liveMigrateServer("1", "bighost", true, false)); + assertFalse(api.liveMigrate("1", "bighost", true, false)); } protected HttpRequest.Builder standardActionRequestBuilderVoidResponse(URI endpoint, String actionName) { diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/AdminActionsApiLiveTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/AdminActionsApiLiveTest.java index ae1bc4a33d..40312f4891 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/AdminActionsApiLiveTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/AdminActionsApiLiveTest.java @@ -32,9 +32,10 @@ import org.jclouds.openstack.nova.v2_0.features.ServerApi; import org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiLiveTest; import org.jclouds.openstack.nova.v2_0.options.CreateBackupOfServerOptions; import org.jclouds.openstack.v2_0.features.ExtensionApi; -import org.testng.annotations.AfterGroups; +import org.testng.SkipException; +import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeGroups; +import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.google.common.base.Optional; @@ -45,7 +46,7 @@ import com.google.common.collect.Iterables; * Tests behavior of HostAdministrationApi * * TODO test migration methods - * + * * @author Adam Lowe */ @Test(groups = "live", testName = "AdminActionsApiLiveTest", singleThreaded = true) @@ -53,13 +54,13 @@ public class AdminActionsApiLiveTest extends BaseNovaApiLiveTest { private ImageApi imageApi; private ServerApi serverApi; private ExtensionApi extensionApi; - private Optional apiOption; + private Optional apiOption; private String zone; private String testServerId; private String backupImageId; - @BeforeGroups(groups = {"integration", "live"}) + @BeforeClass(groups = {"integration", "live"}) @Override public void setupContext() { super.setupContext(); @@ -67,125 +68,130 @@ public class AdminActionsApiLiveTest extends BaseNovaApiLiveTest { serverApi = novaContext.getApi().getServerApiForZone(zone); extensionApi = novaContext.getApi().getExtensionApiForZone(zone); imageApi = novaContext.getApi().getImageApiForZone(zone); - apiOption = novaContext.getApi().getAdminActionsExtensionForZone(zone); + apiOption = novaContext.getApi().getServerAdminExtensionForZone(zone); if (apiOption.isPresent()) { testServerId = createServerInZone(zone).getId(); } } - @AfterGroups(groups = "live", alwaysRun = true) + @AfterClass(groups = { "integration", "live" }) @Override - protected void tearDown() { + protected void tearDownContext() { if (apiOption.isPresent()) { if (testServerId != null) { - assertTrue(novaContext.getApi().getServerApiForZone(zone).deleteServer(testServerId)); + assertTrue(novaContext.getApi().getServerApiForZone(zone).delete(testServerId)); } if (backupImageId != null) { - imageApi.deleteImage(backupImageId); + imageApi.delete(backupImageId); } } - super.tearDown(); + super.tearDownContext(); + } + + protected void skipOnAdminExtensionAbsent() { + if (!apiOption.isPresent()) { + throw new SkipException("Test depends on ServerAdminApi extension"); + } } @AfterMethod(alwaysRun = true) public void ensureServerIsActiveAgain() { - blockUntilServerInState(testServerId, serverApi, Status.ACTIVE); - } - - public void testSuspendAndResume() { - if (apiOption.isPresent()) { - AdminActionsApi api = apiOption.get(); - - // Suspend-resume - try { - api.resumeServer(testServerId); - fail("Resumed an active server!"); - } catch (HttpResponseException e) { - } - assertTrue(api.suspendServer(testServerId)); - blockUntilServerInState(testServerId, serverApi, Status.SUSPENDED); - try { - api.suspendServer(testServerId); - fail("Suspended an already suspended server!"); - } catch (HttpResponseException e) { - } - assertTrue(api.resumeServer(testServerId)); + if (apiOption.isPresent()) blockUntilServerInState(testServerId, serverApi, Status.ACTIVE); - try { - api.resumeServer(testServerId); - fail("Resumed an already resumed server!"); - } catch (HttpResponseException e) { - } + } + + public void testSuspendAndResume() { + skipOnAdminExtensionAbsent(); + ServerAdminApi api = apiOption.get(); + + // Suspend-resume + try { + api.resume(testServerId); + fail("Resumed an active server!"); + } catch (HttpResponseException e) { } + assertTrue(api.suspend(testServerId)); + blockUntilServerInState(testServerId, serverApi, Status.SUSPENDED); + try { + api.suspend(testServerId); + fail("Suspended an already suspended server!"); + } catch (HttpResponseException e) { + } + assertTrue(api.resume(testServerId)); + blockUntilServerInState(testServerId, serverApi, Status.ACTIVE); + try { + api.resume(testServerId); + fail("Resumed an already resumed server!"); + } catch (HttpResponseException e) { + } + } public void testLockAndUnlock() { - if (apiOption.isPresent()) { - AdminActionsApi api = apiOption.get(); + skipOnAdminExtensionAbsent(); + ServerAdminApi api = apiOption.get(); + + // TODO should we be able to double-lock (as it were) + assertTrue(api.unlock(testServerId)); + assertTrue(api.unlock(testServerId)); + assertTrue(api.lock(testServerId)); + assertTrue(api.lock(testServerId)); + assertTrue(api.unlock(testServerId)); + assertTrue(api.unlock(testServerId)); - // TODO should we be able to double-lock (as it were) - assertTrue(api.unlockServer(testServerId)); - assertTrue(api.unlockServer(testServerId)); - assertTrue(api.lockServer(testServerId)); - assertTrue(api.lockServer(testServerId)); - assertTrue(api.unlockServer(testServerId)); - assertTrue(api.unlockServer(testServerId)); - } } public void testResetNetworkAndInjectNetworkInfo() { - if (apiOption.isPresent()) { - AdminActionsApi api = apiOption.get(); - assertTrue(api.resetNetworkOfServer(testServerId)); - assertTrue(api.injectNetworkInfoIntoServer(testServerId)); - } + skipOnAdminExtensionAbsent(); + ServerAdminApi api = apiOption.get(); + assertTrue(api.resetNetwork(testServerId)); + assertTrue(api.injectNetworkInfo(testServerId)); } @Test public void testPauseAndUnpause() { - if (apiOption.isPresent()) { - AdminActionsApi api = apiOption.get(); + skipOnAdminExtensionAbsent(); + ServerAdminApi api = apiOption.get(); - // Unlock and lock (double-checking error contitions too) - try { - api.unpauseServer(testServerId); - fail("Unpaused active server!"); - } catch (HttpResponseException e) { - } - assertTrue(api.pauseServer(testServerId)); - blockUntilServerInState(testServerId, serverApi, Status.PAUSED); - try { - api.pauseServer(testServerId); - fail("paused a paused server!"); - } catch (HttpResponseException e) { - } - assertTrue(api.unpauseServer(testServerId)); - blockUntilServerInState(testServerId, serverApi, Status.ACTIVE); - try { - api.unpauseServer(testServerId); - fail("Unpaused a server we just unpaused!"); - } catch (HttpResponseException e) { - } + // Unlock and lock (double-checking error contitions too) + try { + api.unpause(testServerId); + fail("Unpaused active server!"); + } catch (HttpResponseException e) { } + assertTrue(api.pause(testServerId)); + blockUntilServerInState(testServerId, serverApi, Status.PAUSED); + try { + api.pause(testServerId); + fail("paused a paused server!"); + } catch (HttpResponseException e) { + } + assertTrue(api.unpause(testServerId)); + blockUntilServerInState(testServerId, serverApi, Status.ACTIVE); + try { + api.unpause(testServerId); + fail("Unpaused a server we just unpaused!"); + } catch (HttpResponseException e) { + } + } @Test public void testCreateBackupOfServer() throws InterruptedException { - if (apiOption.isPresent()) { - backupImageId = apiOption.get().createBackupOfServer(testServerId, "jclouds-test-backup", BackupType.DAILY, 0, + skipOnAdminExtensionAbsent(); + backupImageId = apiOption.get().createBackup(testServerId, "jclouds-test-backup", BackupType.DAILY, 0, CreateBackupOfServerOptions.Builder.metadata(ImmutableMap.of("test", "metadata"))); - assertNotNull(backupImageId); - - // If we don't have extended task status, we'll have to wait here! - if (extensionApi.getExtensionByAlias("OS-EXT-STS") == null) { - Thread.sleep(30000); - } - - blockUntilServerInState(testServerId, serverApi, Status.ACTIVE); - - Image backupImage = imageApi.getImage(backupImageId); - assertEquals(backupImage.getId(), backupImageId); + assertNotNull(backupImageId); + + // If we don't have extended task status, we'll have to wait here! + if (extensionApi.get("OS-EXT-STS") == null) { + Thread.sleep(30000); } - } + + blockUntilServerInState(testServerId, serverApi, Status.ACTIVE); + + Image backupImage = imageApi.get(backupImageId); + assertEquals(backupImage.getId(), backupImageId); + } } diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/FlavorExtraSpecsApiExpectTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/FlavorExtraSpecsApiExpectTest.java index f483ece6dc..3832a39f08 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/FlavorExtraSpecsApiExpectTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/FlavorExtraSpecsApiExpectTest.java @@ -50,7 +50,7 @@ public class FlavorExtraSpecsApiExpectTest extends BaseNovaApiExpectTest { HttpResponse.builder().statusCode(200).payload(payloadFromResource("/volume_type_extra_specs.json")).build() ).getFlavorExtraSpecsExtensionForZone("az-1.region-a.geo-1").get(); - assertEquals(api.getAllExtraSpecs("9"), ImmutableMap.of("test", "value1")); + assertEquals(api.getMetadata("9"), ImmutableMap.of("test", "value1")); } public void testGetAllExtraSpecsFailNotFound() { @@ -62,7 +62,7 @@ public class FlavorExtraSpecsApiExpectTest extends BaseNovaApiExpectTest { HttpResponse.builder().statusCode(404).build() ).getFlavorExtraSpecsExtensionForZone("az-1.region-a.geo-1").get(); - assertTrue(api.getAllExtraSpecs("9").isEmpty()); + assertTrue(api.getMetadata("9").isEmpty()); } public void testSetAllExtraSpecs() { @@ -76,7 +76,7 @@ public class FlavorExtraSpecsApiExpectTest extends BaseNovaApiExpectTest { HttpResponse.builder().statusCode(200).build() ).getFlavorExtraSpecsExtensionForZone("az-1.region-a.geo-1").get(); - assertTrue(api.setAllExtraSpecs("9", ImmutableMap.of("test1", "somevalue"))); + assertTrue(api.updateMetadata("9", ImmutableMap.of("test1", "somevalue"))); } public void testSetExtraSpec() { @@ -90,7 +90,7 @@ public class FlavorExtraSpecsApiExpectTest extends BaseNovaApiExpectTest { HttpResponse.builder().statusCode(200).build() ).getFlavorExtraSpecsExtensionForZone("az-1.region-a.geo-1").get(); - assertTrue(api.setExtraSpec("5", "test1", "somevalue")); + assertTrue(api.updateMetadataEntry("5", "test1", "somevalue")); } public void testGetExtraSpec() { @@ -102,7 +102,7 @@ public class FlavorExtraSpecsApiExpectTest extends BaseNovaApiExpectTest { HttpResponse.builder().statusCode(200).payload(payloadFromStringWithContentType("{\"test1\":\"another value\"}", MediaType.APPLICATION_JSON)).build() ).getFlavorExtraSpecsExtensionForZone("az-1.region-a.geo-1").get(); - assertEquals(api.getExtraSpec("5", "test1"), "another value"); + assertEquals(api.getMetadataKey("5", "test1"), "another value"); } public void testGetExtraSpecFailNotFound() { @@ -114,7 +114,7 @@ public class FlavorExtraSpecsApiExpectTest extends BaseNovaApiExpectTest { HttpResponse.builder().statusCode(404).build() ).getFlavorExtraSpecsExtensionForZone("az-1.region-a.geo-1").get(); - assertNull(api.getExtraSpec("5", "test1")); + assertNull(api.getMetadataKey("5", "test1")); } public void testDeleteExtraSpec() { @@ -126,7 +126,7 @@ public class FlavorExtraSpecsApiExpectTest extends BaseNovaApiExpectTest { HttpResponse.builder().statusCode(200).build() ).getFlavorExtraSpecsExtensionForZone("az-1.region-a.geo-1").get(); - assertTrue(api.deleteExtraSpec("5", "test1")); + assertTrue(api.deleteMetadataKey("5", "test1")); } public void testDeleteExtraSpecFailNotFound() { @@ -138,7 +138,7 @@ public class FlavorExtraSpecsApiExpectTest extends BaseNovaApiExpectTest { HttpResponse.builder().statusCode(404).build() ).getFlavorExtraSpecsExtensionForZone("az-1.region-a.geo-1").get(); - assertFalse(api.deleteExtraSpec("5", "test1")); + assertFalse(api.deleteMetadataKey("5", "test1")); } } diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/FlavorExtraSpecsApiLiveTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/FlavorExtraSpecsApiLiveTest.java index a666aafa45..0b24f84d39 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/FlavorExtraSpecsApiLiveTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/FlavorExtraSpecsApiLiveTest.java @@ -27,8 +27,8 @@ import java.util.Map; import org.jclouds.openstack.nova.v2_0.features.FlavorApi; import org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiLiveTest; import org.jclouds.openstack.v2_0.domain.Resource; -import org.testng.annotations.AfterGroups; -import org.testng.annotations.BeforeGroups; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.google.common.base.Optional; @@ -50,7 +50,7 @@ public class FlavorExtraSpecsApiLiveTest extends BaseNovaApiLiveTest { private Resource testFlavor; private Map testSpecs = ImmutableMap.of("jclouds-test", "some data", "jclouds-test2", "more data!"); - @BeforeGroups(groups = { "integration", "live" }) + @BeforeClass(groups = {"integration", "live"}) @Override public void setupContext() { super.setupContext(); @@ -59,29 +59,29 @@ public class FlavorExtraSpecsApiLiveTest extends BaseNovaApiLiveTest { apiOption = novaContext.getApi().getFlavorExtraSpecsExtensionForZone(zone); } - @AfterGroups(groups = "live") + @AfterClass(groups = { "integration", "live" }) @Override - public void tearDown() { + protected void tearDownContext() { if (apiOption.isPresent() && testFlavor != null) { for(String key : testSpecs.keySet()) { - assertTrue(apiOption.get().deleteExtraSpec(testFlavor.getId(), key)); + assertTrue(apiOption.get().deleteMetadataKey(testFlavor.getId(), key)); } } - super.tearDown(); + super.tearDownContext(); } public void testCreateExtraSpecs() { if (apiOption.isPresent()) { FlavorExtraSpecsApi api = apiOption.get(); - testFlavor = Iterables.getLast(flavorApi.listFlavors()); - Map before = api.getAllExtraSpecs(testFlavor.getId()); + testFlavor = Iterables.getLast(flavorApi.list().concat()); + Map before = api.getMetadata(testFlavor.getId()); assertNotNull(before); Map specs = Maps.newHashMap(before); specs.putAll(testSpecs); - assertTrue(api.setAllExtraSpecs(testFlavor.getId(), specs)); - assertEquals(api.getAllExtraSpecs(testFlavor.getId()), specs); + assertTrue(api.updateMetadata(testFlavor.getId(), specs)); + assertEquals(api.getMetadata(testFlavor.getId()), specs); for (Map.Entry entry : specs.entrySet()) { - assertEquals(api.getExtraSpec(testFlavor.getId(), entry.getKey()), entry.getValue()); + assertEquals(api.getMetadataKey(testFlavor.getId(), entry.getKey()), entry.getValue()); } } } @@ -91,13 +91,13 @@ public class FlavorExtraSpecsApiLiveTest extends BaseNovaApiLiveTest { if (apiOption.isPresent()) { FlavorExtraSpecsApi api = apiOption.get(); for (String key : testSpecs.keySet()) { - assertTrue(api.getAllExtraSpecs(testFlavor.getId()).containsKey(key)); + assertTrue(api.getMetadata(testFlavor.getId()).containsKey(key)); } - for (Resource flavor : flavorApi.listFlavors()) { - Map specs = api.getAllExtraSpecs(flavor.getId()); + for (Resource flavor : flavorApi.list().concat()) { + Map specs = api.getMetadata(flavor.getId()); assertNotNull(specs); for (Map.Entry entry : specs.entrySet()) { - assertEquals(api.getExtraSpec(flavor.getId(), entry.getKey()), entry.getValue()); + assertEquals(api.getMetadataKey(flavor.getId(), entry.getKey()), entry.getValue()); } } } @@ -108,16 +108,16 @@ public class FlavorExtraSpecsApiLiveTest extends BaseNovaApiLiveTest { if (apiOption.isPresent()) { FlavorExtraSpecsApi api = apiOption.get(); for (String key : testSpecs.keySet()) { - assertTrue(api.setExtraSpec(testFlavor.getId(), key, "new value")); + assertTrue(api.updateMetadataEntry(testFlavor.getId(), key, "new value")); } for (String key : testSpecs.keySet()) { - assertEquals(api.getExtraSpec(testFlavor.getId(), key), "new value"); + assertEquals(api.getMetadataKey(testFlavor.getId(), key), "new value"); } - for (Resource flavor : flavorApi.listFlavors()) { - Map specs = api.getAllExtraSpecs(flavor.getId()); + for (Resource flavor : flavorApi.list().concat()) { + Map specs = api.getMetadata(flavor.getId()); assertNotNull(specs); for (Map.Entry entry : specs.entrySet()) { - assertEquals(api.getExtraSpec(flavor.getId(), entry.getKey()), entry.getValue()); + assertEquals(api.getMetadataKey(flavor.getId(), entry.getKey()), entry.getValue()); } } } diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/FloatingIPApiExpectTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/FloatingIPApiExpectTest.java index af71ea1acf..9f3369fd84 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/FloatingIPApiExpectTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/FloatingIPApiExpectTest.java @@ -45,7 +45,7 @@ public class FloatingIPApiExpectTest extends BaseNovaApiExpectTest { NovaApi apiWhenExtensionNotInList = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse); - assertEquals(apiWhenExtensionNotInList.getConfiguredZones(), ImmutableSet.of("az-1.region-a.geo-1")); + assertEquals(apiWhenExtensionNotInList.getConfiguredZones(), ImmutableSet.of("az-1.region-a.geo-1", "az-2.region-a.geo-1", "az-3.region-a.geo-1")); assertTrue(apiWhenExtensionNotInList.getFloatingIPExtensionForZone("az-1.region-a.geo-1").isPresent()); @@ -56,84 +56,84 @@ public class FloatingIPApiExpectTest extends BaseNovaApiExpectTest { NovaApi apiWhenExtensionNotInList = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess, extensionsOfNovaRequest, unmatchedExtensionsOfNovaResponse); - assertEquals(apiWhenExtensionNotInList.getConfiguredZones(), ImmutableSet.of("az-1.region-a.geo-1")); + assertEquals(apiWhenExtensionNotInList.getConfiguredZones(), ImmutableSet.of("az-1.region-a.geo-1", "az-2.region-a.geo-1", "az-3.region-a.geo-1")); assertFalse(apiWhenExtensionNotInList.getFloatingIPExtensionForZone("az-1.region-a.geo-1").isPresent()); } public void testListFloatingIPsWhenResponseIs2xx() throws Exception { - HttpRequest listFloatingIPs = HttpRequest + HttpRequest list = HttpRequest .builder() .method("GET") .endpoint("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/os-floating-ips") .addHeader("Accept", "application/json") .addHeader("X-Auth-Token", authToken).build(); - HttpResponse listFloatingIPsResponse = HttpResponse.builder().statusCode(200) + HttpResponse listResponse = HttpResponse.builder().statusCode(200) .payload(payloadFromResource("/floatingip_list.json")).build(); NovaApi apiWhenFloatingIPsExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, - responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, listFloatingIPs, listFloatingIPsResponse); + responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, list, listResponse); - assertEquals(apiWhenFloatingIPsExist.getConfiguredZones(), ImmutableSet.of("az-1.region-a.geo-1")); + assertEquals(apiWhenFloatingIPsExist.getConfiguredZones(), ImmutableSet.of("az-1.region-a.geo-1", "az-2.region-a.geo-1", "az-3.region-a.geo-1")); - assertEquals(apiWhenFloatingIPsExist.getFloatingIPExtensionForZone("az-1.region-a.geo-1").get().listFloatingIPs() + assertEquals(apiWhenFloatingIPsExist.getFloatingIPExtensionForZone("az-1.region-a.geo-1").get().list() .toString(), new ParseFloatingIPListTest().expected().toString()); } public void testListFloatingIPsWhenResponseIs404() throws Exception { - HttpRequest listFloatingIPs = HttpRequest + HttpRequest list = HttpRequest .builder() .method("GET") .endpoint("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/os-floating-ips") .addHeader("Accept", "application/json") .addHeader("X-Auth-Token", authToken).build(); - HttpResponse listFloatingIPsResponse = HttpResponse.builder().statusCode(404).build(); + HttpResponse listResponse = HttpResponse.builder().statusCode(404).build(); NovaApi apiWhenNoServersExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, - responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, listFloatingIPs, listFloatingIPsResponse); + responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, list, listResponse); - assertTrue(apiWhenNoServersExist.getFloatingIPExtensionForZone("az-1.region-a.geo-1").get().listFloatingIPs().isEmpty()); + assertTrue(apiWhenNoServersExist.getFloatingIPExtensionForZone("az-1.region-a.geo-1").get().list().isEmpty()); } public void testGetFloatingIPWhenResponseIs2xx() throws Exception { - HttpRequest getFloatingIP = HttpRequest + HttpRequest get = HttpRequest .builder() .method("GET") .endpoint("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/os-floating-ips/1") .addHeader("Accept", "application/json") .addHeader("X-Auth-Token", authToken).build(); - HttpResponse getFloatingIPResponse = HttpResponse.builder().statusCode(200) + HttpResponse getResponse = HttpResponse.builder().statusCode(200) .payload(payloadFromResource("/floatingip_details.json")).build(); NovaApi apiWhenFloatingIPsExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, - responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, getFloatingIP, getFloatingIPResponse); + responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, get, getResponse); - assertEquals(apiWhenFloatingIPsExist.getFloatingIPExtensionForZone("az-1.region-a.geo-1").get().getFloatingIP("1") + assertEquals(apiWhenFloatingIPsExist.getFloatingIPExtensionForZone("az-1.region-a.geo-1").get().get("1") .toString(), new ParseFloatingIPTest().expected().toString()); } public void testGetFloatingIPWhenResponseIs404() throws Exception { - HttpRequest getFloatingIP = HttpRequest + HttpRequest get = HttpRequest .builder() .method("GET") .endpoint("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/os-floating-ips/1") .addHeader("Accept", "application/json") .addHeader("X-Auth-Token", authToken).build(); - HttpResponse getFloatingIPResponse = HttpResponse.builder().statusCode(404).build(); + HttpResponse getResponse = HttpResponse.builder().statusCode(404).build(); NovaApi apiWhenNoServersExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, - responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, getFloatingIP, getFloatingIPResponse); + responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, get, getResponse); - assertNull(apiWhenNoServersExist.getFloatingIPExtensionForZone("az-1.region-a.geo-1").get().getFloatingIP("1")); + assertNull(apiWhenNoServersExist.getFloatingIPExtensionForZone("az-1.region-a.geo-1").get().get("1")); } public void testAllocateWhenResponseIs2xx() throws Exception { - HttpRequest allocateFloatingIP = HttpRequest + HttpRequest createFloatingIP = HttpRequest .builder() .method("POST") .endpoint("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/os-floating-ips") @@ -141,20 +141,20 @@ public class FloatingIPApiExpectTest extends BaseNovaApiExpectTest { .addHeader("X-Auth-Token", authToken) .payload(payloadFromStringWithContentType("{}", "application/json")).build(); - HttpResponse allocateFloatingIPResponse = HttpResponse.builder().statusCode(200) + HttpResponse createFloatingIPResponse = HttpResponse.builder().statusCode(200) .payload(payloadFromResource("/floatingip_details.json")).build(); NovaApi apiWhenFloatingIPsExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, - responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, allocateFloatingIP, - allocateFloatingIPResponse); + responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, createFloatingIP, + createFloatingIPResponse); - assertEquals(apiWhenFloatingIPsExist.getFloatingIPExtensionForZone("az-1.region-a.geo-1").get().allocate().toString(), + assertEquals(apiWhenFloatingIPsExist.getFloatingIPExtensionForZone("az-1.region-a.geo-1").get().create().toString(), new ParseFloatingIPTest().expected().toString()); } public void testAllocateWhenResponseIs404() throws Exception { - HttpRequest allocateFloatingIP = HttpRequest + HttpRequest createFloatingIP = HttpRequest .builder() .method("POST") .endpoint("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/os-floating-ips") @@ -162,13 +162,13 @@ public class FloatingIPApiExpectTest extends BaseNovaApiExpectTest { .addHeader("X-Auth-Token", authToken) .payload(payloadFromStringWithContentType("{}", "application/json")).build(); - HttpResponse allocateFloatingIPResponse = HttpResponse.builder().statusCode(404).build(); + HttpResponse createFloatingIPResponse = HttpResponse.builder().statusCode(404).build(); NovaApi apiWhenNoServersExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, - responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, allocateFloatingIP, - allocateFloatingIPResponse); + responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, createFloatingIP, + createFloatingIPResponse); - assertNull(apiWhenNoServersExist.getFloatingIPExtensionForZone("az-1.region-a.geo-1").get().allocate()); + assertNull(apiWhenNoServersExist.getFloatingIPExtensionForZone("az-1.region-a.geo-1").get().create()); } } diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/FloatingIPApiLiveTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/FloatingIPApiLiveTest.java index a35aaabb9b..164be4fdbc 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/FloatingIPApiLiveTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/FloatingIPApiLiveTest.java @@ -52,11 +52,11 @@ public class FloatingIPApiLiveTest extends BaseNovaApiLiveTest { if (!apiOption.isPresent()) continue; FloatingIPApi api = apiOption.get(); - Set response = api.listFloatingIPs(); + Set response = api.list().toImmutableSet(); assert null != response; assertTrue(response.size() >= 0); for (FloatingIP ip : response) { - FloatingIP newDetails = api.getFloatingIP(ip.getId()); + FloatingIP newDetails = api.get(ip.getId()); assertEquals(newDetails.getId(), ip.getId()); assertEquals(newDetails.getIp(), ip.getIp()); @@ -68,16 +68,16 @@ public class FloatingIPApiLiveTest extends BaseNovaApiLiveTest { } @Test - public void testAllocateAndDeallocateFloatingIPs() throws Exception { + public void testAllocateAndDecreateFloatingIPs() throws Exception { for (String zoneId : novaContext.getApi().getConfiguredZones()) { Optional apiOption = novaContext.getApi().getFloatingIPExtensionForZone(zoneId); if (!apiOption.isPresent()) continue; FloatingIPApi api = apiOption.get(); - FloatingIP floatingIP = api.allocate(); + FloatingIP floatingIP = api.create(); assertNotNull(floatingIP); - Set response = api.listFloatingIPs(); + Set response = api.list().toImmutableSet(); boolean ipInSet = false; for (FloatingIP ip : response) { if (ip.getId().equals(floatingIP.getId())) @@ -85,9 +85,9 @@ public class FloatingIPApiLiveTest extends BaseNovaApiLiveTest { } assertTrue(ipInSet); - api.deallocate(floatingIP.getId()); + api.delete(floatingIP.getId()); - response = api.listFloatingIPs(); + response = api.list().toImmutableSet(); ipInSet = false; for (FloatingIP ip : response) { if (ip.getId().equals(floatingIP.getId())) { @@ -107,14 +107,14 @@ public class FloatingIPApiLiveTest extends BaseNovaApiLiveTest { FloatingIPApi api = apiOption.get(); ServerApi serverApi = novaContext.getApi().getServerApiForZone(zoneId); Server server = createServerInZone(zoneId); - FloatingIP floatingIP = api.allocate(); + FloatingIP floatingIP = api.create(); assertNotNull(floatingIP); try { - api.addFloatingIPToServer(floatingIP.getIp(), server.getId()); + api.addToServer(floatingIP.getIp(), server.getId()); assertEventually(new ServerHasFloatingIP(serverApi, server.getId(), floatingIP.getIp())); } finally { - api.removeFloatingIPFromServer(floatingIP.getIp(), server.getId()); - serverApi.deleteServer(server.getId()); + api.removeFromServer(floatingIP.getIp(), server.getId()); + serverApi.delete(server.getId()); } } } @@ -155,7 +155,7 @@ public class FloatingIPApiLiveTest extends BaseNovaApiLiveTest { public void run() { try { - Server server = api.getServer(serverId); + Server server = api.get(serverId); boolean ipInServerAddresses = false; Multimap addresses = server.getAddresses(); for (Address address : addresses.values()) { diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/FloatingIPAsyncApiExpectTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/FloatingIPAsyncApiExpectTest.java index 32f1506771..4e14b20c1b 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/FloatingIPAsyncApiExpectTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/FloatingIPAsyncApiExpectTest.java @@ -46,7 +46,7 @@ public class FloatingIPAsyncApiExpectTest extends BaseNovaAsyncApiExpectTest { NovaAsyncApi apiWhenExtensionNotInList = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse); - assertEquals(apiWhenExtensionNotInList.getConfiguredZones(), ImmutableSet.of("az-1.region-a.geo-1")); + assertEquals(apiWhenExtensionNotInList.getConfiguredZones(), ImmutableSet.of("az-1.region-a.geo-1", "az-2.region-a.geo-1", "az-3.region-a.geo-1")); assertTrue(apiWhenExtensionNotInList.getFloatingIPExtensionForZone("az-1.region-a.geo-1").isPresent()); @@ -57,85 +57,85 @@ public class FloatingIPAsyncApiExpectTest extends BaseNovaAsyncApiExpectTest { NovaAsyncApi apiWhenExtensionNotInList = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess, extensionsOfNovaRequest, unmatchedExtensionsOfNovaResponse); - assertEquals(apiWhenExtensionNotInList.getConfiguredZones(), ImmutableSet.of("az-1.region-a.geo-1")); + assertEquals(apiWhenExtensionNotInList.getConfiguredZones(), ImmutableSet.of("az-1.region-a.geo-1", "az-2.region-a.geo-1", "az-3.region-a.geo-1")); assertFalse(apiWhenExtensionNotInList.getFloatingIPExtensionForZone("az-1.region-a.geo-1").isPresent()); } public void testListFloatingIPsWhenResponseIs2xx() throws Exception { - HttpRequest listFloatingIPs = HttpRequest + HttpRequest list = HttpRequest .builder() .method("GET") .endpoint("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/os-floating-ips") .addHeader("Accept", "application/json") .addHeader("X-Auth-Token", authToken).build(); - HttpResponse listFloatingIPsResponse = HttpResponse.builder().statusCode(200) + HttpResponse listResponse = HttpResponse.builder().statusCode(200) .payload(payloadFromResource("/floatingip_list.json")).build(); NovaAsyncApi apiWhenFloatingIPsExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, - responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, listFloatingIPs, listFloatingIPsResponse); + responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, list, listResponse); - assertEquals(apiWhenFloatingIPsExist.getConfiguredZones(), ImmutableSet.of("az-1.region-a.geo-1")); + assertEquals(apiWhenFloatingIPsExist.getConfiguredZones(), ImmutableSet.of("az-1.region-a.geo-1", "az-2.region-a.geo-1", "az-3.region-a.geo-1")); - assertEquals(apiWhenFloatingIPsExist.getFloatingIPExtensionForZone("az-1.region-a.geo-1").get().listFloatingIPs().get() + assertEquals(apiWhenFloatingIPsExist.getFloatingIPExtensionForZone("az-1.region-a.geo-1").get().list().get() .toString(), new ParseFloatingIPListTest().expected().toString()); } public void testListFloatingIPsWhenResponseIs404() throws Exception { - HttpRequest listFloatingIPs = HttpRequest + HttpRequest list = HttpRequest .builder() .method("GET") .endpoint("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/os-floating-ips") .addHeader("Accept", "application/json") .addHeader("X-Auth-Token", authToken).build(); - HttpResponse listFloatingIPsResponse = HttpResponse.builder().statusCode(404).build(); + HttpResponse listResponse = HttpResponse.builder().statusCode(404).build(); NovaAsyncApi apiWhenNoServersExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, - responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, listFloatingIPs, listFloatingIPsResponse); + responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, list, listResponse); - assertTrue(apiWhenNoServersExist.getFloatingIPExtensionForZone("az-1.region-a.geo-1").get().listFloatingIPs().get() + assertTrue(apiWhenNoServersExist.getFloatingIPExtensionForZone("az-1.region-a.geo-1").get().list().get() .isEmpty()); } public void testGetFloatingIPWhenResponseIs2xx() throws Exception { - HttpRequest getFloatingIP = HttpRequest + HttpRequest get = HttpRequest .builder() .method("GET") .endpoint("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/os-floating-ips/1") .addHeader("Accept", "application/json") .addHeader("X-Auth-Token", authToken).build(); - HttpResponse getFloatingIPResponse = HttpResponse.builder().statusCode(200) + HttpResponse getResponse = HttpResponse.builder().statusCode(200) .payload(payloadFromResource("/floatingip_details.json")).build(); NovaAsyncApi apiWhenFloatingIPsExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, - responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, getFloatingIP, getFloatingIPResponse); + responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, get, getResponse); - assertEquals(apiWhenFloatingIPsExist.getFloatingIPExtensionForZone("az-1.region-a.geo-1").get().getFloatingIP("1").get() + assertEquals(apiWhenFloatingIPsExist.getFloatingIPExtensionForZone("az-1.region-a.geo-1").get().get("1").get() .toString(), new ParseFloatingIPTest().expected().toString()); } public void testGetFloatingIPWhenResponseIs404() throws Exception { - HttpRequest getFloatingIP = HttpRequest + HttpRequest get = HttpRequest .builder() .method("GET") .endpoint("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/os-floating-ips/1") .addHeader("Accept", "application/json") .addHeader("X-Auth-Token", authToken).build(); - HttpResponse getFloatingIPResponse = HttpResponse.builder().statusCode(404).build(); + HttpResponse getResponse = HttpResponse.builder().statusCode(404).build(); NovaAsyncApi apiWhenNoServersExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, - responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, getFloatingIP, getFloatingIPResponse); + responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, get, getResponse); - assertNull(apiWhenNoServersExist.getFloatingIPExtensionForZone("az-1.region-a.geo-1").get().getFloatingIP("1").get()); + assertNull(apiWhenNoServersExist.getFloatingIPExtensionForZone("az-1.region-a.geo-1").get().get("1").get()); } public void testAllocateWhenResponseIs2xx() throws Exception { - HttpRequest allocateFloatingIP = HttpRequest + HttpRequest createFloatingIP = HttpRequest .builder() .method("POST") .endpoint("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/os-floating-ips") @@ -143,20 +143,20 @@ public class FloatingIPAsyncApiExpectTest extends BaseNovaAsyncApiExpectTest { .addHeader("X-Auth-Token", authToken) .payload(payloadFromStringWithContentType("{}", "application/json")).build(); - HttpResponse allocateFloatingIPResponse = HttpResponse.builder().statusCode(200) + HttpResponse createFloatingIPResponse = HttpResponse.builder().statusCode(200) .payload(payloadFromResource("/floatingip_details.json")).build(); NovaAsyncApi apiWhenFloatingIPsExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, - responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, allocateFloatingIP, - allocateFloatingIPResponse); + responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, createFloatingIP, + createFloatingIPResponse); - assertEquals(apiWhenFloatingIPsExist.getFloatingIPExtensionForZone("az-1.region-a.geo-1").get().allocate().get() + assertEquals(apiWhenFloatingIPsExist.getFloatingIPExtensionForZone("az-1.region-a.geo-1").get().create().get() .toString(), new ParseFloatingIPTest().expected().toString()); } public void testAllocateWhenResponseIs404() throws Exception { - HttpRequest allocateFloatingIP = HttpRequest + HttpRequest createFloatingIP = HttpRequest .builder() .method("POST") .endpoint("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/os-floating-ips") @@ -164,13 +164,13 @@ public class FloatingIPAsyncApiExpectTest extends BaseNovaAsyncApiExpectTest { .addHeader("X-Auth-Token", authToken) .payload(payloadFromStringWithContentType("{}", "application/json")).build(); - HttpResponse allocateFloatingIPResponse = HttpResponse.builder().statusCode(404).build(); + HttpResponse createFloatingIPResponse = HttpResponse.builder().statusCode(404).build(); NovaAsyncApi apiWhenNoServersExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, - responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, allocateFloatingIP, - allocateFloatingIPResponse); + responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, createFloatingIP, + createFloatingIPResponse); - assertNull(apiWhenNoServersExist.getFloatingIPExtensionForZone("az-1.region-a.geo-1").get().allocate().get()); + assertNull(apiWhenNoServersExist.getFloatingIPExtensionForZone("az-1.region-a.geo-1").get().create().get()); } } diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/HostAdministrationApiExpectTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/HostAdministrationApiExpectTest.java index b824552ec8..f280603328 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/HostAdministrationApiExpectTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/HostAdministrationApiExpectTest.java @@ -59,7 +59,7 @@ public class HostAdministrationApiExpectTest extends BaseNovaApiExpectTest { Host expected = Host.builder().name("ubuntu").service("compute").build(); - Set result = api.listHosts(); + Set result = api.list().toImmutableSet(); Host host = Iterables.getOnlyElement(result); assertEquals(host.getName(), "ubuntu"); assertEquals(host.getService(), "compute"); @@ -84,7 +84,7 @@ public class HostAdministrationApiExpectTest extends BaseNovaApiExpectTest { HostResourceUsage.builder().memoryMb(6144).project("f8535069c3fb404cb61c873b1a0b4921").cpu(3).diskGb(80).host("ubuntu").build() ); - assertEquals(api.getHostResourceUsage("xyz"), expected); + assertEquals(api.listResourceUsage("xyz").toImmutableSet(), expected); } public void testEnableHost() { @@ -99,7 +99,7 @@ public class HostAdministrationApiExpectTest extends BaseNovaApiExpectTest { HttpResponse.builder().statusCode(200) .payload(payloadFromStringWithContentType("{\"host\":\"ubuntu\",\"status\":\"enabled\"}", MediaType.APPLICATION_JSON)) .build()).getHostAdministrationExtensionForZone("az-1.region-a.geo-1").get(); - assertTrue(api.enableHost("ubuntu")); + assertTrue(api.enable("ubuntu")); } @Test(expectedExceptions = ResourceNotFoundException.class) @@ -114,7 +114,7 @@ public class HostAdministrationApiExpectTest extends BaseNovaApiExpectTest { .endpoint(endpoint).build(), HttpResponse.builder().statusCode(404) .build()).getHostAdministrationExtensionForZone("az-1.region-a.geo-1").get(); - api.enableHost("ubuntu"); + api.enable("ubuntu"); } public void testEnableHostFailNotEnabled() { @@ -129,7 +129,7 @@ public class HostAdministrationApiExpectTest extends BaseNovaApiExpectTest { HttpResponse.builder().statusCode(200) .payload(payloadFromStringWithContentType("{\"host\":\"ubuntu\",\"status\":\"disabled\"}", MediaType.APPLICATION_JSON)) .build()).getHostAdministrationExtensionForZone("az-1.region-a.geo-1").get(); - assertFalse(api.enableHost("ubuntu")); + assertFalse(api.enable("ubuntu")); } public void testDisableHost() { @@ -144,7 +144,7 @@ public class HostAdministrationApiExpectTest extends BaseNovaApiExpectTest { HttpResponse.builder().statusCode(200) .payload(payloadFromStringWithContentType("{\"host\":\"ubuntu\",\"status\":\"disabled\"}", MediaType.APPLICATION_JSON)) .build()).getHostAdministrationExtensionForZone("az-1.region-a.geo-1").get(); - assertTrue(api.disableHost("ubuntu")); + assertTrue(api.disable("ubuntu")); } public void testStartMaintenance() { @@ -159,7 +159,7 @@ public class HostAdministrationApiExpectTest extends BaseNovaApiExpectTest { HttpResponse.builder().statusCode(200) .payload(payloadFromStringWithContentType("{\"host\":\"ubuntu\",\"maintenance_mode\":\"on_maintenance\"}", MediaType.APPLICATION_JSON)) .build()).getHostAdministrationExtensionForZone("az-1.region-a.geo-1").get(); - assertTrue(api.startHostMaintenance("ubuntu")); + assertTrue(api.startMaintenance("ubuntu")); } public void testStopMaintenance() { @@ -174,7 +174,7 @@ public class HostAdministrationApiExpectTest extends BaseNovaApiExpectTest { HttpResponse.builder().statusCode(200) .payload(payloadFromStringWithContentType("{\"host\":\"ubuntu\",\"maintenance_mode\":\"off_maintenance\"}", MediaType.APPLICATION_JSON)) .build()).getHostAdministrationExtensionForZone("az-1.region-a.geo-1").get(); - assertTrue(api.stopHostMaintenance("ubuntu")); + assertTrue(api.stopMaintenance("ubuntu")); } public void testStartupHost() { @@ -187,7 +187,7 @@ public class HostAdministrationApiExpectTest extends BaseNovaApiExpectTest { HttpResponse.builder().statusCode(200) .payload(payloadFromStringWithContentType("{\"host\":\"ubuntu\",\"power_action\":\"startup\"}", MediaType.APPLICATION_JSON)) .build()).getHostAdministrationExtensionForZone("az-1.region-a.geo-1").get(); - assertTrue(api.startupHost("ubuntu")); + assertTrue(api.startup("ubuntu")); } @Test(expectedExceptions = ResourceNotFoundException.class) @@ -199,7 +199,7 @@ public class HostAdministrationApiExpectTest extends BaseNovaApiExpectTest { .addHeader("Accept", "application/json") .addHeader("X-Auth-Token", authToken).build(), HttpResponse.builder().statusCode(404).build()).getHostAdministrationExtensionForZone("az-1.region-a.geo-1").get(); - assertTrue(api.startupHost("ubuntu")); + assertTrue(api.startup("ubuntu")); } public void testStartupHostFailWrongActionInProgress() { @@ -212,7 +212,7 @@ public class HostAdministrationApiExpectTest extends BaseNovaApiExpectTest { HttpResponse.builder().statusCode(200) .payload(payloadFromStringWithContentType("{\"host\":\"ubuntu\",\"power_action\":\"shutdown\"}", MediaType.APPLICATION_JSON)) .build()).getHostAdministrationExtensionForZone("az-1.region-a.geo-1").get(); - assertFalse(api.startupHost("ubuntu")); + assertFalse(api.startup("ubuntu")); } public void testShutdownHost() { @@ -225,7 +225,7 @@ public class HostAdministrationApiExpectTest extends BaseNovaApiExpectTest { HttpResponse.builder().statusCode(200) .payload(payloadFromStringWithContentType("{\"host\":\"ubuntu\",\"power_action\":\"shutdown\"}", MediaType.APPLICATION_JSON)) .build()).getHostAdministrationExtensionForZone("az-1.region-a.geo-1").get(); - assertTrue(api.shutdownHost("ubuntu")); + assertTrue(api.shutdown("ubuntu")); } public void testRebootHost() { @@ -238,6 +238,6 @@ public class HostAdministrationApiExpectTest extends BaseNovaApiExpectTest { HttpResponse.builder().statusCode(200) .payload(payloadFromStringWithContentType("{\"host\":\"ubuntu\",\"power_action\":\"reboot\"}", MediaType.APPLICATION_JSON)) .build()).getHostAdministrationExtensionForZone("az-1.region-a.geo-1").get(); - assertTrue(api.rebootHost("ubuntu")); + assertTrue(api.reboot("ubuntu")); } } diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/HostAdministrationApiLiveTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/HostAdministrationApiLiveTest.java index 20ce931b8e..d9f0fe8c4d 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/HostAdministrationApiLiveTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/HostAdministrationApiLiveTest.java @@ -65,10 +65,10 @@ public class HostAdministrationApiLiveTest extends BaseNovaApiLiveTest { public void testListAndGet() throws Exception { if (optApi.isPresent()) { HostAdministrationApi api = optApi.get(); - Set hosts = api.listHosts(); + Set hosts = api.list().toImmutableSet(); assertNotNull(hosts); for (Host host : hosts) { - for (HostResourceUsage usage : api.getHostResourceUsage(host.getName())) { + for (HostResourceUsage usage : api.listResourceUsage(host.getName())) { assertEquals(usage.getHost(), host.getName()); assertNotNull(usage); } @@ -80,10 +80,10 @@ public class HostAdministrationApiLiveTest extends BaseNovaApiLiveTest { public void testEnableDisable() throws Exception { if (optApi.isPresent()) { HostAdministrationApi api = optApi.get(); - Host host = Iterables.find(api.listHosts(), isComputeHost); + Host host = Iterables.find(api.list(), isComputeHost); - assertTrue(api.disableHost(host.getName())); - assertTrue(api.enableHost(host.getName())); + assertTrue(api.disable(host.getName())); + assertTrue(api.enable(host.getName())); } } @@ -91,9 +91,9 @@ public class HostAdministrationApiLiveTest extends BaseNovaApiLiveTest { public void testMaintenanceMode() throws Exception { if (optApi.isPresent()) { HostAdministrationApi api = optApi.get(); - Host host = Iterables.find(api.listHosts(), isComputeHost); - assertTrue(api.startHostMaintenance(host.getName())); - assertTrue(api.stopHostMaintenance(host.getName())); + Host host = Iterables.find(api.list(), isComputeHost); + assertTrue(api.startMaintenance(host.getName())); + assertTrue(api.stopMaintenance(host.getName())); } } @@ -101,8 +101,8 @@ public class HostAdministrationApiLiveTest extends BaseNovaApiLiveTest { public void testReboot() throws Exception { if (optApi.isPresent()) { HostAdministrationApi api = optApi.get(); - Host host = Iterables.find(api.listHosts(), isComputeHost); - assertTrue(api.rebootHost(host.getName())); + Host host = Iterables.find(api.list(), isComputeHost); + assertTrue(api.reboot(host.getName())); } } @@ -110,9 +110,9 @@ public class HostAdministrationApiLiveTest extends BaseNovaApiLiveTest { public void testShutdownAndStartup() throws Exception { if (optApi.isPresent()) { HostAdministrationApi api = optApi.get(); - Host host = Iterables.find(api.listHosts(), isComputeHost); - assertTrue(api.shutdownHost(host.getName())); - assertTrue(api.startupHost(host.getName())); + Host host = Iterables.find(api.list(), isComputeHost); + assertTrue(api.shutdown(host.getName())); + assertTrue(api.startup(host.getName())); } } } diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/HostAggregateApiExpectTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/HostAggregateApiExpectTest.java index 55997fb309..f84c934b1f 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/HostAggregateApiExpectTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/HostAggregateApiExpectTest.java @@ -54,7 +54,7 @@ public class HostAggregateApiExpectTest extends BaseNovaApiExpectTest { HttpResponse.builder().statusCode(200).payload(payloadFromResource("/host_aggregate_list.json")).build()) .getHostAggregateExtensionForZone("az-1.region-a.geo-1").get(); - HostAggregate result = Iterables.getOnlyElement(api.listAggregates()); + HostAggregate result = Iterables.getOnlyElement(api.list()); assertEquals(result, exampleHostAggregate()); } @@ -66,7 +66,7 @@ public class HostAggregateApiExpectTest extends BaseNovaApiExpectTest { HttpResponse.builder().statusCode(200).payload(payloadFromResource("/host_aggregate_with_host_details.json")).build()) .getHostAggregateExtensionForZone("az-1.region-a.geo-1").get(); - assertEquals(api.getAggregate("1"), exampleHostAggregateWithHost()); + assertEquals(api.get("1"), exampleHostAggregateWithHost()); } public void testGetFailNotFound() { @@ -76,7 +76,7 @@ public class HostAggregateApiExpectTest extends BaseNovaApiExpectTest { authenticatedGET().endpoint(endpoint).build(), HttpResponse.builder().statusCode(404).build()).getHostAggregateExtensionForZone("az-1.region-a.geo-1").get(); - assertNull(api.getAggregate("1")); + assertNull(api.get("1")); } public void testCreateAggregate() { @@ -89,7 +89,7 @@ public class HostAggregateApiExpectTest extends BaseNovaApiExpectTest { HttpResponse.builder().statusCode(200).payload(payloadFromResource("/host_aggregate_details.json")).build()) .getHostAggregateExtensionForZone("az-1.region-a.geo-1").get(); - assertEquals(api.createAggregate("ubuntu1", "nova"), exampleHostAggregate()); + assertEquals(api.createInAvailabilityZone("ubuntu1", "nova"), exampleHostAggregate()); } public void testDeleteAggregate() { @@ -99,7 +99,7 @@ public class HostAggregateApiExpectTest extends BaseNovaApiExpectTest { authenticatedGET().endpoint(endpoint).method("DELETE").build(), HttpResponse.builder().statusCode(200).build()).getHostAggregateExtensionForZone("az-1.region-a.geo-1").get(); - assertTrue(api.deleteAggregate("1")); + assertTrue(api.delete("1")); } public void testDeleteAggregateFailNotFound() { @@ -109,7 +109,7 @@ public class HostAggregateApiExpectTest extends BaseNovaApiExpectTest { authenticatedGET().endpoint(endpoint).method("DELETE").build(), HttpResponse.builder().statusCode(404).build()).getHostAggregateExtensionForZone("az-1.region-a.geo-1").get(); - assertFalse(api.deleteAggregate("1")); + assertFalse(api.delete("1")); } public void testUpdateName() { diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/HostAggregateApiLiveTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/HostAggregateApiLiveTest.java index 566c2b3c53..339bbf9f24 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/HostAggregateApiLiveTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/HostAggregateApiLiveTest.java @@ -28,8 +28,8 @@ import java.util.Set; import org.jclouds.openstack.nova.v2_0.domain.Host; import org.jclouds.openstack.nova.v2_0.domain.HostAggregate; import org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiLiveTest; -import org.testng.annotations.AfterGroups; -import org.testng.annotations.BeforeGroups; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.google.common.base.Optional; @@ -49,7 +49,7 @@ public class HostAggregateApiLiveTest extends BaseNovaApiLiveTest { private HostAggregate testAggregate; - @BeforeGroups(groups = {"integration", "live"}) + @BeforeClass(groups = {"integration", "live"}) @Override public void setupContext() { super.setupContext(); @@ -58,19 +58,19 @@ public class HostAggregateApiLiveTest extends BaseNovaApiLiveTest { hostAdminOption = novaContext.getApi().getHostAdministrationExtensionForZone(zone); } + @AfterClass(groups = { "integration", "live" }) @Override - @AfterGroups(groups = {"integration", "live"}) - public void tearDown() { + protected void tearDownContext() { if (testAggregate != null) { - assertTrue(apiOption.get().deleteAggregate(testAggregate.getId())); + assertTrue(apiOption.get().delete(testAggregate.getId())); } - super.tearDown(); + super.tearDownContext(); } public void testCreateAggregate() { if (apiOption.isPresent()) { // TODO assuming "nova" availability zone is present - testAggregate = apiOption.get().createAggregate("jclouds-test-a", "nova"); + testAggregate = apiOption.get().createInAvailabilityZone("jclouds-test-a", "nova"); } } @@ -78,13 +78,13 @@ public class HostAggregateApiLiveTest extends BaseNovaApiLiveTest { public void testListAndGetAggregate() { if (apiOption.isPresent()) { HostAggregateApi api = apiOption.get(); - Set aggregates = api.listAggregates(); + Set aggregates = api.list().toImmutableSet(); for (HostAggregate aggregate : aggregates) { assertNotNull(aggregate.getId()); assertNotNull(aggregate.getName()); assertNotNull(aggregate.getAvailabilityZone()); - HostAggregate details = api.getAggregate(aggregate.getId()); + HostAggregate details = api.get(aggregate.getId()); assertEquals(details.getId(), aggregate.getId()); assertEquals(details.getName(), aggregate.getName()); assertEquals(details.getAvailabilityZone(), aggregate.getAvailabilityZone()); @@ -110,7 +110,7 @@ public class HostAggregateApiLiveTest extends BaseNovaApiLiveTest { } // Re-fetch to double-check - details = api.getAggregate(testAggregate.getId()); + details = api.get(testAggregate.getId()); for (String key : theMetaData.keySet()) { assertEquals(details.getMetadata().get(key), theMetaData.get(key)); } @@ -123,7 +123,7 @@ public class HostAggregateApiLiveTest extends BaseNovaApiLiveTest { public void testModifyHosts() { if (apiOption.isPresent() && hostAdminOption.isPresent()) { HostAggregateApi api = apiOption.get(); - Host host = Iterables.getFirst(hostAdminOption.get().listHosts(), null); + Host host = Iterables.getFirst(hostAdminOption.get().list(), null); assertNotNull(host); String host_id = host.getName(); @@ -136,7 +136,7 @@ public class HostAggregateApiLiveTest extends BaseNovaApiLiveTest { assertEquals(details.getHosts(), ImmutableSet.of(host_id)); // re-fetch to double-check - details = api.getAggregate(testAggregate.getId()); + details = api.get(testAggregate.getId()); assertEquals(details.getHosts(), ImmutableSet.of(host_id)); // TODO wait until status of aggregate isn't CHANGING (hostAdministration.shutdown?) diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/KeyPairApiExpectTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/KeyPairApiExpectTest.java index 5f215c3b50..dc8e0e7590 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/KeyPairApiExpectTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/KeyPairApiExpectTest.java @@ -40,45 +40,45 @@ import com.google.common.collect.ImmutableSet; public class KeyPairApiExpectTest extends BaseNovaApiExpectTest { public void testListKeyPairsWhenResponseIs2xx() throws Exception { - HttpRequest listKeyPairs = HttpRequest + HttpRequest list = HttpRequest .builder() .method("GET") .endpoint("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/os-keypairs") .addHeader("Accept", "application/json") .addHeader("X-Auth-Token", authToken).build(); - HttpResponse listKeyPairsResponse = HttpResponse.builder().statusCode(200) + HttpResponse listResponse = HttpResponse.builder().statusCode(200) .payload(payloadFromResource("/keypair_list.json")).build(); NovaApi apiWhenServersExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, - responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, listKeyPairs, listKeyPairsResponse); + responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, list, listResponse); - assertEquals(apiWhenServersExist.getConfiguredZones(), ImmutableSet.of("az-1.region-a.geo-1")); + assertEquals(apiWhenServersExist.getConfiguredZones(), ImmutableSet.of("az-1.region-a.geo-1", "az-2.region-a.geo-1", "az-3.region-a.geo-1")); // NOTE this required a change to the KeyPair domain object toString method - assertEquals(apiWhenServersExist.getKeyPairExtensionForZone("az-1.region-a.geo-1").get().listKeyPairs().toString(), + assertEquals(apiWhenServersExist.getKeyPairExtensionForZone("az-1.region-a.geo-1").get().list().toString(), new ParseKeyPairListTest().expected().toString()); } public void testListKeyPairsWhenResponseIs404() throws Exception { - HttpRequest listKeyPairs = HttpRequest + HttpRequest list = HttpRequest .builder() .method("GET") .endpoint("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/os-keypairs") .addHeader("Accept", "application/json") .addHeader("X-Auth-Token", authToken).build(); - HttpResponse listKeyPairsResponse = HttpResponse.builder().statusCode(404).build(); + HttpResponse listResponse = HttpResponse.builder().statusCode(404).build(); NovaApi apiWhenNoServersExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, - responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, listKeyPairs, listKeyPairsResponse); + responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, list, listResponse); - assertTrue(apiWhenNoServersExist.getKeyPairExtensionForZone("az-1.region-a.geo-1").get().listKeyPairs().isEmpty()); + assertTrue(apiWhenNoServersExist.getKeyPairExtensionForZone("az-1.region-a.geo-1").get().list().isEmpty()); } public void testCreateKeyPair() throws Exception { - HttpRequest createKeyPair = HttpRequest + HttpRequest create = HttpRequest .builder() .method("POST") .endpoint("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/os-keypairs") @@ -87,19 +87,19 @@ public class KeyPairApiExpectTest extends BaseNovaApiExpectTest { .payload(payloadFromStringWithContentType("{\"keypair\":{\"name\":\"testkeypair\"}}", "application/json")) .build(); - HttpResponse createKeyPairResponse = HttpResponse.builder().statusCode(200) + HttpResponse createResponse = HttpResponse.builder().statusCode(200) .payload(payloadFromResource("/keypair_created.json")).build(); NovaApi apiWhenServersExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, - responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, createKeyPair, createKeyPairResponse); + responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, create, createResponse); - assertEquals(apiWhenServersExist.getKeyPairExtensionForZone("az-1.region-a.geo-1").get().createKeyPair("testkeypair") + assertEquals(apiWhenServersExist.getKeyPairExtensionForZone("az-1.region-a.geo-1").get().create("testkeypair") .toString(), new ParseKeyPairTest().expected().toString()); } public void testCreateKeyPairWithPublicKey() throws Exception { - HttpRequest createKeyPair = HttpRequest + HttpRequest create = HttpRequest .builder() .method("POST") .endpoint("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/os-keypairs") @@ -110,35 +110,35 @@ public class KeyPairApiExpectTest extends BaseNovaApiExpectTest { "{\"keypair\":{\"name\":\"testkeypair\",\"public_key\":\"ssh-rsa AAAXB3NzaC1yc2EAAAADAQABAAAAgQDFNyGjgs6c9akgmZ2ou/fJf7Pdrc23hC95/gM/33OrG4GZABACE4DTioa/PGN+7rHv9YUavUCtXrWayhGniKq/wCuI5fo5TO4AmDNv7/sCGHIHFumADSIoLx0vFhGJIetXEWxL9r0lfFC7//6yZM2W3KcGjbMtlPXqBT9K9PzdyQ== nova@nv-aw2az1-api0001\n\"}}", "application/json")).build(); - HttpResponse createKeyPairResponse = HttpResponse.builder().statusCode(200) + HttpResponse createResponse = HttpResponse.builder().statusCode(200) .payload(payloadFromResource("/keypair_created.json")).build(); NovaApi apiWhenServersExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, - responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, createKeyPair, createKeyPairResponse); + responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, create, createResponse); assertEquals( apiWhenServersExist .getKeyPairExtensionForZone("az-1.region-a.geo-1") .get() - .createKeyPairWithPublicKey( + .createWithPublicKey( "testkeypair", "ssh-rsa AAAXB3NzaC1yc2EAAAADAQABAAAAgQDFNyGjgs6c9akgmZ2ou/fJf7Pdrc23hC95/gM/33OrG4GZABACE4DTioa/PGN+7rHv9YUavUCtXrWayhGniKq/wCuI5fo5TO4AmDNv7/sCGHIHFumADSIoLx0vFhGJIetXEWxL9r0lfFC7//6yZM2W3KcGjbMtlPXqBT9K9PzdyQ== nova@nv-aw2az1-api0001\n") .toString(), new ParseKeyPairTest().expected().toString()); } public void testDeleteKeyPair() throws Exception { - HttpRequest deleteKeyPair = HttpRequest + HttpRequest delete = HttpRequest .builder() .method("DELETE") .endpoint("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/os-keypairs/testkeypair") .addHeader("Accept", "*/*") .addHeader("X-Auth-Token", authToken).build(); - HttpResponse deleteKeyPairResponse = HttpResponse.builder().statusCode(202).build(); + HttpResponse deleteResponse = HttpResponse.builder().statusCode(202).build(); NovaApi apiWhenServersExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, - responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, deleteKeyPair, deleteKeyPairResponse); + responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, delete, deleteResponse); - assertTrue(apiWhenServersExist.getKeyPairExtensionForZone("az-1.region-a.geo-1").get().deleteKeyPair("testkeypair")); + assertTrue(apiWhenServersExist.getKeyPairExtensionForZone("az-1.region-a.geo-1").get().delete("testkeypair")); } } diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/KeyPairApiLiveTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/KeyPairApiLiveTest.java index e8f2837970..4bb91ef873 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/KeyPairApiLiveTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/KeyPairApiLiveTest.java @@ -20,13 +20,12 @@ package org.jclouds.openstack.nova.v2_0.extensions; import static org.testng.Assert.assertNotNull; -import java.util.Map; -import java.util.Set; - import org.jclouds.openstack.nova.v2_0.domain.KeyPair; import org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiLiveTest; import org.testng.annotations.Test; +import com.google.common.collect.FluentIterable; + /** * Tests behavior of {@code KeyPairApi} * @@ -38,7 +37,7 @@ public class KeyPairApiLiveTest extends BaseNovaApiLiveTest { public void testListKeyPairs() throws Exception { for (String zoneId : novaContext.getApi().getConfiguredZones()) { KeyPairApi api = novaContext.getApi().getKeyPairExtensionForZone(zoneId).get(); - Set> keyPairsList = api.listKeyPairs(); + FluentIterable keyPairsList = api.list(); assertNotNull(keyPairsList); } } @@ -49,11 +48,11 @@ public class KeyPairApiLiveTest extends BaseNovaApiLiveTest { KeyPairApi api = novaContext.getApi().getKeyPairExtensionForZone(zoneId).get(); KeyPair keyPair = null; try { - keyPair = api.createKeyPair(KEYPAIR_NAME); + keyPair = api.create(KEYPAIR_NAME); assertNotNull(keyPair); } finally { if (keyPair != null) { - api.deleteKeyPair(KEYPAIR_NAME); + api.delete(KEYPAIR_NAME); } } } @@ -67,11 +66,11 @@ public class KeyPairApiLiveTest extends BaseNovaApiLiveTest { KeyPairApi api = novaContext.getApi().getKeyPairExtensionForZone(zoneId).get(); KeyPair keyPair = null; try { - keyPair = api.createKeyPairWithPublicKey(KEYPAIR_NAME, PUBLIC_KEY); + keyPair = api.createWithPublicKey(KEYPAIR_NAME, PUBLIC_KEY); assertNotNull(keyPair); } finally { if (keyPair != null) { - api.deleteKeyPair(KEYPAIR_NAME); + api.delete(KEYPAIR_NAME); } } } diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/QuotaApiExpectTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/QuotaApiExpectTest.java index b3e31ae09a..b28a35f606 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/QuotaApiExpectTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/QuotaApiExpectTest.java @@ -28,7 +28,7 @@ import javax.ws.rs.core.MediaType; import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpResponse; -import org.jclouds.openstack.nova.v2_0.domain.Quotas; +import org.jclouds.openstack.nova.v2_0.domain.Quota; import org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiExpectTest; import org.jclouds.rest.ResourceNotFoundException; import org.testng.annotations.Test; @@ -48,7 +48,7 @@ public class QuotaApiExpectTest extends BaseNovaApiExpectTest { authenticatedGET().endpoint(endpoint).build(), HttpResponse.builder().statusCode(200).payload(payloadFromResource("/quotas.json")).build()).getQuotaExtensionForZone("az-1.region-a.geo-1").get(); - assertEquals(api.getQuotasForTenant("demo"), getTestQuotas()); + assertEquals(api.getByTenant("demo"), getTestQuotas()); } public void testGetQuotasFailsTenantNotFound() throws Exception { @@ -57,7 +57,7 @@ public class QuotaApiExpectTest extends BaseNovaApiExpectTest { responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, authenticatedGET().endpoint(endpoint).build(), HttpResponse.builder().statusCode(404).build()).getQuotaExtensionForZone("az-1.region-a.geo-1").get(); - assertNull(api.getQuotasForTenant("demo")); + assertNull(api.getByTenant("demo")); } public void testGetDefaultQuotas() throws Exception { @@ -67,7 +67,7 @@ public class QuotaApiExpectTest extends BaseNovaApiExpectTest { authenticatedGET().endpoint(endpoint).build(), HttpResponse.builder().statusCode(200).payload(payloadFromResource("/quotas.json")).build()).getQuotaExtensionForZone("az-1.region-a.geo-1").get(); - assertEquals(api.getDefaultQuotasForTenant("demo"), getTestQuotas()); + assertEquals(api.getDefaultsForTenant("demo"), getTestQuotas()); } public void testGetDefaultQuotasFailsTenantNotFound() throws Exception { @@ -76,7 +76,7 @@ public class QuotaApiExpectTest extends BaseNovaApiExpectTest { responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, authenticatedGET().endpoint(endpoint).build(), HttpResponse.builder().statusCode(404).build()).getQuotaExtensionForZone("az-1.region-a.geo-1").get(); - assertNull(api.getDefaultQuotasForTenant("demo")); + assertNull(api.getDefaultsForTenant("demo")); } @@ -90,7 +90,7 @@ public class QuotaApiExpectTest extends BaseNovaApiExpectTest { .build(), HttpResponse.builder().statusCode(200).build()).getQuotaExtensionForZone("az-1.region-a.geo-1").get(); - assertTrue(api.updateQuotasForTenant("demo", getTestQuotas())); + assertTrue(api.updateQuotaOfTenant(getTestQuotas(), "demo")); } @Test(expectedExceptions = ResourceNotFoundException.class) @@ -104,11 +104,11 @@ public class QuotaApiExpectTest extends BaseNovaApiExpectTest { .build(), HttpResponse.builder().statusCode(404).build()).getQuotaExtensionForZone("az-1.region-a.geo-1").get(); - api.updateQuotasForTenant("demo", getTestQuotas()); + api.updateQuotaOfTenant(getTestQuotas(), "demo"); } - public static Quotas getTestQuotas() { - return Quotas.builder() + public static Quota getTestQuotas() { + return Quota.builder() .metadataItems(128) .injectedFileContentBytes(10240) .injectedFiles(5) diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/QuotaApiLiveTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/QuotaApiLiveTest.java index efd88d750d..2cb2bb2412 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/QuotaApiLiveTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/QuotaApiLiveTest.java @@ -21,7 +21,7 @@ package org.jclouds.openstack.nova.v2_0.extensions; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; -import org.jclouds.openstack.nova.v2_0.domain.Quotas; +import org.jclouds.openstack.nova.v2_0.domain.Quota; import org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiLiveTest; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; @@ -50,14 +50,14 @@ public class QuotaApiLiveTest extends BaseNovaApiLiveTest { public void testGetQuotasForCurrentTenant() { if (apiOption.isPresent()) { - Quotas quota = apiOption.get().getQuotasForTenant(tenant); + Quota quota = apiOption.get().getByTenant(tenant); assertQuotasIsValid(quota); } } public void testGetDefaultQuotasForCurrentTenant() { if (apiOption.isPresent()) { - Quotas quota = apiOption.get().getDefaultQuotasForTenant(tenant); + Quota quota = apiOption.get().getDefaultsForTenant(tenant); assertQuotasIsValid(quota); } } @@ -65,28 +65,28 @@ public class QuotaApiLiveTest extends BaseNovaApiLiveTest { public void testUpdateQuotasOfCurrentTenantThenReset() { if (apiOption.isPresent()) { QuotaApi api = apiOption.get(); - Quotas before = api.getQuotasForTenant(tenant); + Quota before = api.getByTenant(tenant); assertQuotasIsValid(before); - Quotas modified = before.toBuilder() + Quota modified = before.toBuilder() .cores(before.getCores() - 1) .instances(before.getInstances() - 1) - .metadataItems(before.getMetadataItems() - 1) + .metadataItems(before.getMetadatas() - 1) .ram(before.getRam() - 1) .volumes(before.getVolumes() - 1) .build(); - assertTrue(api.updateQuotasForTenant(tenant, modified)); + assertTrue(api.updateQuotaOfTenant(modified, tenant)); - assertEquals(api.getQuotasForTenant(tenant), modified); + assertEquals(api.getByTenant(tenant), modified); - assertTrue(api.updateQuotasForTenant(tenant, before)); + assertTrue(api.updateQuotaOfTenant(before, tenant)); - assertEquals(api.getQuotasForTenant(tenant), before); + assertEquals(api.getByTenant(tenant), before); } } - protected void assertQuotasIsValid(Quotas quota) { + protected void assertQuotasIsValid(Quota quota) { assertTrue(quota.getCores() > 0); assertTrue(quota.getFloatingIps() >= 0); assertTrue(quota.getGigabytes() > 0); diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/QuotaClassApiExpectTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/QuotaClassApiExpectTest.java index 0a8ca1a5f6..612c73f8f2 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/QuotaClassApiExpectTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/QuotaClassApiExpectTest.java @@ -48,7 +48,7 @@ public class QuotaClassApiExpectTest extends BaseNovaApiExpectTest { authenticatedGET().endpoint(endpoint).build(), HttpResponse.builder().statusCode(200).payload(payloadFromResource("/quota_class.json")).build()).getQuotaClassExtensionForZone("az-1.region-a.geo-1").get(); - assertEquals(api.getQuotaClass("jcloudstestquotas"), getTestQuotas()); + assertEquals(api.get("jcloudstestquotas"), getTestQuotas()); } public void testGetQuotasFailsTenantNotFound() throws Exception { @@ -57,7 +57,7 @@ public class QuotaClassApiExpectTest extends BaseNovaApiExpectTest { responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, authenticatedGET().endpoint(endpoint).build(), HttpResponse.builder().statusCode(404).build()).getQuotaClassExtensionForZone("az-1.region-a.geo-1").get(); - assertNull(api.getQuotaClass("jcloudstestquotas")); + assertNull(api.get("jcloudstestquotas")); } public void testUpdateQuotas() throws Exception { @@ -70,7 +70,7 @@ public class QuotaClassApiExpectTest extends BaseNovaApiExpectTest { .build(), HttpResponse.builder().statusCode(200).build()).getQuotaClassExtensionForZone("az-1.region-a.geo-1").get(); - assertTrue(api.updateQuotaClass("myclass", getTestQuotas())); + assertTrue(api.update("myclass", getTestQuotas())); } @Test(expectedExceptions = ResourceNotFoundException.class) @@ -84,7 +84,7 @@ public class QuotaClassApiExpectTest extends BaseNovaApiExpectTest { .build(), HttpResponse.builder().statusCode(404).build()).getQuotaClassExtensionForZone("az-1.region-a.geo-1").get(); - api.updateQuotaClass("jcloudstestquotas", getTestQuotas()); + api.update("jcloudstestquotas", getTestQuotas()); } public static QuotaClass getTestQuotas() { diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/QuotaClassApiLiveTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/QuotaClassApiLiveTest.java index d5b80da512..dd79198298 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/QuotaClassApiLiveTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/QuotaClassApiLiveTest.java @@ -60,16 +60,16 @@ public class QuotaClassApiLiveTest extends BaseNovaApiLiveTest { .volumes(5) .build(); - assertTrue(api.updateQuotaClass(firstVersion.getId(), firstVersion)); + assertTrue(api.update(firstVersion.getId(), firstVersion)); - assertEquals(api.getQuotaClass(firstVersion.getId()), firstVersion); + assertEquals(api.get(firstVersion.getId()), firstVersion); // Change it again (since we may have run this test before and we can't delete the QuotaClass) QuotaClass secondVersion = firstVersion.toBuilder().ram(8192).build(); - assertTrue(api.updateQuotaClass(secondVersion.getId(), secondVersion)); + assertTrue(api.update(secondVersion.getId(), secondVersion)); - assertEquals(api.getQuotaClass(secondVersion.getId()), secondVersion); + assertEquals(api.get(secondVersion.getId()), secondVersion); } } } diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/SecurityGroupApiExpectTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/SecurityGroupApiExpectTest.java index cf978e2f31..fd2c1b8ec7 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/SecurityGroupApiExpectTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/SecurityGroupApiExpectTest.java @@ -47,22 +47,22 @@ import com.google.common.collect.ImmutableSet; @Test(groups = "unit", testName = "SecurityGroupApiExpectTest") public class SecurityGroupApiExpectTest extends BaseNovaApiExpectTest { public void testListSecurityGroupsWhenResponseIs2xx() throws Exception { - HttpRequest listSecurityGroups = HttpRequest.builder().method("GET").endpoint( + HttpRequest list = HttpRequest.builder().method("GET").endpoint( URI.create("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/os-security-groups")).headers( ImmutableMultimap. builder().put("Accept", "application/json").put("X-Auth-Token", authToken).build()).build(); - HttpResponse listSecurityGroupsResponse = HttpResponse.builder().statusCode(200).payload( + HttpResponse listResponse = HttpResponse.builder().statusCode(200).payload( payloadFromResource("/securitygroup_list.json")).build(); NovaApi apiWhenSecurityGroupsExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, - responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, listSecurityGroups, - listSecurityGroupsResponse); + responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, list, + listResponse); - assertEquals(apiWhenSecurityGroupsExist.getConfiguredZones(), ImmutableSet.of("az-1.region-a.geo-1")); + assertEquals(apiWhenSecurityGroupsExist.getConfiguredZones(), ImmutableSet.of("az-1.region-a.geo-1", "az-2.region-a.geo-1", "az-3.region-a.geo-1")); assertEquals(apiWhenSecurityGroupsExist.getSecurityGroupExtensionForZone("az-1.region-a.geo-1").get() - .listSecurityGroups().toString(), new ParseSecurityGroupListTest().expected().toString()); + .list().toString(), new ParseSecurityGroupListTest().expected().toString()); } public void testListSecurityGroupsWhenReponseIs404IsEmpty() throws Exception { @@ -78,7 +78,7 @@ public class SecurityGroupApiExpectTest extends BaseNovaApiExpectTest { listListSecurityGroupsResponse); assertTrue(apiWhenNoSecurityGroupsExist.getSecurityGroupExtensionForZone("az-1.region-a.geo-1").get() - .listSecurityGroups().isEmpty()); + .list().isEmpty()); } public void testGetSecurityGroupWhenResponseIs2xx() throws Exception { @@ -96,7 +96,7 @@ public class SecurityGroupApiExpectTest extends BaseNovaApiExpectTest { getSecurityGroupResponse); assertEquals(apiWhenSecurityGroupsExist.getSecurityGroupExtensionForZone("az-1.region-a.geo-1").get() - .getSecurityGroup("0").toString(), new ParseSecurityGroupTest().expected().toString()); + .get("0").toString(), new ParseSecurityGroupTest().expected().toString()); } public void testGetSecurityGroupWhenResponseIs404() throws Exception { @@ -112,12 +112,12 @@ public class SecurityGroupApiExpectTest extends BaseNovaApiExpectTest { getSecurityGroupResponse); assertNull(apiWhenNoSecurityGroupsExist.getSecurityGroupExtensionForZone("az-1.region-a.geo-1").get() - .getSecurityGroup("0")); + .get("0")); } public void testCreateSecurityGroupWhenResponseIs2xx() throws Exception { - HttpRequest createSecurityGroup = HttpRequest.builder().method("POST").endpoint( + HttpRequest create = HttpRequest.builder().method("POST").endpoint( URI.create("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/os-security-groups")).headers( ImmutableMultimap. builder().put("Accept", "application/json").put("X-Auth-Token", authToken).build()) @@ -126,38 +126,38 @@ public class SecurityGroupApiExpectTest extends BaseNovaApiExpectTest { "{\"security_group\":{\"name\":\"jclouds-test\",\"description\":\"jclouds-test\"}}", "application/json")).build(); - HttpResponse createSecurityGroupResponse = HttpResponse.builder().statusCode(200).payload( + HttpResponse createResponse = HttpResponse.builder().statusCode(200).payload( payloadFromResource("/securitygroup_created.json")).build(); NovaApi apiWhenSecurityGroupsExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, - responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, createSecurityGroup, - createSecurityGroupResponse); + responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, create, + createResponse); assertEquals(apiWhenSecurityGroupsExist.getSecurityGroupExtensionForZone("az-1.region-a.geo-1").get() - .createSecurityGroupWithNameAndDescription("jclouds-test", "jclouds-test").toString(), - createSecurityGroupExpected().toString()); + .createWithDescription("jclouds-test", "jclouds-test").toString(), + createExpected().toString()); } public void testDeleteSecurityGroupWhenResponseIs2xx() throws Exception { - HttpRequest deleteSecurityGroup = HttpRequest.builder().method("DELETE").endpoint( + HttpRequest delete = HttpRequest.builder().method("DELETE").endpoint( URI.create("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/os-security-groups/160")) .headers( ImmutableMultimap. builder().put("Accept", "application/json") .put("X-Auth-Token", authToken).build()).build(); - HttpResponse deleteSecurityGroupResponse = HttpResponse.builder().statusCode(202).build(); + HttpResponse deleteResponse = HttpResponse.builder().statusCode(202).build(); NovaApi apiWhenServersExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, - responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, deleteSecurityGroup, - deleteSecurityGroupResponse); + responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, delete, + deleteResponse); assertTrue(apiWhenServersExist.getSecurityGroupExtensionForZone("az-1.region-a.geo-1").get() - .deleteSecurityGroup("160")); + .delete("160")); } public void testCreateSecurityGroupRuleForCidrBlockWhenResponseIs2xx() throws Exception { - HttpRequest createSecurityGroupRule = HttpRequest + HttpRequest createRule = HttpRequest .builder() .method("POST") .endpoint("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/os-security-group-rules") @@ -168,21 +168,21 @@ public class SecurityGroupApiExpectTest extends BaseNovaApiExpectTest { "{\"security_group_rule\":{\"parent_group_id\":\"161\",\"cidr\":\"0.0.0.0/0\",\"ip_protocol\":\"tcp\",\"from_port\":\"80\",\"to_port\":\"8080\"}}", "application/json")).build(); - HttpResponse createSecurityGroupRuleResponse = HttpResponse.builder().statusCode(200).payload( + HttpResponse createRuleResponse = HttpResponse.builder().statusCode(200).payload( payloadFromResource("/securitygrouprule_created.json")).build(); NovaApi apiWhenSecurityGroupsExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, - responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, createSecurityGroupRule, - createSecurityGroupRuleResponse); + responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, createRule, + createRuleResponse); assertEquals(apiWhenSecurityGroupsExist.getSecurityGroupExtensionForZone("az-1.region-a.geo-1").get() - .createSecurityGroupRuleAllowingCidrBlock("161", + .createRuleAllowingCidrBlock("161", Ingress.builder().ipProtocol(IpProtocol.TCP).fromPort(80).toPort(8080).build(), "0.0.0.0/0") - .toString(), createSecurityGroupRuleExpected().toString()); + .toString(), createRuleExpected().toString()); } public void testCreateSecurityGroupRuleForSecurityGroupIdWhenResponseIs2xx() throws Exception { - HttpRequest createSecurityGroupRule = HttpRequest + HttpRequest createRule = HttpRequest .builder() .method("POST") .endpoint("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/os-security-group-rules") @@ -193,43 +193,43 @@ public class SecurityGroupApiExpectTest extends BaseNovaApiExpectTest { "{\"security_group_rule\":{\"group_id\":\"999\",\"parent_group_id\":\"161\",\"ip_protocol\":\"tcp\",\"from_port\":\"80\",\"to_port\":\"8080\"}}", "application/json")).build(); - HttpResponse createSecurityGroupRuleResponse = HttpResponse.builder().statusCode(200).payload( + HttpResponse createRuleResponse = HttpResponse.builder().statusCode(200).payload( payloadFromResource("/securitygrouprule_created.json")).build(); NovaApi apiWhenSecurityGroupsExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, - responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, createSecurityGroupRule, - createSecurityGroupRuleResponse); + responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, createRule, + createRuleResponse); assertEquals(apiWhenSecurityGroupsExist.getSecurityGroupExtensionForZone("az-1.region-a.geo-1").get() - .createSecurityGroupRuleAllowingSecurityGroupId("161", + .createRuleAllowingSecurityGroupId("161", Ingress.builder().ipProtocol(IpProtocol.TCP).fromPort(80).toPort(8080).build(), "999") - .toString(), createSecurityGroupRuleExpected().toString()); + .toString(), createRuleExpected().toString()); } public void testDeleteSecurityGroupRuleWhenResponseIs2xx() throws Exception { - HttpRequest deleteSecurityGroupRule = HttpRequest.builder().method("DELETE").endpoint( + HttpRequest deleteRule = HttpRequest.builder().method("DELETE").endpoint( URI.create("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/os-security-group-rules/161")) .headers( ImmutableMultimap. builder().put("Accept", "*/*") .put("X-Auth-Token", authToken).build()).build(); - HttpResponse deleteSecurityGroupRuleResponse = HttpResponse.builder().statusCode(202).build(); + HttpResponse deleteRuleResponse = HttpResponse.builder().statusCode(202).build(); NovaApi apiWhenSecurityGroupsExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, - responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, deleteSecurityGroupRule, - deleteSecurityGroupRuleResponse); + responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, deleteRule, + deleteRuleResponse); assertTrue(apiWhenSecurityGroupsExist.getSecurityGroupExtensionForZone("az-1.region-a.geo-1").get() - .deleteSecurityGroupRule("161")); + .deleteRule("161")); } - private SecurityGroup createSecurityGroupExpected() { + private SecurityGroup createExpected() { return SecurityGroup.builder().description("jclouds-test").id("160").name("jclouds-test").rules( ImmutableSet. of()).tenantId("dev_16767499955063").build(); } - private SecurityGroupRule createSecurityGroupRuleExpected() { + private SecurityGroupRule createRuleExpected() { return SecurityGroupRule.builder().fromPort(80).id("218").ipProtocol( IpProtocol.TCP).ipRange("0.0.0.0/0").parentGroupId("161").toPort(8080).build(); } diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/SecurityGroupApiLiveTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/SecurityGroupApiLiveTest.java index e6a5a57ce8..b3555bcf06 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/SecurityGroupApiLiveTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/SecurityGroupApiLiveTest.java @@ -41,10 +41,10 @@ public class SecurityGroupApiLiveTest extends BaseNovaApiLiveTest { public static final String SECURITY_GROUP_NAME = "testsg"; - public void listSecurityGroups() throws Exception { + public void list() throws Exception { for (String zoneId : novaContext.getApi().getConfiguredZones()) { SecurityGroupApi api = novaContext.getApi().getSecurityGroupExtensionForZone(zoneId).get(); - Set securityGroupsList = api.listSecurityGroups(); + Set securityGroupsList = api.list().toImmutableSet(); assertNotNull(securityGroupsList); } } @@ -56,14 +56,14 @@ public class SecurityGroupApiLiveTest extends BaseNovaApiLiveTest { String id; try { securityGroup = api - .createSecurityGroupWithNameAndDescription(SECURITY_GROUP_NAME, "test security group"); + .createWithDescription(SECURITY_GROUP_NAME, "test security group"); assertNotNull(securityGroup); id = securityGroup.getId(); - SecurityGroup theGroup = api.getSecurityGroup(id); + SecurityGroup theGroup = api.get(id); assertNotNull(theGroup); } finally { if (securityGroup != null) { - api.deleteSecurityGroup(securityGroup.getId()); + api.delete(securityGroup.getId()); } } } @@ -75,25 +75,25 @@ public class SecurityGroupApiLiveTest extends BaseNovaApiLiveTest { SecurityGroup securityGroup = null; try { - securityGroup = api.createSecurityGroupWithNameAndDescription(SECURITY_GROUP_NAME, "test security group"); + securityGroup = api.createWithDescription(SECURITY_GROUP_NAME, "test security group"); assertNotNull(securityGroup); for (int port : ImmutableSet.of(22, 8080)) { - SecurityGroupRule rule = api.createSecurityGroupRuleAllowingCidrBlock(securityGroup.getId(), Ingress + SecurityGroupRule rule = api.createRuleAllowingCidrBlock(securityGroup.getId(), Ingress .builder().ipProtocol(IpProtocol.TCP).fromPort(port).toPort(port).build(), "0.0.0.0/0"); assertNotNull(rule); - SecurityGroupRule rule2 = api.createSecurityGroupRuleAllowingSecurityGroupId(securityGroup.getId(), + SecurityGroupRule rule2 = api.createRuleAllowingSecurityGroupId(securityGroup.getId(), Ingress.builder().ipProtocol(IpProtocol.TCP).fromPort(port).toPort(port).build(), securityGroup .getId()); assertNotNull(rule2); } - securityGroup = api.getSecurityGroup(securityGroup.getId()); + securityGroup = api.get(securityGroup.getId()); } finally { if (securityGroup != null) { - api.deleteSecurityGroup(securityGroup.getId()); + api.delete(securityGroup.getId()); } } } diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/ServerWithSecurityGroupsApiExpectTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/ServerWithSecurityGroupsApiExpectTest.java index 8c06d5bdd2..e9551c0981 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/ServerWithSecurityGroupsApiExpectTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/ServerWithSecurityGroupsApiExpectTest.java @@ -47,7 +47,7 @@ public class ServerWithSecurityGroupsApiExpectTest extends BaseNovaApiExpectTest HttpResponse.builder().statusCode(200).payload(payloadFromResource("/server_with_security_groups.json")).build() ).getServerWithSecurityGroupsExtensionForZone("az-1.region-a.geo-1").get(); - ServerWithSecurityGroups server = api.getServer("8d0a6ca5-8849-4b3d-b86e-f24c92490ebb"); + ServerWithSecurityGroups server = api.get("8d0a6ca5-8849-4b3d-b86e-f24c92490ebb"); assertEquals(server.getId(), "8d0a6ca5-8849-4b3d-b86e-f24c92490ebb"); assertEquals(server.getSecurityGroupNames(), ImmutableSet.of("default", "group1")); } @@ -60,6 +60,6 @@ public class ServerWithSecurityGroupsApiExpectTest extends BaseNovaApiExpectTest authenticatedGET().endpoint(endpoint).build(), HttpResponse.builder().statusCode(404).build() ).getServerWithSecurityGroupsExtensionForZone("az-1.region-a.geo-1").get(); - assertNull(api.getServer("8d0a6ca5-8849-4b3d-b86e-f24c92490ebb")); + assertNull(api.get("8d0a6ca5-8849-4b3d-b86e-f24c92490ebb")); } } diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/ServerWithSecurityGroupsApiLiveTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/ServerWithSecurityGroupsApiLiveTest.java index 533ac32432..4254a1d147 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/ServerWithSecurityGroupsApiLiveTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/ServerWithSecurityGroupsApiLiveTest.java @@ -56,8 +56,8 @@ public class ServerWithSecurityGroupsApiLiveTest extends BaseNovaApiLiveTest { public void testGetServer() { if (apiOption.isPresent()) { - for (Resource server : serverApi.listServers()) { - ServerWithSecurityGroups serverWithGroups = apiOption.get().getServer(server.getId()); + for (Resource server : serverApi.list().concat()) { + ServerWithSecurityGroups serverWithGroups = apiOption.get().get(server.getId()); assertEquals(serverWithGroups.getId(), server.getId()); assertEquals(serverWithGroups.getName(), server.getName()); assertNotNull(serverWithGroups.getSecurityGroupNames()); @@ -68,12 +68,12 @@ public class ServerWithSecurityGroupsApiLiveTest extends BaseNovaApiLiveTest { try { testServer = createServerInZone(zone); - ServerWithSecurityGroups results = apiOption.get().getServer(testServer.getId()); + ServerWithSecurityGroups results = apiOption.get().get(testServer.getId()); assertEquals(results.getId(), testServer.getId()); assertEquals(results.getSecurityGroupNames(), ImmutableSet.of("default")); } finally { if (testServer != null) { - serverApi.deleteServer(testServer.getId()); + serverApi.delete(testServer.getId()); } } } diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/SimpleTenantUsageApiExpectTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/SimpleTenantUsageApiExpectTest.java index e158655dd2..d99e66bb6f 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/SimpleTenantUsageApiExpectTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/SimpleTenantUsageApiExpectTest.java @@ -58,7 +58,7 @@ public class SimpleTenantUsageApiExpectTest extends BaseNovaApiExpectTest { .payload(payloadFromResource("/simple_tenant_usages.json")).build()) .getSimpleTenantUsageExtensionForZone("az-1.region-a.geo-1").get(); - Set results = api.listTenantUsages(); + Set results = api.list().toImmutableSet(); SimpleTenantUsage usage = Iterables.getOnlyElement(results); assertEquals(usage.getTenantId(), "f8535069c3fb404cb61c873b1a0b4921"); @@ -84,7 +84,7 @@ public class SimpleTenantUsageApiExpectTest extends BaseNovaApiExpectTest { .payload(payloadFromResource("/simple_tenant_usage.json")).build()) .getSimpleTenantUsageExtensionForZone("az-1.region-a.geo-1").get(); - SimpleTenantUsage usage = api.getTenantUsage("test-1234"); + SimpleTenantUsage usage = api.get("test-1234"); assertEquals(usage.getTenantId(), "f8535069c3fb404cb61c873b1a0b4921"); SimpleTenantUsage expected = SimpleTenantUsage.builder().tenantId("f8535069c3fb404cb61c873b1a0b4921").totalHours(4.833333333333333E-7).totalLocalGbUsage(1.933333333333333E-05) diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/SimpleTenantUsageApiLiveTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/SimpleTenantUsageApiLiveTest.java index 4fe7a30b36..887481a56f 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/SimpleTenantUsageApiLiveTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/SimpleTenantUsageApiLiveTest.java @@ -41,10 +41,10 @@ public class SimpleTenantUsageApiLiveTest extends BaseNovaApiLiveTest { Optional optApi = novaContext.getApi().getSimpleTenantUsageExtensionForZone(zoneId); if (optApi.isPresent() && identity.endsWith(":admin")) { SimpleTenantUsageApi api = optApi.get(); - Set usages = api.listTenantUsages(); + Set usages = api.list().toImmutableSet(); assertNotNull(usages); for (SimpleTenantUsage usage : usages) { - SimpleTenantUsage details = api.getTenantUsage(usage.getTenantId()); + SimpleTenantUsage details = api.get(usage.getTenantId()); assertNotNull(details); } } diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/VirtualInterfaceApiExpectTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/VirtualInterfaceApiExpectTest.java index be03ed603a..b3dfefe215 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/VirtualInterfaceApiExpectTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/VirtualInterfaceApiExpectTest.java @@ -47,7 +47,7 @@ public class VirtualInterfaceApiExpectTest extends BaseNovaApiExpectTest { HttpResponse.builder().statusCode(200).payload(payloadFromResource("/virtual_interfaces_list.json")).build() ).getVirtualInterfaceExtensionForZone("az-1.region-a.geo-1").get(); - VirtualInterface vif = Iterables.getOnlyElement(api.listVirtualInterfacesForServer("1")); + VirtualInterface vif = Iterables.getOnlyElement(api.listOnServer("1")); assertEquals(vif.getId(), "02315827-b05c-4668-9c05-75c68838074a"); assertEquals(vif.getMacAddress(), "fa:16:3e:09:71:34"); } @@ -61,6 +61,6 @@ public class VirtualInterfaceApiExpectTest extends BaseNovaApiExpectTest { HttpResponse.builder().statusCode(404).build() ).getVirtualInterfaceExtensionForZone("az-1.region-a.geo-1").get(); - assertTrue(api.listVirtualInterfacesForServer("1").isEmpty()); + assertTrue(api.listOnServer("1").isEmpty()); } } diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/VirtualInterfaceApiLiveTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/VirtualInterfaceApiLiveTest.java index f409ea1181..8047bcae93 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/VirtualInterfaceApiLiveTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/VirtualInterfaceApiLiveTest.java @@ -55,14 +55,14 @@ public class VirtualInterfaceApiLiveTest extends BaseNovaApiLiveTest { Server testServer = null; try { testServer = createServerInZone(zone); - Set results = apiOption.get().listVirtualInterfacesForServer(testServer.getId()); + Set results = apiOption.get().listOnServer(testServer.getId()).toImmutableSet(); for (VirtualInterface vif : results) { assertNotNull(vif.getId()); assertNotNull(vif.getMacAddress()); } } finally { if (testServer != null) { - novaContext.getApi().getServerApiForZone(zone).deleteServer(testServer.getId()); + novaContext.getApi().getServerApiForZone(zone).delete(testServer.getId()); } } } diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/VolumeApiExpectTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/VolumeApiExpectTest.java index 80bde501e3..25b036a4da 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/VolumeApiExpectTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/VolumeApiExpectTest.java @@ -62,7 +62,7 @@ public class VolumeApiExpectTest extends BaseNovaApiExpectTest { HttpResponse.builder().statusCode(200).payload(payloadFromResource("/volume_list.json")).build() ).getVolumeExtensionForZone("az-1.region-a.geo-1").get(); - Set volumes = api.listVolumes(); + Set volumes = api.list().toImmutableSet(); assertEquals(volumes, ImmutableSet.of(testVolume())); } @@ -75,7 +75,7 @@ public class VolumeApiExpectTest extends BaseNovaApiExpectTest { HttpResponse.builder().statusCode(404).build() ).getVolumeExtensionForZone("az-1.region-a.geo-1").get(); - Set volumes = api.listVolumes(); + Set volumes = api.list().toImmutableSet(); assertTrue(volumes.isEmpty()); } @@ -88,7 +88,7 @@ public class VolumeApiExpectTest extends BaseNovaApiExpectTest { HttpResponse.builder().statusCode(200).payload(payloadFromResource("/volume_list_detail.json")).build() ).getVolumeExtensionForZone("az-1.region-a.geo-1").get(); - Set volumes = api.listVolumesInDetail(); + Set volumes = api.listInDetail().toImmutableSet(); assertEquals(volumes, ImmutableSet.of(testVolume())); } @@ -101,7 +101,7 @@ public class VolumeApiExpectTest extends BaseNovaApiExpectTest { HttpResponse.builder().statusCode(404).build() ).getVolumeExtensionForZone("az-1.region-a.geo-1").get(); - Set volumes = api.listVolumesInDetail(); + Set volumes = api.listInDetail().toImmutableSet(); assertTrue(volumes.isEmpty()); } @@ -117,7 +117,7 @@ public class VolumeApiExpectTest extends BaseNovaApiExpectTest { HttpResponse.builder().statusCode(200).payload(payloadFromResource("/volume_details.json")).build() ).getVolumeExtensionForZone("az-1.region-a.geo-1").get(); - Volume volume = api.createVolume(1, CreateVolumeOptions.Builder.name("jclouds-test-volume").description("description of test volume")); + Volume volume = api.create(1, CreateVolumeOptions.Builder.name("jclouds-test-volume").description("description of test volume")); assertEquals(volume, testVolume()); } @@ -135,7 +135,7 @@ public class VolumeApiExpectTest extends BaseNovaApiExpectTest { HttpResponse.builder().statusCode(404).payload(payloadFromResource("/volume_details.json")).build() ).getVolumeExtensionForZone("az-1.region-a.geo-1").get(); - api.createVolume(1, CreateVolumeOptions.Builder.name("jclouds-test-volume").description("description of test volume")); + api.create(1, CreateVolumeOptions.Builder.name("jclouds-test-volume").description("description of test volume")); } public void testGetVolume() { @@ -147,7 +147,7 @@ public class VolumeApiExpectTest extends BaseNovaApiExpectTest { HttpResponse.builder().statusCode(200).payload(payloadFromResource("/volume_details.json")).build() ).getVolumeExtensionForZone("az-1.region-a.geo-1").get(); - Volume volume = api.getVolume("1"); + Volume volume = api.get("1"); assertEquals(volume, testVolume()); // double-check equals() assertEquals(volume.getStatus(), Volume.Status.IN_USE); @@ -167,7 +167,7 @@ public class VolumeApiExpectTest extends BaseNovaApiExpectTest { HttpResponse.builder().statusCode(404).build() ).getVolumeExtensionForZone("az-1.region-a.geo-1").get(); - assertNull(api.getVolume("1")); + assertNull(api.get("1")); } public void testDeleteVolume() { @@ -179,7 +179,7 @@ public class VolumeApiExpectTest extends BaseNovaApiExpectTest { HttpResponse.builder().statusCode(200).payload(payloadFromResource("/attachment_details.json")).build() ).getVolumeExtensionForZone("az-1.region-a.geo-1").get(); - assertTrue(api.deleteVolume("1")); + assertTrue(api.delete("1")); } public void testDeleteVolumeFail() { @@ -191,7 +191,7 @@ public class VolumeApiExpectTest extends BaseNovaApiExpectTest { HttpResponse.builder().statusCode(404).build() ).getVolumeExtensionForZone("az-1.region-a.geo-1").get(); - assertFalse(api.deleteVolume("1")); + assertFalse(api.delete("1")); } public void testListAttachments() { @@ -203,7 +203,7 @@ public class VolumeApiExpectTest extends BaseNovaApiExpectTest { HttpResponse.builder().statusCode(200).payload(payloadFromResource("/attachment_list.json")).build() ).getVolumeExtensionForZone("az-1.region-a.geo-1").get(); - Set attachments = api.listAttachmentsOnServer("instance-1"); + Set attachments = api.listAttachmentsOnServer("instance-1").toImmutableSet(); assertEquals(attachments, ImmutableSet.of(testAttachment())); // double-check individual fields VolumeAttachment attachment = Iterables.getOnlyElement(attachments); @@ -312,7 +312,7 @@ public class VolumeApiExpectTest extends BaseNovaApiExpectTest { HttpResponse.builder().statusCode(200).payload(payloadFromResource("/snapshot_list.json")).build() ).getVolumeExtensionForZone("az-1.region-a.geo-1").get(); - Set snapshots = api.listSnapshots(); + Set snapshots = api.listSnapshots().toImmutableSet(); assertEquals(snapshots, ImmutableSet.of(testSnapshot())); } @@ -325,7 +325,7 @@ public class VolumeApiExpectTest extends BaseNovaApiExpectTest { HttpResponse.builder().statusCode(404).build() ).getVolumeExtensionForZone("az-1.region-a.geo-1").get(); - Set snapshots = api.listSnapshots(); + Set snapshots = api.listSnapshots().toImmutableSet(); assertTrue(snapshots.isEmpty()); } @@ -363,7 +363,7 @@ public class VolumeApiExpectTest extends BaseNovaApiExpectTest { HttpResponse.builder().statusCode(200).payload(payloadFromResource("/snapshot_list_detail.json")).build() ).getVolumeExtensionForZone("az-1.region-a.geo-1").get(); - Set snapshots = api.listSnapshotsInDetail(); + Set snapshots = api.listSnapshotsInDetail().toImmutableSet(); assertEquals(snapshots, ImmutableSet.of(testSnapshot())); // double-check individual fields @@ -385,7 +385,7 @@ public class VolumeApiExpectTest extends BaseNovaApiExpectTest { HttpResponse.builder().statusCode(404).build() ).getVolumeExtensionForZone("az-1.region-a.geo-1").get(); - Set snapshots = api.listSnapshotsInDetail(); + Set snapshots = api.listSnapshotsInDetail().toImmutableSet(); assertTrue(snapshots.isEmpty()); } diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/VolumeApiLiveTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/VolumeApiLiveTest.java index fe10147f79..4e1efbf00b 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/VolumeApiLiveTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/VolumeApiLiveTest.java @@ -31,8 +31,8 @@ import org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiLiveTest; import org.jclouds.openstack.nova.v2_0.options.CreateVolumeOptions; import org.jclouds.openstack.nova.v2_0.options.CreateVolumeSnapshotOptions; import org.jclouds.predicates.RetryablePredicate; -import org.testng.annotations.AfterGroups; -import org.testng.annotations.BeforeGroups; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.google.common.base.Objects; @@ -54,7 +54,7 @@ public class VolumeApiLiveTest extends BaseNovaApiLiveTest { private Volume testVolume; private VolumeSnapshot testSnapshot; - @BeforeGroups(groups = { "integration", "live" }) + @BeforeClass(groups = {"integration", "live"}) @Override public void setupContext() { super.setupContext(); @@ -62,9 +62,9 @@ public class VolumeApiLiveTest extends BaseNovaApiLiveTest { volumeOption = novaContext.getApi().getVolumeExtensionForZone(zone); } - @AfterGroups(groups = "live", alwaysRun = true) + @AfterClass(groups = { "integration", "live" }) @Override - protected void tearDown() { + protected void tearDownContext() { if (volumeOption.isPresent()) { if (testSnapshot != null) { final String snapshotId = testSnapshot.getId(); @@ -78,28 +78,28 @@ public class VolumeApiLiveTest extends BaseNovaApiLiveTest { } if (testVolume != null) { final String volumeId = testVolume.getId(); - assertTrue(volumeOption.get().deleteVolume(volumeId)); + assertTrue(volumeOption.get().delete(volumeId)); assertTrue(new RetryablePredicate(new Predicate() { @Override public boolean apply(VolumeApi volumeApi) { - return volumeOption.get().getVolume(volumeId) == null; + return volumeOption.get().get(volumeId) == null; } }, 180 * 1000L).apply(volumeOption.get())); } } - super.tearDown(); + super.tearDownContext(); } public void testCreateVolume() { if (volumeOption.isPresent()) { - testVolume = volumeOption.get().createVolume( + testVolume = volumeOption.get().create( 1, CreateVolumeOptions.Builder.name("jclouds-test-volume").description("description of test volume") .availabilityZone(zone)); assertTrue(new RetryablePredicate(new Predicate() { @Override public boolean apply(VolumeApi volumeApi) { - return volumeOption.get().getVolume(testVolume.getId()).getStatus() == Volume.Status.AVAILABLE; + return volumeOption.get().get(testVolume.getId()).getStatus() == Volume.Status.AVAILABLE; } }, 180 * 1000L).apply(volumeOption.get())); } @@ -108,28 +108,28 @@ public class VolumeApiLiveTest extends BaseNovaApiLiveTest { @Test(dependsOnMethods = "testCreateVolume") public void testListVolumes() { if (volumeOption.isPresent()) { - Set volumes = volumeOption.get().listVolumes(); + Set volumes = volumeOption.get().list().toImmutableSet(); assertNotNull(volumes); boolean foundIt = false; for (Volume vol : volumes) { - Volume details = volumeOption.get().getVolume(vol.getId()); + Volume details = volumeOption.get().get(vol.getId()); assertNotNull(details); if (Objects.equal(details.getId(), testVolume.getId())) { foundIt = true; } } - assertTrue(foundIt, "Failed to find the volume we created in listVolumes() response"); + assertTrue(foundIt, "Failed to find the volume we created in list() response"); } } @Test(dependsOnMethods = "testCreateVolume") public void testListVolumesInDetail() { if (volumeOption.isPresent()) { - Set volumes = volumeOption.get().listVolumesInDetail(); + Set volumes = volumeOption.get().listInDetail().toImmutableSet(); assertNotNull(volumes); boolean foundIt = false; for (Volume vol : volumes) { - Volume details = volumeOption.get().getVolume(vol.getId()); + Volume details = volumeOption.get().get(vol.getId()); assertNotNull(details); assertNotNull(details.getId()); assertNotNull(details.getCreated()); @@ -144,7 +144,7 @@ public class VolumeApiLiveTest extends BaseNovaApiLiveTest { foundIt = true; } } - assertTrue(foundIt, "Failed to find the volume we previously created in listVolumesInDetail() response"); + assertTrue(foundIt, "Failed to find the volume we previously created in listInDetail() response"); } } @@ -174,7 +174,7 @@ public class VolumeApiLiveTest extends BaseNovaApiLiveTest { @Test(dependsOnMethods = "testCreateSnapshot") public void testListSnapshots() { if (volumeOption.isPresent()) { - Set snapshots = volumeOption.get().listSnapshots(); + Set snapshots = volumeOption.get().listSnapshots().toImmutableSet(); assertNotNull(snapshots); boolean foundIt = false; for (VolumeSnapshot snap : snapshots) { @@ -193,7 +193,7 @@ public class VolumeApiLiveTest extends BaseNovaApiLiveTest { @Test(dependsOnMethods = "testCreateSnapshot") public void testListSnapshotsInDetail() { if (volumeOption.isPresent()) { - Set snapshots = volumeOption.get().listSnapshotsInDetail(); + Set snapshots = volumeOption.get().listSnapshotsInDetail().toImmutableSet(); assertNotNull(snapshots); boolean foundIt = false; for (VolumeSnapshot snap : snapshots) { @@ -225,7 +225,7 @@ public class VolumeApiLiveTest extends BaseNovaApiLiveTest { try { final String serverId = server_id = createServerInZone(zone).getId(); - Set attachments = volumeOption.get().listAttachmentsOnServer(serverId); + Set attachments = volumeOption.get().listAttachmentsOnServer(serverId).toImmutableSet(); assertNotNull(attachments); final int before = attachments.size(); @@ -241,11 +241,11 @@ public class VolumeApiLiveTest extends BaseNovaApiLiveTest { } }, 60 * 1000L).apply(volumeOption.get())); - attachments = volumeOption.get().listAttachmentsOnServer(serverId); + attachments = volumeOption.get().listAttachmentsOnServer(serverId).toImmutableSet(); assertNotNull(attachments); assertEquals(attachments.size(), before + 1); - assertEquals(volumeOption.get().getVolume(testVolume.getId()).getStatus(), Volume.Status.IN_USE); + assertEquals(volumeOption.get().get(testVolume.getId()).getStatus(), Volume.Status.IN_USE); boolean foundIt = false; for (VolumeAttachment att : attachments) { @@ -274,7 +274,7 @@ public class VolumeApiLiveTest extends BaseNovaApiLiveTest { } finally { if (server_id != null) - novaContext.getApi().getServerApiForZone(zone).deleteServer(server_id); + novaContext.getApi().getServerApiForZone(zone).delete(server_id); } } diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/VolumeTypeApiExpectTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/VolumeTypeApiExpectTest.java index a62308adac..24574ef46a 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/VolumeTypeApiExpectTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/VolumeTypeApiExpectTest.java @@ -57,7 +57,7 @@ public class VolumeTypeApiExpectTest extends BaseNovaApiExpectTest { HttpResponse.builder().statusCode(200).payload(payloadFromResource("/volume_type_list.json")).build() ).getVolumeTypeExtensionForZone("az-1.region-a.geo-1").get(); - Set types = api.listVolumeTypes(); + Set types = api.list().toImmutableSet(); assertEquals(types, ImmutableSet.of(testVolumeType())); } @@ -70,7 +70,7 @@ public class VolumeTypeApiExpectTest extends BaseNovaApiExpectTest { HttpResponse.builder().statusCode(200).payload(payloadFromResource("/volume_type.json")).build() ).getVolumeTypeExtensionForZone("az-1.region-a.geo-1").get(); - VolumeType type = api.getVolumeType("8"); + VolumeType type = api.get("8"); assertEquals(type, testVolumeType()); } @@ -83,7 +83,7 @@ public class VolumeTypeApiExpectTest extends BaseNovaApiExpectTest { HttpResponse.builder().statusCode(404).build() ).getVolumeTypeExtensionForZone("az-1.region-a.geo-1").get(); - assertNull(api.getVolumeType("8")); + assertNull(api.get("8")); } public void testCreateVolumeType() { @@ -97,7 +97,7 @@ public class VolumeTypeApiExpectTest extends BaseNovaApiExpectTest { HttpResponse.builder().statusCode(200).payload(payloadFromResource("/volume_type.json")).build() ).getVolumeTypeExtensionForZone("az-1.region-a.geo-1").get(); - VolumeType type = api.createVolumeType("jclouds-test-1"); + VolumeType type = api.create("jclouds-test-1"); assertEquals(type, testVolumeType()); } @@ -112,7 +112,7 @@ public class VolumeTypeApiExpectTest extends BaseNovaApiExpectTest { HttpResponse.builder().statusCode(200).payload(payloadFromResource("/volume_type.json")).build() ).getVolumeTypeExtensionForZone("az-1.region-a.geo-1").get(); - VolumeType type = api.createVolumeType("jclouds-test-1", CreateVolumeTypeOptions.NONE); + VolumeType type = api.create("jclouds-test-1", CreateVolumeTypeOptions.NONE); assertEquals(type, testVolumeType()); } @@ -127,7 +127,7 @@ public class VolumeTypeApiExpectTest extends BaseNovaApiExpectTest { HttpResponse.builder().statusCode(200).payload(payloadFromResource("/volume_type.json")).build() ).getVolumeTypeExtensionForZone("az-1.region-a.geo-1").get(); - VolumeType type = api.createVolumeType("jclouds-test-1", CreateVolumeTypeOptions.Builder.specs(ImmutableMap.of("x", "y"))); + VolumeType type = api.create("jclouds-test-1", CreateVolumeTypeOptions.Builder.specs(ImmutableMap.of("x", "y"))); assertEquals(type, testVolumeType()); } @@ -140,7 +140,7 @@ public class VolumeTypeApiExpectTest extends BaseNovaApiExpectTest { HttpResponse.builder().statusCode(200).build() ).getVolumeTypeExtensionForZone("az-1.region-a.geo-1").get(); - assertTrue(api.deleteVolumeType("8")); + assertTrue(api.delete("8")); } public void testDeleteVolumeTypeFailNotFound() { @@ -152,7 +152,7 @@ public class VolumeTypeApiExpectTest extends BaseNovaApiExpectTest { HttpResponse.builder().statusCode(404).build() ).getVolumeTypeExtensionForZone("az-1.region-a.geo-1").get(); - assertFalse(api.deleteVolumeType("8")); + assertFalse(api.delete("8")); } public void testGetAllExtraSpecs() { @@ -164,7 +164,7 @@ public class VolumeTypeApiExpectTest extends BaseNovaApiExpectTest { HttpResponse.builder().statusCode(200).payload(payloadFromResource("/volume_type_extra_specs.json")).build() ).getVolumeTypeExtensionForZone("az-1.region-a.geo-1").get(); - assertEquals(api.getAllExtraSpecs("9"), ImmutableMap.of("test", "value1")); + assertEquals(api.getExtraSpecs("9"), ImmutableMap.of("test", "value1")); } public void testGetAllExtraSpecsFailNotFound() { @@ -176,7 +176,7 @@ public class VolumeTypeApiExpectTest extends BaseNovaApiExpectTest { HttpResponse.builder().statusCode(404).build() ).getVolumeTypeExtensionForZone("az-1.region-a.geo-1").get(); - assertTrue(api.getAllExtraSpecs("9").isEmpty()); + assertTrue(api.getExtraSpecs("9").isEmpty()); } public void testSetAllExtraSpecs() { @@ -190,7 +190,7 @@ public class VolumeTypeApiExpectTest extends BaseNovaApiExpectTest { HttpResponse.builder().statusCode(200).build() ).getVolumeTypeExtensionForZone("az-1.region-a.geo-1").get(); - assertTrue(api.setAllExtraSpecs("9", ImmutableMap.of("test1", "somevalue"))); + assertTrue(api.updateExtraSpecs("9", ImmutableMap.of("test1", "somevalue"))); } public void testSetExtraSpec() { @@ -204,7 +204,7 @@ public class VolumeTypeApiExpectTest extends BaseNovaApiExpectTest { HttpResponse.builder().statusCode(200).build() ).getVolumeTypeExtensionForZone("az-1.region-a.geo-1").get(); - assertTrue(api.setExtraSpec("5", "test1", "somevalue")); + assertTrue(api.updateExtraSpec("5", "test1", "somevalue")); } public void testGetExtraSpec() { diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/VolumeTypeApiLiveTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/VolumeTypeApiLiveTest.java index 6d87e17c07..3733c4beb9 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/VolumeTypeApiLiveTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/extensions/VolumeTypeApiLiveTest.java @@ -28,7 +28,7 @@ import org.jclouds.openstack.nova.v2_0.domain.VolumeType; import org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiLiveTest; import org.jclouds.openstack.nova.v2_0.options.CreateVolumeTypeOptions; import org.jclouds.predicates.RetryablePredicate; -import org.testng.annotations.AfterGroups; +import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeGroups; import org.testng.annotations.Test; @@ -59,70 +59,71 @@ public class VolumeTypeApiLiveTest extends BaseNovaApiLiveTest { volumeTypeOption = novaContext.getApi().getVolumeTypeExtensionForZone(zone); } - @AfterGroups(groups = "live") + + @AfterClass(groups = { "integration", "live" }) @Override - protected void tearDown() { + protected void tearDownContext() { if (volumeTypeOption.isPresent()) { if (testVolumeType != null) { final String id = testVolumeType.getId(); - assertTrue(volumeTypeOption.get().deleteVolumeType(id)); + assertTrue(volumeTypeOption.get().delete(id)); assertTrue(new RetryablePredicate(new Predicate() { @Override public boolean apply(VolumeTypeApi volumeApi) { - return volumeApi.getVolumeType(id) == null; + return volumeApi.get(id) == null; } }, 5 * 1000L).apply(volumeTypeOption.get())); } } - super.tearDown(); + super.tearDownContext(); } public void testCreateVolumeType() { if (volumeTypeOption.isPresent()) { - testVolumeType = volumeTypeOption.get().createVolumeType( + testVolumeType = volumeTypeOption.get().create( "jclouds-test-1", CreateVolumeTypeOptions.Builder.specs(ImmutableMap.of("test", "value1"))); assertTrue(new RetryablePredicate(new Predicate() { @Override public boolean apply(VolumeTypeApi volumeTypeApi) { - return volumeTypeApi.getVolumeType(testVolumeType.getId()) != null; + return volumeTypeApi.get(testVolumeType.getId()) != null; } }, 180 * 1000L).apply(volumeTypeOption.get())); - assertEquals(volumeTypeOption.get().getVolumeType(testVolumeType.getId()).getName(), "jclouds-test-1"); - assertEquals(volumeTypeOption.get().getVolumeType(testVolumeType.getId()).getExtraSpecs(), ImmutableMap.of("test", "value1")); + assertEquals(volumeTypeOption.get().get(testVolumeType.getId()).getName(), "jclouds-test-1"); + assertEquals(volumeTypeOption.get().get(testVolumeType.getId()).getExtraSpecs(), ImmutableMap.of("test", "value1")); } } @Test(dependsOnMethods = "testCreateVolumeType") public void testListVolumeTypes() { if (volumeTypeOption.isPresent()) { - Set volumeTypes = volumeTypeOption.get().listVolumeTypes(); + Set volumeTypes = volumeTypeOption.get().list().toImmutableSet(); assertNotNull(volumeTypes); boolean foundIt = false; for (VolumeType vt : volumeTypes) { - VolumeType details = volumeTypeOption.get().getVolumeType(vt.getId()); + VolumeType details = volumeTypeOption.get().get(vt.getId()); assertNotNull(details); if (Objects.equal(details.getId(), testVolumeType.getId())) { foundIt = true; } } - assertTrue(foundIt, "Failed to find the volume type we created in listVolumeTypes() response"); + assertTrue(foundIt, "Failed to find the volume type we created in list() response"); } } @Test(dependsOnMethods = "testCreateVolumeType") public void testExtraSpecs() { if (volumeTypeOption.isPresent()) { - assertEquals(volumeTypeOption.get().getAllExtraSpecs(testVolumeType.getId()), ImmutableMap.of("test", "value1")); + assertEquals(volumeTypeOption.get().getExtraSpecs(testVolumeType.getId()), ImmutableMap.of("test", "value1")); assertEquals(volumeTypeOption.get().getExtraSpec(testVolumeType.getId(), "test"), "value1"); - assertTrue(volumeTypeOption.get().setAllExtraSpecs(testVolumeType.getId(), ImmutableMap.of("test1", "wibble"))); + assertTrue(volumeTypeOption.get().updateExtraSpecs(testVolumeType.getId(), ImmutableMap.of("test1", "wibble"))); } } @Test(dependsOnMethods = "testCreateVolumeType") public void testUpdateIndividualSpec() { if (volumeTypeOption.isPresent()) { - assertTrue(volumeTypeOption.get().setExtraSpec(testVolumeType.getId(), "test1", "freddy")); + assertTrue(volumeTypeOption.get().updateExtraSpec(testVolumeType.getId(), "test1", "freddy")); assertEquals(volumeTypeOption.get().getExtraSpec(testVolumeType.getId(), "test1"), "freddy"); } } diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/features/ExtensionApiExpectTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/features/ExtensionApiExpectTest.java index 12fa23a3e7..1efb9797d5 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/features/ExtensionApiExpectTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/features/ExtensionApiExpectTest.java @@ -54,9 +54,9 @@ public class ExtensionApiExpectTest extends BaseNovaApiExpectTest { NovaApi apiWhenExtensionsExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess, listExtensions, listExtensionsResponse); - assertEquals(apiWhenExtensionsExist.getConfiguredZones(), ImmutableSet.of("az-1.region-a.geo-1")); + assertEquals(apiWhenExtensionsExist.getConfiguredZones(), ImmutableSet.of("az-1.region-a.geo-1", "az-2.region-a.geo-1", "az-3.region-a.geo-1")); - assertEquals(apiWhenExtensionsExist.getExtensionApiForZone("az-1.region-a.geo-1").listExtensions().toString(), + assertEquals(apiWhenExtensionsExist.getExtensionApiForZone("az-1.region-a.geo-1").list().toString(), new ParseExtensionListTest().expected().toString()); } @@ -73,7 +73,7 @@ public class ExtensionApiExpectTest extends BaseNovaApiExpectTest { NovaApi apiWhenNoServersExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess, listExtensions, listExtensionsResponse); - assertTrue(apiWhenNoServersExist.getExtensionApiForZone("az-1.region-a.geo-1").listExtensions().isEmpty()); + assertTrue(apiWhenNoServersExist.getExtensionApiForZone("az-1.region-a.geo-1").list().isEmpty()); } // TODO: gson deserializer for Multimap @@ -92,7 +92,7 @@ public class ExtensionApiExpectTest extends BaseNovaApiExpectTest { NovaApi apiWhenExtensionsExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess, getExtension, getExtensionResponse); - assertEquals(apiWhenExtensionsExist.getExtensionApiForZone("az-1.region-a.geo-1").getExtensionByAlias("RS-PIE") + assertEquals(apiWhenExtensionsExist.getExtensionApiForZone("az-1.region-a.geo-1").get("RS-PIE") .toString(), new ParseExtensionTest().expected().toString()); } @@ -110,7 +110,7 @@ public class ExtensionApiExpectTest extends BaseNovaApiExpectTest { NovaApi apiWhenNoExtensionsExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess, getExtension, getExtensionResponse); - assertNull(apiWhenNoExtensionsExist.getExtensionApiForZone("az-1.region-a.geo-1").getExtensionByAlias("RS-PIE")); + assertNull(apiWhenNoExtensionsExist.getExtensionApiForZone("az-1.region-a.geo-1").get("RS-PIE")); } diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/features/ExtensionApiLiveTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/features/ExtensionApiLiveTest.java index 9a6d3e9b3e..2f1ef50f23 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/features/ExtensionApiLiveTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/features/ExtensionApiLiveTest.java @@ -46,7 +46,7 @@ public class ExtensionApiLiveTest extends BaseNovaApiLiveTest { public void testListExtensions() throws Exception { for (String zoneId : zones) { ExtensionApi api = novaContext.getApi().getExtensionApiForZone(zoneId); - Set response = api.listExtensions(); + Set response = api.list(); assertNotNull(response); assertFalse(response.isEmpty()); for (Extension extension : response) { @@ -69,9 +69,9 @@ public class ExtensionApiLiveTest extends BaseNovaApiLiveTest { public void testGetExtensionByAlias() throws Exception { for (String zoneId : zones) { ExtensionApi api = novaContext.getApi().getExtensionApiForZone(zoneId); - Set response = api.listExtensions(); + Set response = api.list(); for (Extension extension : response) { - Extension details = api.getExtensionByAlias(extension.getId()); + Extension details = api.get(extension.getId()); assertNotNull(details); assertEquals(details.getId(), extension.getId()); assertEquals(details.getName(), extension.getName()); diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/features/FlavorApiExpectTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/features/FlavorApiExpectTest.java index 8f2b73c3b1..e1891e5349 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/features/FlavorApiExpectTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/features/FlavorApiExpectTest.java @@ -54,9 +54,9 @@ public class FlavorApiExpectTest extends BaseNovaApiExpectTest { NovaApi apiWhenFlavorsExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess, listFlavors, listFlavorsResponse); - assertEquals(apiWhenFlavorsExist.getConfiguredZones(), ImmutableSet.of("az-1.region-a.geo-1")); + assertEquals(apiWhenFlavorsExist.getConfiguredZones(), ImmutableSet.of("az-1.region-a.geo-1", "az-2.region-a.geo-1", "az-3.region-a.geo-1")); - assertEquals(apiWhenFlavorsExist.getFlavorApiForZone("az-1.region-a.geo-1").listFlavors().toString(), + assertEquals(apiWhenFlavorsExist.getFlavorApiForZone("az-1.region-a.geo-1").list().concat().toString(), new ParseFlavorListTest().expected().toString()); } @@ -73,7 +73,7 @@ public class FlavorApiExpectTest extends BaseNovaApiExpectTest { NovaApi apiWhenNoServersExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess, listFlavors, listFlavorsResponse); - assertTrue(apiWhenNoServersExist.getFlavorApiForZone("az-1.region-a.geo-1").listFlavors().isEmpty()); + assertTrue(apiWhenNoServersExist.getFlavorApiForZone("az-1.region-a.geo-1").list().concat().isEmpty()); } // TODO: gson deserializer for Multimap @@ -93,7 +93,7 @@ public class FlavorApiExpectTest extends BaseNovaApiExpectTest { responseWithKeystoneAccess, getFlavor, getFlavorResponse); assertEquals( - apiWhenFlavorsExist.getFlavorApiForZone("az-1.region-a.geo-1").getFlavor("52415800-8b69-11e0-9b19-734f1195ff37") + apiWhenFlavorsExist.getFlavorApiForZone("az-1.region-a.geo-1").get("52415800-8b69-11e0-9b19-734f1195ff37") .toString(), new ParseFlavorTest().expected().toString()); } @@ -111,7 +111,7 @@ public class FlavorApiExpectTest extends BaseNovaApiExpectTest { NovaApi apiWhenNoFlavorsExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess, getFlavor, getFlavorResponse); - assertNull(apiWhenNoFlavorsExist.getFlavorApiForZone("az-1.region-a.geo-1").getFlavor("123")); + assertNull(apiWhenNoFlavorsExist.getFlavorApiForZone("az-1.region-a.geo-1").get("123")); } diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/features/FlavorApiLiveTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/features/FlavorApiLiveTest.java index 6dbdb99330..a45e6bfce4 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/features/FlavorApiLiveTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/features/FlavorApiLiveTest.java @@ -47,7 +47,7 @@ public class FlavorApiLiveTest extends BaseNovaApiLiveTest { public void testListFlavors() throws Exception { for (String zoneId : zones) { FlavorApi api = novaContext.getApi().getFlavorApiForZone(zoneId); - Set response = api.listFlavors(); + Set response = api.list().concat().toImmutableSet(); assertNotNull(response); assertFalse(response.isEmpty()); for (Resource flavor : response) { @@ -67,7 +67,7 @@ public class FlavorApiLiveTest extends BaseNovaApiLiveTest { public void testListFlavorsInDetail() throws Exception { for (String zoneId : zones) { FlavorApi api = novaContext.getApi().getFlavorApiForZone(zoneId); - Set response = api.listFlavorsInDetail(); + Set response = api.listInDetail().concat().toImmutableSet(); assertNotNull(response); assertFalse(response.isEmpty()); for (Flavor flavor : response) { @@ -90,9 +90,9 @@ public class FlavorApiLiveTest extends BaseNovaApiLiveTest { public void testGetFlavorById() throws Exception { for (String zoneId : zones) { FlavorApi api = novaContext.getApi().getFlavorApiForZone(zoneId); - Set response = api.listFlavorsInDetail(); + Set response = api.listInDetail().concat().toImmutableSet(); for (Flavor flavor : response) { - Flavor details = api.getFlavor(flavor.getId()); + Flavor details = api.get(flavor.getId()); assertNotNull(details); assertEquals(details.getId(), flavor.getId()); assertEquals(details.getName(), flavor.getName()); diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/features/ImageApiExpectTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/features/ImageApiExpectTest.java index 2b3768bcf8..945ff05d18 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/features/ImageApiExpectTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/features/ImageApiExpectTest.java @@ -21,6 +21,7 @@ package org.jclouds.openstack.nova.v2_0.features; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; +import static org.testng.Assert.fail; import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpResponse; @@ -28,8 +29,11 @@ import org.jclouds.openstack.nova.v2_0.NovaApi; import org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiExpectTest; import org.jclouds.openstack.nova.v2_0.parse.ParseImageListTest; import org.jclouds.openstack.nova.v2_0.parse.ParseImageTest; +import org.jclouds.openstack.nova.v2_0.parse.ParseMetadataListTest; +import org.jclouds.openstack.nova.v2_0.parse.ParseMetadataUpdateTest; import org.testng.annotations.Test; +import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; /** @@ -40,39 +44,39 @@ import com.google.common.collect.ImmutableSet; @Test(groups = "unit", testName = "ImageAsyncApiTest") public class ImageApiExpectTest extends BaseNovaApiExpectTest { public void testListImagesWhenResponseIs2xx() throws Exception { - HttpRequest listImages = HttpRequest + HttpRequest list = HttpRequest .builder() .method("GET") .endpoint("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/images") .addHeader("Accept", "application/json") .addHeader("X-Auth-Token", authToken).build(); - HttpResponse listImagesResponse = HttpResponse.builder().statusCode(200) + HttpResponse listResponse = HttpResponse.builder().statusCode(200) .payload(payloadFromResource("/image_list.json")).build(); NovaApi apiWhenImagesExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, - responseWithKeystoneAccess, listImages, listImagesResponse); + responseWithKeystoneAccess, list, listResponse); - assertEquals(apiWhenImagesExist.getConfiguredZones(), ImmutableSet.of("az-1.region-a.geo-1")); + assertEquals(apiWhenImagesExist.getConfiguredZones(), ImmutableSet.of("az-1.region-a.geo-1", "az-2.region-a.geo-1", "az-3.region-a.geo-1")); - assertEquals(apiWhenImagesExist.getImageApiForZone("az-1.region-a.geo-1").listImages().toString(), + assertEquals(apiWhenImagesExist.getImageApiForZone("az-1.region-a.geo-1").list().concat().toString(), new ParseImageListTest().expected().toString()); } public void testListImagesWhenReponseIs404IsEmpty() throws Exception { - HttpRequest listImages = HttpRequest + HttpRequest list = HttpRequest .builder() .method("GET") .endpoint("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/images") .addHeader("Accept", "application/json") .addHeader("X-Auth-Token", authToken).build(); - HttpResponse listImagesResponse = HttpResponse.builder().statusCode(404).build(); + HttpResponse listResponse = HttpResponse.builder().statusCode(404).build(); NovaApi apiWhenNoServersExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, - responseWithKeystoneAccess, listImages, listImagesResponse); + responseWithKeystoneAccess, list, listResponse); - assertTrue(apiWhenNoServersExist.getImageApiForZone("az-1.region-a.geo-1").listImages().isEmpty()); + assertTrue(apiWhenNoServersExist.getImageApiForZone("az-1.region-a.geo-1").list().concat().isEmpty()); } public void testGetImageWhenResponseIs2xx() throws Exception { @@ -91,7 +95,7 @@ public class ImageApiExpectTest extends BaseNovaApiExpectTest { responseWithKeystoneAccess, getImage, getImageResponse); assertEquals( - apiWhenImagesExist.getImageApiForZone("az-1.region-a.geo-1").getImage("52415800-8b69-11e0-9b19-734f5736d2a2") + apiWhenImagesExist.getImageApiForZone("az-1.region-a.geo-1").get("52415800-8b69-11e0-9b19-734f5736d2a2") .toString(), new ParseImageTest().expected().toString()); } @@ -108,9 +112,268 @@ public class ImageApiExpectTest extends BaseNovaApiExpectTest { NovaApi apiWhenNoImagesExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess, getImage, getImageResponse); - assertNull(apiWhenNoImagesExist.getImageApiForZone("az-1.region-a.geo-1").getImage( + assertNull(apiWhenNoImagesExist.getImageApiForZone("az-1.region-a.geo-1").get( "52415800-8b69-11e0-9b19-734f5736d2a2")); } + public void testListMetadataWhenResponseIs2xx() throws Exception { + String imageId = "52415800-8b69-11e0-9b19-734f5736d2a2"; + HttpRequest getMetadata = HttpRequest + .builder() + .method("GET") + .endpoint("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/images/" + imageId + "/metadata") + .addHeader("Accept", "application/json") + .addHeader("X-Auth-Token", authToken).build(); + + HttpResponse getMetadataResponse = HttpResponse.builder().statusCode(200) + .payload(payloadFromResource("/metadata_list.json")).build(); + + NovaApi apiWhenServerExists = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, + responseWithKeystoneAccess, getMetadata, getMetadataResponse); + + assertEquals(apiWhenServerExists.getImageApiForZone("az-1.region-a.geo-1").getMetadata(imageId).toString(), + new ParseMetadataListTest().expected().toString()); + } + + public void testListMetadataWhenResponseIs404() throws Exception { + String imageId = "52415800-8b69-11e0-9b19-734f5736d2a2"; + HttpRequest getMetadata = HttpRequest + .builder() + .method("GET") + .endpoint("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/images/" + imageId + "/metadata") + .addHeader("Accept", "*/*") + .addHeader("X-Auth-Token", authToken) + .build(); + + HttpResponse getMetadataResponse = HttpResponse.builder().statusCode(404).build(); + + NovaApi apiWhenServerExists = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, + responseWithKeystoneAccess, getMetadata, getMetadataResponse); + + try { + apiWhenServerExists.getImageApiForZone("az-1.region-a.geo-1").getMetadata(imageId); + fail("Expected an exception."); + } catch (Exception e) { + ; + } + } + + public void testSetMetadataWhenResponseIs2xx() throws Exception { + String imageId = "52415800-8b69-11e0-9b19-734f5736d2a2"; + ImmutableMap metadata = new ImmutableMap.Builder() + .put("Server Label", "Web Head 1") + .put("Image Version", "2.1") + .build(); + + HttpRequest setMetadata = HttpRequest + .builder() + .method("PUT") + .endpoint("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/images/" + imageId + "/metadata") + .addHeader("Accept", "application/json") + .addHeader("X-Auth-Token", authToken) + .payload(payloadFromStringWithContentType("{\"metadata\":{\"Server Label\":\"Web Head 1\",\"Image Version\":\"2.1\"}}","application/json")) + .build(); + + HttpResponse setMetadataResponse = HttpResponse.builder().statusCode(200) + .payload(payloadFromResource("/metadata_list.json")).build(); + + NovaApi apiWhenImageExists = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, + responseWithKeystoneAccess, setMetadata, setMetadataResponse); + + assertEquals(apiWhenImageExists.getImageApiForZone("az-1.region-a.geo-1").setMetadata(imageId, metadata).toString(), + new ParseMetadataListTest().expected().toString()); + } + + public void testSetMetadataWhenResponseIs404() throws Exception { + String imageId = "52415800-8b69-11e0-9b19-734f5736d2a2"; + ImmutableMap metadata = new ImmutableMap.Builder() + .put("Server Label", "Web Head 1") + .put("Image Version", "2.1") + .build(); + + HttpRequest setMetadata = HttpRequest + .builder() + .method("PUT") + .endpoint("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/images/" +imageId + "/metadata") + .addHeader("Accept", "*/*") + .addHeader("X-Auth-Token", authToken) + .payload(payloadFromStringWithContentType("{\"metadata\":{\"Server Label\":\"Web Head 1\",\"Image Version\":\"2.1\"}}","application/json")) + .build(); + + HttpResponse setMetadataResponse = HttpResponse.builder().statusCode(404).build(); + + NovaApi apiWhenServerExists = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, + responseWithKeystoneAccess, setMetadata, setMetadataResponse); + + try { + apiWhenServerExists.getImageApiForZone("az-1.region-a.geo-1").setMetadata(imageId, metadata); + fail("Expected an exception."); + } catch (Exception e) { + ; + } + } + + public void testUpdateMetadataWhenResponseIs2xx() throws Exception { + String imageId = "52415800-8b69-11e0-9b19-734f5736d2a2"; + ImmutableMap metadata = new ImmutableMap.Builder() + .put("Server Label", "Web Head 2") + .put("Server Description", "Simple Server") + .build(); + + HttpRequest setMetadata = HttpRequest + .builder() + .method("POST") + .endpoint("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/images/" + imageId + "/metadata") + .addHeader("Accept", "application/json") + .addHeader("X-Auth-Token", authToken) + .payload(payloadFromStringWithContentType("{\"metadata\":{\"Server Label\":\"Web Head 2\",\"Server Description\":\"Simple Server\"}}","application/json")) + .build(); + + HttpResponse setMetadataResponse = HttpResponse.builder().statusCode(200) + .payload(payloadFromResource("/metadata_updated.json")).build(); + + NovaApi apiWhenServerExists = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, + responseWithKeystoneAccess, setMetadata, setMetadataResponse); + + assertEquals(apiWhenServerExists.getImageApiForZone("az-1.region-a.geo-1").updateMetadata(imageId, metadata).toString(), + new ParseMetadataUpdateTest().expected().toString()); + } + + public void testUpdateMetadataWhenResponseIs404() throws Exception { + String imageId = "52415800-8b69-11e0-9b19-734f5736d2a2"; + ImmutableMap metadata = new ImmutableMap.Builder() + .put("Server Label", "Web Head 2") + .put("Server Description", "Simple Server") + .build(); + + HttpRequest setMetadata = HttpRequest + .builder() + .method("POST") + .endpoint("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/servers/" + imageId + "/metadata") + .addHeader("Accept", "application/json") + .addHeader("X-Auth-Token", authToken) + .payload(payloadFromStringWithContentType("{\"metadata\":{\"Server Label\":\"Web Head 2\",\"Server Description\":\"Simple Server\"}}","application/json")) + .build(); + + HttpResponse setMetadataResponse = HttpResponse.builder().statusCode(404) + .payload(payloadFromResource("/metadata_updated.json")).build(); + + NovaApi apiWhenServerExists = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, + responseWithKeystoneAccess, setMetadata, setMetadataResponse); + + try { + apiWhenServerExists.getImageApiForZone("az-1.region-a.geo-1").setMetadata(imageId, metadata); + fail("Expected an exception."); + } catch (Exception e) { + ; + } + } + + public void testGetMetadataItemWhenResponseIs2xx() throws Exception { + String imageId = "52415800-8b69-11e0-9b19-734f5736d2a2"; + String key = "Image%20Version"; + + HttpRequest getMetadata = HttpRequest + .builder() + .method("GET") + .endpoint("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/images/" + imageId + "/metadata/" + key) + .addHeader("Accept", "application/json") + .addHeader("X-Auth-Token", authToken) + .build(); + + HttpResponse getMetadataResponse = HttpResponse.builder().statusCode(200) + .payload(payloadFromString("{\"metadata\":{\"Image Version\":\"2.5\"}}")).build(); + + NovaApi apiWhenServerExists = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, + responseWithKeystoneAccess, getMetadata, getMetadataResponse); + + assertEquals(apiWhenServerExists.getImageApiForZone("az-1.region-a.geo-1").getMetadata(imageId, "Image Version").toString(), + "2.5"); + } + + public void testGetMetadataItemWhenResponseIs404() throws Exception { + String imageId = "52415800-8b69-11e0-9b19-734f5736d2a2"; + String key = "Image%20Version"; + + HttpRequest getMetadata = HttpRequest + .builder() + .method("GET") + .endpoint("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/images/" + imageId + "/metadata/" + key) + .addHeader("Accept", "application/json") + .addHeader("X-Auth-Token", authToken) + .build(); + + HttpResponse getMetadataResponse = HttpResponse.builder().statusCode(404) + .payload(payloadFromStringWithContentType("{\"metadata\":{\"Image Version\":\"2.5\"}}", "application/json")).build(); + + NovaApi apiWhenImageExists = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, + responseWithKeystoneAccess, getMetadata, getMetadataResponse); + + assertNull(apiWhenImageExists.getImageApiForZone("az-1.region-a.geo-1").getMetadata(imageId, key)); + } + + public void testSetMetadataItemWhenResponseIs2xx() throws Exception { + String imageId = "52415800-8b69-11e0-9b19-734f5736d2a2"; + String key = "Image Version"; + + HttpRequest updateMetadata = HttpRequest + .builder() + .method("PUT") + .endpoint("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/images/" + imageId + "/metadata/" + "Image%20Version") + .addHeader("Accept", "application/json") + .addHeader("X-Auth-Token", authToken) + .payload(payloadFromStringWithContentType("{\"metadata\":{\"Image Version\":\"2.5\"}}", "application/json")) + .build(); + + HttpResponse updateMetadataResponse = HttpResponse.builder().statusCode(200) + .payload(payloadFromStringWithContentType("{\"metadata\":{\"Image Version\":\"2.5\"}}", "application/json")).build(); + + NovaApi apiWhenServerExists = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, + responseWithKeystoneAccess, updateMetadata, updateMetadataResponse); + + assertEquals(apiWhenServerExists.getImageApiForZone("az-1.region-a.geo-1").updateMetadata(imageId, key, "2.5").toString(), + "2.5"); + } + + public void testDeleteMetadataItemWhenResponseIs2xx() throws Exception { + String imageId = "52415800-8b69-11e0-9b19-734f5736d2a2"; + String key = "Image%20Version"; + + HttpRequest deleteMetadata = HttpRequest + .builder() + .method("DELETE") + .endpoint("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/images/" + imageId + "/metadata/" + key) + .addHeader("Accept", "*/*") + .addHeader("X-Auth-Token", authToken) + .build(); + + HttpResponse deleteMetadataResponse = HttpResponse.builder().statusCode(204).build(); + + NovaApi apiWhenImageExists = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, + responseWithKeystoneAccess, deleteMetadata, deleteMetadataResponse); + + apiWhenImageExists.getImageApiForZone("az-1.region-a.geo-1").deleteMetadata(imageId, key); + } + + public void testDeleteMetadataItemWhenResponseIs404() throws Exception { + String imageId = "52415800-8b69-11e0-9b19-734f5736d2a2"; + String key = "Image%20Version"; + + HttpRequest deleteMetadata = HttpRequest + .builder() + .method("DELETE") + .endpoint("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/images/" + imageId + "/metadata/" + key) + .addHeader("Accept", "*/*") + .addHeader("X-Auth-Token", authToken) + .build(); + + HttpResponse deleteMetadataResponse = HttpResponse.builder().statusCode(404).build(); + + NovaApi apiWhenImageExists = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, + responseWithKeystoneAccess, deleteMetadata, deleteMetadataResponse); + + apiWhenImageExists.getImageApiForZone("az-1.region-a.geo-1").deleteMetadata(imageId, key); + + } } diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/features/ImageApiLiveTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/features/ImageApiLiveTest.java index 7f9bc2b50d..678115aa6c 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/features/ImageApiLiveTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/features/ImageApiLiveTest.java @@ -42,7 +42,7 @@ public class ImageApiLiveTest extends BaseNovaApiLiveTest { public void testListImages() throws Exception { for (String zoneId : zones) { ImageApi api = novaContext.getApi().getImageApiForZone(zoneId); - Set response = api.listImages(); + Set response = api.list().concat().toImmutableSet(); assertNotNull(response); assertFalse(response.isEmpty()); for (Resource image : response) { @@ -57,7 +57,7 @@ public class ImageApiLiveTest extends BaseNovaApiLiveTest { public void testListImagesInDetail() throws Exception { for (String zoneId : novaContext.getApi().getConfiguredZones()) { ImageApi api = novaContext.getApi().getImageApiForZone(zoneId); - Set response = api.listImagesInDetail(); + Set response = api.listInDetail().concat().toImmutableSet(); assertNotNull(response); assertFalse(response.isEmpty()); for (Image image : response) { @@ -65,14 +65,14 @@ public class ImageApiLiveTest extends BaseNovaApiLiveTest { assertNotNull(image.getName()); assertNotNull(image.getLinks()); assertNotNull(image.getCreated()); - assertTrue(image.getMinDisk() > 0); - assertTrue(image.getMinRam() > 0); + // image.getMinDisk() can be zero + // image.getMinRam() can be zero assertTrue(image.getProgress() >= 0 && image.getProgress() <= 100); assertNotNull(image.getStatus()); - assertNotNull(image.getServer()); - assertNotNull(image.getTenantId()); - assertNotNull(image.getUpdated()); - assertNotNull(image.getUserId()); + // image.getServer() can be null + // image.getTenantId() can be null + // image.getUpdated() can be null + // image.getUserId() can be null } } } @@ -81,9 +81,9 @@ public class ImageApiLiveTest extends BaseNovaApiLiveTest { public void testGetImageById() throws Exception { for (String zoneId : novaContext.getApi().getConfiguredZones()) { ImageApi api = novaContext.getApi().getImageApiForZone(zoneId); - Set response = api.listImagesInDetail(); + Set response = api.listInDetail().concat().toImmutableSet(); for (Image image : response) { - Image details = api.getImage(image.getId()); + Image details = api.get(image.getId()); assertNotNull(details); assertEquals(details.getId(), image.getId()); assertEquals(details.getName(), image.getName()); diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/features/ServerApiExpectTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/features/ServerApiExpectTest.java index 897ee0192b..6c36540257 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/features/ServerApiExpectTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/features/ServerApiExpectTest.java @@ -28,9 +28,12 @@ import org.jclouds.openstack.nova.v2_0.NovaApi; import org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiExpectTest; import org.jclouds.openstack.nova.v2_0.options.CreateServerOptions; import org.jclouds.openstack.nova.v2_0.parse.ParseCreatedServerTest; +import org.jclouds.openstack.nova.v2_0.parse.ParseMetadataListTest; +import org.jclouds.openstack.nova.v2_0.parse.ParseMetadataUpdateTest; import org.jclouds.openstack.nova.v2_0.parse.ParseServerListTest; import org.testng.annotations.Test; +import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.ImmutableSet; @@ -56,9 +59,9 @@ public class ServerApiExpectTest extends BaseNovaApiExpectTest { NovaApi apiWhenServersExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess, listServers, listServersResponse); - assertEquals(apiWhenServersExist.getConfiguredZones(), ImmutableSet.of("az-1.region-a.geo-1")); + assertEquals(apiWhenServersExist.getConfiguredZones(), ImmutableSet.of("az-1.region-a.geo-1", "az-2.region-a.geo-1", "az-3.region-a.geo-1")); - assertEquals(apiWhenServersExist.getServerApiForZone("az-1.region-a.geo-1").listServers().toString(), + assertEquals(apiWhenServersExist.getServerApiForZone("az-1.region-a.geo-1").list().concat().toString(), new ParseServerListTest().expected().toString()); } @@ -75,7 +78,7 @@ public class ServerApiExpectTest extends BaseNovaApiExpectTest { NovaApi apiWhenNoServersExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess, listServers, listServersResponse); - assertTrue(apiWhenNoServersExist.getServerApiForZone("az-1.region-a.geo-1").listServers().isEmpty()); + assertTrue(apiWhenNoServersExist.getServerApiForZone("az-1.region-a.geo-1").list().concat().isEmpty()); } public void testCreateServerWhenResponseIs202() throws Exception { @@ -96,7 +99,7 @@ public class ServerApiExpectTest extends BaseNovaApiExpectTest { NovaApi apiWithNewServer = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess, createServer, createServerResponse); - assertEquals(apiWithNewServer.getServerApiForZone("az-1.region-a.geo-1").createServer("test-e92", "1241", "100").toString(), + assertEquals(apiWithNewServer.getServerApiForZone("az-1.region-a.geo-1").create("test-e92", "1241", "100").toString(), new ParseCreatedServerTest().expected().toString()); } @@ -120,7 +123,7 @@ public class ServerApiExpectTest extends BaseNovaApiExpectTest { NovaApi apiWithNewServer = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess, createServer, createServerResponse); - assertEquals(apiWithNewServer.getServerApiForZone("az-1.region-a.geo-1").createServer("test-e92", "1241", + assertEquals(apiWithNewServer.getServerApiForZone("az-1.region-a.geo-1").create("test-e92", "1241", "100", new CreateServerOptions().securityGroupNames("group1", "group2")).toString(), new ParseCreatedServerTest().expected().toString()); } @@ -196,7 +199,7 @@ public class ServerApiExpectTest extends BaseNovaApiExpectTest { NovaApi apiWhenServerExists = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess, stopServer, stopServerResponse); - apiWhenServerExists.getServerApiForZone("az-1.region-a.geo-1").stopServer(serverId); + apiWhenServerExists.getServerApiForZone("az-1.region-a.geo-1").stop(serverId); } public void testStopServerWhenResponseIs404() throws Exception { @@ -218,7 +221,7 @@ public class ServerApiExpectTest extends BaseNovaApiExpectTest { responseWithKeystoneAccess, stopServer, stopServerResponse); try { - apiWhenServerExists.getServerApiForZone("az-1.region-a.geo-1").stopServer(serverId); + apiWhenServerExists.getServerApiForZone("az-1.region-a.geo-1").stop(serverId); fail("Expected an exception."); } catch (Exception e) { ; @@ -243,7 +246,7 @@ public class ServerApiExpectTest extends BaseNovaApiExpectTest { NovaApi apiWhenServerExists = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess, startServer, startServerResponse); - apiWhenServerExists.getServerApiForZone("az-1.region-a.geo-1").startServer(serverId); + apiWhenServerExists.getServerApiForZone("az-1.region-a.geo-1").start(serverId); } public void testStartServerWhenResponseIs404() throws Exception { @@ -264,11 +267,314 @@ public class ServerApiExpectTest extends BaseNovaApiExpectTest { responseWithKeystoneAccess, startServer, startServerResponse); try { - apiWhenServerExists.getServerApiForZone("az-1.region-a.geo-1").startServer(serverId); + apiWhenServerExists.getServerApiForZone("az-1.region-a.geo-1").start(serverId); fail("Expected an exception."); } catch (Exception e) { ; } } + public void testListMetadataWhenResponseIs2xx() throws Exception { + String serverId = "123"; + + HttpRequest getMetadata = HttpRequest + .builder() + .method("GET") + .endpoint("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/servers/" + serverId + "/metadata") + .addHeader("Accept", "application/json") + .addHeader("X-Auth-Token", authToken).build(); + + HttpResponse getMetadataResponse = HttpResponse.builder().statusCode(200) + .payload(payloadFromResource("/metadata_list.json")).build(); + + + NovaApi apiWhenServerExists = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, + responseWithKeystoneAccess, getMetadata, getMetadataResponse); + + assertEquals(apiWhenServerExists.getServerApiForZone("az-1.region-a.geo-1").getMetadata(serverId).toString(), + new ParseMetadataListTest().expected().toString()); + } + + public void testListMetadataWhenResponseIs404() throws Exception { + String serverId = "123"; + HttpRequest getMetadata = HttpRequest + .builder() + .method("GET") + .endpoint("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/servers/" + serverId + "/metadata") + .addHeader("Accept", "*/*") + .addHeader("X-Auth-Token", authToken) + .build(); + + HttpResponse getMetadataResponse = HttpResponse.builder().statusCode(404).build(); + + NovaApi apiWhenServerExists = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, + responseWithKeystoneAccess, getMetadata, getMetadataResponse); + + try { + apiWhenServerExists.getServerApiForZone("az-1.region-a.geo-1").getMetadata(serverId); + fail("Expected an exception."); + } catch (Exception e) { + ; + } + } + + public void testSetMetadataWhenResponseIs2xx() throws Exception { + String serverId = "123"; + ImmutableMap metadata = new ImmutableMap.Builder() + .put("Server Label", "Web Head 1") + .put("Image Version", "2.1") + .build(); + + HttpRequest setMetadata = HttpRequest + .builder() + .method("PUT") + .endpoint("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/servers/" + serverId + "/metadata") + .addHeader("Accept", "application/json") + .addHeader("X-Auth-Token", authToken) + .payload(payloadFromStringWithContentType("{\"metadata\":{\"Server Label\":\"Web Head 1\",\"Image Version\":\"2.1\"}}","application/json")) + .build(); + + HttpResponse setMetadataResponse = HttpResponse.builder().statusCode(200) + .payload(payloadFromResource("/metadata_list.json")).build(); + + NovaApi apiWhenServerExists = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, + responseWithKeystoneAccess, setMetadata, setMetadataResponse); + + assertEquals(apiWhenServerExists.getServerApiForZone("az-1.region-a.geo-1").setMetadata(serverId, metadata).toString(), + new ParseMetadataListTest().expected().toString()); + } + + public void testSetMetadataWhenResponseIs404() throws Exception { + String serverId = "123"; + ImmutableMap metadata = new ImmutableMap.Builder() + .put("Server Label", "Web Head 1") + .put("Image Version", "2.1") + .build(); + + HttpRequest setMetadata = HttpRequest + .builder() + .method("PUT") + .endpoint("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/servers/" + serverId + "/metadata") + .addHeader("Accept", "*/*") + .addHeader("X-Auth-Token", authToken) + .payload(payloadFromStringWithContentType("{\"metadata\":{\"Server Label\":\"Web Head 1\",\"Image Version\":\"2.1\"}}","application/json")) + .build(); + + HttpResponse setMetadataResponse = HttpResponse.builder().statusCode(404).build(); + + NovaApi apiWhenServerExists = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, + responseWithKeystoneAccess, setMetadata, setMetadataResponse); + + try { + apiWhenServerExists.getServerApiForZone("az-1.region-a.geo-1").setMetadata(serverId, metadata); + fail("Expected an exception."); + } catch (Exception e) { + ; + } + } + + public void testUpdateMetadataWhenResponseIs2xx() throws Exception { + String serverId = "123"; + ImmutableMap metadata = new ImmutableMap.Builder() + .put("Server Label", "Web Head 2") + .put("Server Description", "Simple Server") + .build(); + + HttpRequest setMetadata = HttpRequest + .builder() + .method("POST") + .endpoint("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/servers/" + serverId + "/metadata") + .addHeader("Accept", "application/json") + .addHeader("X-Auth-Token", authToken) + .payload(payloadFromStringWithContentType("{\"metadata\":{\"Server Label\":\"Web Head 2\",\"Server Description\":\"Simple Server\"}}","application/json")) + .build(); + + HttpResponse setMetadataResponse = HttpResponse.builder().statusCode(200) + .payload(payloadFromResource("/metadata_updated.json")).build(); + + NovaApi apiWhenServerExists = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, + responseWithKeystoneAccess, setMetadata, setMetadataResponse); + + assertEquals(apiWhenServerExists.getServerApiForZone("az-1.region-a.geo-1").updateMetadata(serverId, metadata).toString(), + new ParseMetadataUpdateTest().expected().toString()); + } + + public void testUpdateMetadataWhenResponseIs404() throws Exception { + String serverId = "123"; + ImmutableMap metadata = new ImmutableMap.Builder() + .put("Server Label", "Web Head 2") + .put("Server Description", "Simple Server") + .build(); + + HttpRequest setMetadata = HttpRequest + .builder() + .method("POST") + .endpoint("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/servers/" + serverId + "/metadata") + .addHeader("Accept", "application/json") + .addHeader("X-Auth-Token", authToken) + .payload(payloadFromStringWithContentType("{\"metadata\":{\"Server Label\":\"Web Head 2\",\"Server Description\":\"Simple Server\"}}","application/json")) + .build(); + + HttpResponse setMetadataResponse = HttpResponse.builder().statusCode(404) + .payload(payloadFromResource("/metadata_updated.json")).build(); + + NovaApi apiWhenServerExists = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, + responseWithKeystoneAccess, setMetadata, setMetadataResponse); + + try { + apiWhenServerExists.getServerApiForZone("az-1.region-a.geo-1").setMetadata(serverId, metadata); + fail("Expected an exception."); + } catch (Exception e) { + ; + } + } + + public void testGetMetadataItemWhenResponseIs2xx() throws Exception { + String serverId = "123"; + String key = "Server Label"; + + HttpRequest getMetadata = HttpRequest + .builder() + .method("GET") + .endpoint("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/servers/" + serverId + "/metadata/" + "Server%20Label") + .addHeader("Accept", "application/json") + .addHeader("X-Auth-Token", authToken) + .build(); + + HttpResponse getMetadataResponse = HttpResponse.builder().statusCode(200) + .payload(payloadFromResource("/metadata_item.json")).build(); + + NovaApi apiWhenServerExists = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, + responseWithKeystoneAccess, getMetadata, getMetadataResponse); + + assertEquals(apiWhenServerExists.getServerApiForZone("az-1.region-a.geo-1").getMetadata(serverId, key).toString(), + "Web Head 1"); + } + + public void testGetMetadataItemWhenResponseIs404() throws Exception { + String serverId = "123"; + ImmutableMap metadata = new ImmutableMap.Builder() + .put("Server Label", "Web Head 1") + .build(); + + HttpRequest setMetadata = HttpRequest + .builder() + .method("GET") + .endpoint("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/servers/" + serverId + "/metadata") + .addHeader("Accept", "application/json") + .addHeader("X-Auth-Token", authToken) + .payload(payloadFromStringWithContentType("{\"metadata\":{\"Server Label\":\"Web Head 2\",\"Server Description\":\"Simple Server\"}}","application/json")) + .build(); + + HttpResponse setMetadataResponse = HttpResponse.builder().statusCode(404) + .payload(payloadFromResource("/metadata_updated.json")).build(); + + NovaApi apiWhenServerExists = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, + responseWithKeystoneAccess, setMetadata, setMetadataResponse); + + try { + apiWhenServerExists.getServerApiForZone("az-1.region-a.geo-1").setMetadata(serverId, metadata); + fail("Expected an exception."); + } catch (Exception e) { + ; + } + } + + public void testSetMetadataItemWhenResponseIs2xx() throws Exception { + String serverId = "123"; + ImmutableMap metadata = new ImmutableMap.Builder() + .put("Server Label", "Web Head 2") + .put("Server Description", "Simple Server") + .build(); + + HttpRequest setMetadata = HttpRequest + .builder() + .method("POST") + .endpoint("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/servers/" + serverId + "/metadata") + .addHeader("Accept", "application/json") + .addHeader("X-Auth-Token", authToken) + .payload(payloadFromStringWithContentType("{\"metadata\":{\"Server Label\":\"Web Head 2\",\"Server Description\":\"Simple Server\"}}","application/json")) + .build(); + + HttpResponse setMetadataResponse = HttpResponse.builder().statusCode(200) + .payload(payloadFromResource("/metadata_updated.json")).build(); + + NovaApi apiWhenServerExists = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, + responseWithKeystoneAccess, setMetadata, setMetadataResponse); + + assertEquals(apiWhenServerExists.getServerApiForZone("az-1.region-a.geo-1").updateMetadata(serverId, metadata).toString(), + new ParseMetadataUpdateTest().expected().toString()); + } + + public void testSetMetadataItemWhenResponseIs404() throws Exception { + String serverId = "123"; + ImmutableMap metadata = new ImmutableMap.Builder() + .put("Server Label", "Web Head 2") + .put("Server Description", "Simple Server") + .build(); + + HttpRequest setMetadata = HttpRequest + .builder() + .method("POST") + .endpoint("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/servers/" + serverId + "/metadata") + .addHeader("Accept", "application/json") + .addHeader("X-Auth-Token", authToken) + .payload(payloadFromStringWithContentType("{\"metadata\":{\"Server Label\":\"Web Head 2\",\"Server Description\":\"Simple Server\"}}","application/json")) + .build(); + + HttpResponse setMetadataResponse = HttpResponse.builder().statusCode(404) + .payload(payloadFromResource("/metadata_updated.json")).build(); + + NovaApi apiWhenServerExists = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, + responseWithKeystoneAccess, setMetadata, setMetadataResponse); + + try { + apiWhenServerExists.getServerApiForZone("az-1.region-a.geo-1").setMetadata(serverId, metadata); + fail("Expected an exception."); + } catch (Exception e) { + ; + } + } + + public void testDeleteMetadataItemWhenResponseIs2xx() throws Exception { + String serverId = "123"; + String key = "Server%20Label"; + + HttpRequest updateMetadata = HttpRequest + .builder() + .method("DELETE") + .endpoint("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/servers/" + serverId + "/metadata/" + key) + .addHeader("Accept", "*/*") + .addHeader("X-Auth-Token", authToken) + .build(); + + HttpResponse updateMetadataResponse = HttpResponse.builder().statusCode(204).build(); + + NovaApi apiWhenServerExists = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, + responseWithKeystoneAccess, updateMetadata, updateMetadataResponse); + + apiWhenServerExists.getServerApiForZone("az-1.region-a.geo-1").deleteMetadata(serverId, key); + + } + + public void testDeleteMetadataItemWhenResponseIs404() throws Exception { + String serverId = "123"; + String key = "Server%20Label"; + + HttpRequest deleteMetadata = HttpRequest + .builder() + .method("DELETE") + .endpoint("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/servers/" + serverId + "/metadata/" + key) + .addHeader("Accept", "*/*") + .addHeader("X-Auth-Token", authToken) + .build(); + + HttpResponse deleteMetadataResponse = HttpResponse.builder().statusCode(404).build(); + + NovaApi apiWhenServerExists = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, + responseWithKeystoneAccess, deleteMetadata, deleteMetadataResponse); + + apiWhenServerExists.getServerApiForZone("az-1.region-a.geo-1").deleteMetadata(serverId, key); + + } } diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/features/ServerApiLiveTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/features/ServerApiLiveTest.java index b8d78ed364..e02dc437c1 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/features/ServerApiLiveTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/features/ServerApiLiveTest.java @@ -19,9 +19,9 @@ package org.jclouds.openstack.nova.v2_0.features; import static org.testng.Assert.assertEquals; -import static org.testng.Assert.*; - -import java.util.Set; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertTrue; import org.jclouds.openstack.nova.v2_0.domain.Server; import org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiLiveTest; @@ -44,12 +44,7 @@ public class ServerApiLiveTest extends BaseNovaApiLiveTest { public void testListServers() throws Exception { for (String zoneId : zones) { ServerApi api = novaContext.getApi().getServerApiForZone(zoneId); - Set response = api.listServers(); - assertNotNull(response); - assertFalse(response.isEmpty()); - assert null != response; - assertTrue(response.size() >= 0); - for (Resource server : response) { + for (Resource server : api.list().concat()) { checkResource(server); } } @@ -59,10 +54,7 @@ public class ServerApiLiveTest extends BaseNovaApiLiveTest { public void testListServersInDetail() throws Exception { for (String zoneId : zones) { ServerApi api = novaContext.getApi().getServerApiForZone(zoneId); - Set response = api.listServersInDetail(); - assertNotNull(response); - assertFalse(response.isEmpty()); - for (Server server : response) { + for (Server server : api.listInDetail().concat()) { checkServer(server); } } @@ -72,9 +64,8 @@ public class ServerApiLiveTest extends BaseNovaApiLiveTest { public void testGetServerById() throws Exception { for (String zoneId : zones) { ServerApi api = novaContext.getApi().getServerApiForZone(zoneId); - Set response = api.listServers(); - for (Resource server : response) { - Server details = api.getServer(server.getId()); + for (Resource server : api.list().concat()) { + Server details = api.get(server.getId()); assertEquals(details.getId(), server.getId()); assertEquals(details.getName(), server.getName()); assertEquals(details.getLinks(), server.getLinks()); diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/functions/CreateSecurityGroupIfNeededTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/functions/CreateSecurityGroupIfNeededTest.java index 4965d2cb60..4c38df007e 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/functions/CreateSecurityGroupIfNeededTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/functions/CreateSecurityGroupIfNeededTest.java @@ -44,7 +44,7 @@ import com.google.common.collect.ImmutableSet; */ @Test(groups = "unit", testName = "CreateSecurityGroupIfNeededTest") public class CreateSecurityGroupIfNeededTest extends BaseNovaApiExpectTest { - HttpRequest createSecurityGroup = HttpRequest.builder().method("POST").endpoint( + HttpRequest create = HttpRequest.builder().method("POST").endpoint( URI.create("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/os-security-groups")).headers( ImmutableMultimap. builder().put("Accept", "application/json").put("X-Auth-Token", authToken).build()) @@ -61,13 +61,13 @@ public class CreateSecurityGroupIfNeededTest extends BaseNovaApiExpectTest { builder.put(extensionsOfNovaRequest, extensionsOfNovaResponse); int groupId = 2769; - HttpResponse createSecurityGroupResponse = HttpResponse.builder().statusCode(200) + HttpResponse createResponse = HttpResponse.builder().statusCode(200) .payload( payloadFromStringWithContentType( String.format("{\"security_group\": {\"rules\": [], \"tenant_id\": \"37936628937291\", \"id\": %s, \"name\": \"jclouds_mygroup\", \"description\": \"jclouds_mygroup\"}}", groupId), "application/json; charset=UTF-8")).build(); - builder.put(createSecurityGroup, createSecurityGroupResponse); + builder.put(create, createResponse); int ruleId = 10331; @@ -138,23 +138,23 @@ public class CreateSecurityGroupIfNeededTest extends BaseNovaApiExpectTest { builder.put(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess); builder.put(extensionsOfNovaRequest, extensionsOfNovaResponse); - HttpResponse createSecurityGroupResponse = HttpResponse.builder().statusCode(400) + HttpResponse createResponse = HttpResponse.builder().statusCode(400) .payload( payloadFromStringWithContentType( "{\"badRequest\": {\"message\": \"Security group test already exists\", \"code\": 400}}", "application/json; charset=UTF-8")).build(); - builder.put(createSecurityGroup, createSecurityGroupResponse); + builder.put(create, createResponse); - HttpRequest listSecurityGroups = HttpRequest.builder().method("GET").endpoint( + HttpRequest list = HttpRequest.builder().method("GET").endpoint( URI.create("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/os-security-groups")).headers( ImmutableMultimap. builder().put("Accept", "application/json").put("X-Auth-Token", authToken).build()).build(); - HttpResponse listSecurityGroupsResponse = HttpResponse.builder().statusCode(200).payload( + HttpResponse listResponse = HttpResponse.builder().statusCode(200).payload( payloadFromResource("/securitygroup_list_details_computeservice_typical.json")).build(); - builder.put(listSecurityGroups, listSecurityGroupsResponse); + builder.put(list, listResponse); NovaApi apiWhenSecurityGroupsExist = requestsSendResponses(builder.build()); diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/functions/FindSecurityGroupWithNameAndReturnTrueExpectTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/functions/FindSecurityGroupWithNameAndReturnTrueExpectTest.java index e386bf4ad1..8bdba651cb 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/functions/FindSecurityGroupWithNameAndReturnTrueExpectTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/functions/FindSecurityGroupWithNameAndReturnTrueExpectTest.java @@ -46,17 +46,17 @@ import com.google.common.collect.Iterables; public class FindSecurityGroupWithNameAndReturnTrueExpectTest extends BaseNovaApiExpectTest { public void testUpdateReferenceWhenSecurityGroupListContainsGroupName() throws Exception { - HttpRequest listSecurityGroups = HttpRequest.builder().method("GET").endpoint( + HttpRequest list = HttpRequest.builder().method("GET").endpoint( URI.create("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/os-security-groups")).headers( ImmutableMultimap. builder().put("Accept", "application/json").put("X-Auth-Token", authToken).build()).build(); - HttpResponse listSecurityGroupsResponse = HttpResponse.builder().statusCode(200).payload( + HttpResponse listResponse = HttpResponse.builder().statusCode(200).payload( payloadFromResource("/securitygroup_list.json")).build(); NovaApi apiWhenSecurityGroupsExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, - responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, listSecurityGroups, - listSecurityGroupsResponse); + responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, list, + listResponse); FindSecurityGroupWithNameAndReturnTrue predicate = new FindSecurityGroupWithNameAndReturnTrue( apiWhenSecurityGroupsExist); @@ -74,17 +74,17 @@ public class FindSecurityGroupWithNameAndReturnTrueExpectTest extends BaseNovaAp } public void testDoesNotUpdateReferenceWhenSecurityGroupListMissingGroupName() throws Exception { - HttpRequest listSecurityGroups = HttpRequest.builder().method("GET").endpoint( + HttpRequest list = HttpRequest.builder().method("GET").endpoint( URI.create("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/os-security-groups")).headers( ImmutableMultimap. builder().put("Accept", "application/json").put("X-Auth-Token", authToken).build()).build(); - HttpResponse listSecurityGroupsResponse = HttpResponse.builder().statusCode(200).payload( + HttpResponse listResponse = HttpResponse.builder().statusCode(200).payload( payloadFromResource("/securitygroup_list.json")).build(); NovaApi apiWhenSecurityGroupsExist = requestsSendResponses(keystoneAuthWithUsernameAndPasswordAndTenantName, - responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, listSecurityGroups, - listSecurityGroupsResponse); + responseWithKeystoneAccess, extensionsOfNovaRequest, extensionsOfNovaResponse, list, + listResponse); FindSecurityGroupWithNameAndReturnTrue predicate = new FindSecurityGroupWithNameAndReturnTrue( apiWhenSecurityGroupsExist); diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/internal/BaseNovaApiLiveTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/internal/BaseNovaApiLiveTest.java index 2d90bd10ea..79bc69ab91 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/internal/BaseNovaApiLiveTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/internal/BaseNovaApiLiveTest.java @@ -33,9 +33,9 @@ import org.jclouds.openstack.nova.v2_0.domain.ServerCreated; import org.jclouds.openstack.nova.v2_0.features.FlavorApi; import org.jclouds.openstack.nova.v2_0.features.ImageApi; import org.jclouds.openstack.nova.v2_0.features.ServerApi; +import org.jclouds.openstack.v2_0.domain.Resource; import org.jclouds.rest.RestContext; -import org.testng.annotations.AfterGroups; -import org.testng.annotations.BeforeGroups; +import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.google.common.base.Throwables; @@ -50,6 +50,7 @@ import com.google.common.collect.Ordering; */ @Test(groups = "live") public class BaseNovaApiLiveTest extends BaseComputeServiceContextLiveTest { + protected String hostName = System.getProperty("user.name").replace('.','-').toLowerCase(); public BaseNovaApiLiveTest() { provider = "openstack-nova"; @@ -58,12 +59,19 @@ public class BaseNovaApiLiveTest extends BaseComputeServiceContextLiveTest { protected Set zones; protected RestContext novaContext; - @BeforeGroups(groups = { "integration", "live" }, alwaysRun = true) + @BeforeClass(groups = { "integration", "live" }) @Override public void setupContext() { super.setupContext(); novaContext = view.unwrap(); zones = novaContext.getApi().getConfiguredZones(); + for (String zone : zones){ + ServerApi api = novaContext.getApi().getServerApiForZone(zone); + for (Resource server : api.list().concat()){ + if (server.getName().equals(hostName)) + api.delete(server.getId()); + } + } } @Override @@ -74,17 +82,11 @@ public class BaseNovaApiLiveTest extends BaseComputeServiceContextLiveTest { return props; } - @AfterGroups(groups = "live") - protected void tearDown() { - if (novaContext != null) - novaContext.close(); - } - protected Server createServerInZone(String zoneId) { ServerApi serverApi = novaContext.getApi().getServerApiForZone(zoneId); - ServerCreated server = serverApi.createServer("test", imageIdForZone(zoneId), flavorRefForZone(zoneId)); + ServerCreated server = serverApi.create(hostName, imageIdForZone(zoneId), flavorRefForZone(zoneId)); blockUntilServerInState(server.getId(), serverApi, Status.ACTIVE); - return serverApi.getServer(server.getId()); + return serverApi.get(server.getId()); } /** @@ -93,10 +95,9 @@ public class BaseNovaApiLiveTest extends BaseComputeServiceContextLiveTest { */ protected void blockUntilServerInState(String serverId, ServerApi api, Status status) { Server currentDetails = null; - for (currentDetails = api.getServer(serverId); currentDetails.getStatus() != status || - (currentDetails.getExtendedStatus().isPresent() && currentDetails.getExtendedStatus().get().getTaskState() != null); - currentDetails = api - .getServer(serverId)) { + for (currentDetails = api.get(serverId); currentDetails.getStatus() != status + || ((currentDetails.getExtendedStatus().isPresent() && currentDetails.getExtendedStatus().get() + .getTaskState() != null)); currentDetails = api.get(serverId)) { System.out.printf("blocking on status %s%n%s%n", status, currentDetails); try { Thread.sleep(5 * 1000); @@ -108,12 +109,12 @@ public class BaseNovaApiLiveTest extends BaseComputeServiceContextLiveTest { protected String imageIdForZone(String zoneId) { ImageApi imageApi = novaContext.getApi().getImageApiForZone(zoneId); - return Iterables.getLast(imageApi.listImages()).getId(); + return Iterables.getLast(imageApi.list().concat()).getId(); } protected String flavorRefForZone(String zoneId) { FlavorApi flavorApi = novaContext.getApi().getFlavorApiForZone(zoneId); - return DEFAULT_FLAVOR_ORDERING.min(flavorApi.listFlavorsInDetail()).getId(); + return DEFAULT_FLAVOR_ORDERING.min(flavorApi.listInDetail().concat()).getId(); } static final Ordering DEFAULT_FLAVOR_ORDERING = new Ordering() { diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/internal/BaseNovaComputeServiceContextExpectTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/internal/BaseNovaComputeServiceContextExpectTest.java index 7c56fb1ca8..fdf5fae0a5 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/internal/BaseNovaComputeServiceContextExpectTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/internal/BaseNovaComputeServiceContextExpectTest.java @@ -39,12 +39,12 @@ import com.google.inject.Module; public abstract class BaseNovaComputeServiceContextExpectTest extends BaseNovaExpectTest implements Function { - protected final HttpRequest listImagesDetail = HttpRequest.builder().method("GET").endpoint( + protected final HttpRequest listDetail = HttpRequest.builder().method("GET").endpoint( URI.create("https://az-1.region-a.geo-1.compute.hpcloudsvc.com/v1.1/3456/images/detail")).headers( ImmutableMultimap. builder().put("Accept", "application/json").put("X-Auth-Token", authToken).build()).build(); - protected final HttpResponse listImagesDetailResponse = HttpResponse.builder().statusCode(200).payload( + protected final HttpResponse listDetailResponse = HttpResponse.builder().statusCode(200).payload( payloadFromResource("/image_list_detail.json")).build(); protected final HttpRequest listFlavorsDetail = HttpRequest.builder().method("GET").endpoint( diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/internal/BaseNovaExpectTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/internal/BaseNovaExpectTest.java index e24d00bebd..553d853248 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/internal/BaseNovaExpectTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/internal/BaseNovaExpectTest.java @@ -18,8 +18,6 @@ */ package org.jclouds.openstack.nova.v2_0.internal; -import java.util.Properties; - import javax.ws.rs.core.MediaType; import org.jclouds.http.HttpRequest; @@ -73,14 +71,6 @@ public class BaseNovaExpectTest extends BaseRestApiExpectTest { unmatchedExtensionsOfNovaResponse = HttpResponse.builder().statusCode(200) .payload(payloadFromResource("/extension_list.json")).build(); } - - @Override - protected Properties setupProperties() { - Properties overrides = super.setupProperties(); - // hpcloud or trystack - overrides.setProperty("jclouds.zones", "az-1.region-a.geo-1,RegionOne"); - return overrides; - } @Override protected HttpRequestComparisonType compareHttpRequestAsType(HttpRequest input) { diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/parse/ParseKeyPairListTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/parse/ParseKeyPairListTest.java index bc30d5b001..34769989d0 100644 --- a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/parse/ParseKeyPairListTest.java +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/parse/ParseKeyPairListTest.java @@ -18,9 +18,6 @@ */ package org.jclouds.openstack.nova.v2_0.parse; -import java.util.Map; -import java.util.Set; - import javax.ws.rs.Consumes; import javax.ws.rs.core.MediaType; @@ -28,11 +25,12 @@ import org.jclouds.json.BaseItemParserTest; import org.jclouds.json.config.GsonModule; import org.jclouds.openstack.nova.v2_0.config.NovaParserModule; import org.jclouds.openstack.nova.v2_0.domain.KeyPair; -import org.jclouds.rest.annotations.SelectJson; +import org.jclouds.openstack.nova.v2_0.functions.internal.ParseKeyPairs; +import org.jclouds.rest.annotations.ResponseParser; import org.testng.annotations.Test; +import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Maps; import com.google.inject.Guice; import com.google.inject.Injector; @@ -41,7 +39,7 @@ import com.google.inject.Injector; * @author Michael Arnold */ @Test(groups = "unit", testName = "ParseKeyPairListTest") -public class ParseKeyPairListTest extends BaseItemParserTest>> { +public class ParseKeyPairListTest extends BaseItemParserTest> { @Override public String resource() { @@ -49,26 +47,20 @@ public class ParseKeyPairListTest extends BaseItemParserTest> expected() { - Map kp1 = Maps.newHashMap(); - kp1.put( - "keypair", + public FluentIterable expected() { + return FluentIterable.from(ImmutableSet.of( KeyPair .builder() .publicKey( "ssh-rsa AAAXB3NzaC1yc2EAAAADAQABAAAAgQCy9EC3O7Ff80vPEfAHDQob61PGwcpYc5KE7tEZnZhrB9n0NyHPRm0E0M+ls3fcTa04HDi+R0DzmRwoyhHQJyI658v8kWZZcuvFjKCcsgsSh/dzdX0xTreLIzSOzt5U7RnZYfshP5cmxtF99yrEY3M/swdin0L+fXsTSkR1B42STQ== nova@nv-aw2az1-api0001") - .name("default").fingerprint("ab:0c:f4:f3:54:c0:5d:3f:ed:62:ad:d3:94:7c:79:7c").build()); - Map kp2 = Maps.newHashMap(); - kp2.put( - "keypair", + .name("default").fingerprint("ab:0c:f4:f3:54:c0:5d:3f:ed:62:ad:d3:94:7c:79:7c").build(), KeyPair .builder() .publicKey( "ssh-rsa AAAXB3NzaC1yc2EAAAADAQABAAAAgQDFNyGjgs6c9akgmZ2ou/fJf7Pdrc23hC95/gM/33OrG4GZABACE4DTioa/PGN+7rHv9YUavUCtXrWayhGniKq/wCuI5fo5TO4AmDNv7/sCGHIHFumADSIoLx0vFhGJIetXEWxL9r0lfFC7//6yZM2W3KcGjbMtlPXqBT9K9PzdyQ== nova@nv-aw2az1-api0001") - .name("testkeypair").fingerprint("d2:1f:c9:2b:d8:90:77:5f:15:64:27:e3:9f:77:1d:e4").build()); - return ImmutableSet.of(kp1, kp2); + .name("testkeypair").fingerprint("d2:1f:c9:2b:d8:90:77:5f:15:64:27:e3:9f:77:1d:e4").build())); } protected Injector injector() { diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/parse/ParseMetadataItemTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/parse/ParseMetadataItemTest.java new file mode 100644 index 0000000000..d99709a879 --- /dev/null +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/parse/ParseMetadataItemTest.java @@ -0,0 +1,60 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.nova.v2_0.parse; + +import java.util.Map; + +import javax.ws.rs.Consumes; +import javax.ws.rs.core.MediaType; + +import org.jclouds.json.BaseItemParserTest; +import org.jclouds.json.config.GsonModule; +import org.jclouds.openstack.nova.v2_0.config.NovaParserModule; +import org.jclouds.rest.annotations.SelectJson; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableMap; +import com.google.inject.Guice; +import com.google.inject.Injector; + +/** + * + * @author Jeremy Daggett + */ +@Test(groups = "unit", testName = "ParseMetadataItemTest") +public class ParseMetadataItemTest extends BaseItemParserTest> { + + @Override + public String resource() { + return "/metadata_item.json"; + } + + @Override + @SelectJson("metadata") + @Consumes(MediaType.APPLICATION_JSON) + public Map expected() { + ImmutableMap metadata = ImmutableMap.of("Server Label", "Web Head 1"); + return metadata; + } + + protected Injector injector() { + return Guice.createInjector(new NovaParserModule(), new GsonModule()); + } + +} diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/parse/ParseMetadataListTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/parse/ParseMetadataListTest.java new file mode 100644 index 0000000000..db195fcf23 --- /dev/null +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/parse/ParseMetadataListTest.java @@ -0,0 +1,65 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.nova.v2_0.parse; + +import java.util.Map; + +import javax.ws.rs.Consumes; +import javax.ws.rs.core.MediaType; + +import org.jclouds.json.BaseItemParserTest; +import org.jclouds.json.config.GsonModule; +import org.jclouds.openstack.nova.v2_0.config.NovaParserModule; +import org.jclouds.rest.annotations.SelectJson; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableMap; +import com.google.inject.Guice; +import com.google.inject.Injector; + +/** + * + * @author Jeremy Daggett + */ +@Test(groups = "unit", testName = "ParseMetadataListTest") +public class ParseMetadataListTest extends BaseItemParserTest> { + + @Override + public String resource() { + return "/metadata_list.json"; + } + + @Override + @SelectJson("metadata") + @Consumes(MediaType.APPLICATION_JSON) + public Map expected() { + ImmutableMap metadata = + new ImmutableMap.Builder() + .put("Server Label", "Web Head 1") + .put("Image Version", "2.1") + .build(); + + return metadata; + } + + protected Injector injector() { + return Guice.createInjector(new NovaParserModule(), new GsonModule()); + } + +} diff --git a/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/parse/ParseMetadataUpdateTest.java b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/parse/ParseMetadataUpdateTest.java new file mode 100644 index 0000000000..dc08093ab2 --- /dev/null +++ b/apis/openstack-nova/src/test/java/org/jclouds/openstack/nova/v2_0/parse/ParseMetadataUpdateTest.java @@ -0,0 +1,66 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.nova.v2_0.parse; + +import java.util.Map; + +import javax.ws.rs.Consumes; +import javax.ws.rs.core.MediaType; + +import org.jclouds.json.BaseItemParserTest; +import org.jclouds.json.config.GsonModule; +import org.jclouds.openstack.nova.v2_0.config.NovaParserModule; +import org.jclouds.rest.annotations.SelectJson; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableMap; +import com.google.inject.Guice; +import com.google.inject.Injector; + +/** + * + * @author Jeremy Daggett + */ +@Test(groups = "unit", testName = "ParseMetadataUpdateTest") +public class ParseMetadataUpdateTest extends BaseItemParserTest> { + + @Override + public String resource() { + return "/metadata_updated.json"; + } + + @Override + @SelectJson("metadata") + @Consumes(MediaType.APPLICATION_JSON) + public Map expected() { + ImmutableMap metadata = + new ImmutableMap.Builder() + .put("Server Label", "Web Head 2") + .put("Image Version", "2.1") + .put("Server Description", "Simple Server") + .build(); + + return metadata; + } + + protected Injector injector() { + return Guice.createInjector(new NovaParserModule(), new GsonModule()); + } + +} diff --git a/apis/openstack-nova/src/test/resources/metadata_item.json b/apis/openstack-nova/src/test/resources/metadata_item.json new file mode 100644 index 0000000000..f853109c10 --- /dev/null +++ b/apis/openstack-nova/src/test/resources/metadata_item.json @@ -0,0 +1,5 @@ +{ + "metadata": { + "Server Label": "Web Head 1" + } +} \ No newline at end of file diff --git a/apis/openstack-nova/src/test/resources/metadata_list.json b/apis/openstack-nova/src/test/resources/metadata_list.json new file mode 100644 index 0000000000..174d7d60be --- /dev/null +++ b/apis/openstack-nova/src/test/resources/metadata_list.json @@ -0,0 +1,6 @@ +{ + "metadata": { + "Server Label": "Web Head 1", + "Image Version": "2.1" + } +} \ No newline at end of file diff --git a/apis/openstack-nova/src/test/resources/metadata_updated.json b/apis/openstack-nova/src/test/resources/metadata_updated.json new file mode 100644 index 0000000000..82d9fd3ac9 --- /dev/null +++ b/apis/openstack-nova/src/test/resources/metadata_updated.json @@ -0,0 +1,7 @@ +{ + "metadata": { + "Server Label": "Web Head 2", + "Image Version": "2.1", + "Server Description": "Simple Server" + } +} \ No newline at end of file diff --git a/apis/pom.xml b/apis/pom.xml index bde1678588..e3a08751eb 100644 --- a/apis/pom.xml +++ b/apis/pom.xml @@ -24,7 +24,7 @@ jclouds-project org.jclouds - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../project/pom.xml org.jclouds.api @@ -54,5 +54,6 @@ cloudsigma cloudstack rackspace-cloudidentity + sqs diff --git a/apis/rackspace-cloudidentity/pom.xml b/apis/rackspace-cloudidentity/pom.xml index a0b478d390..7e8eb0d7d4 100644 --- a/apis/rackspace-cloudidentity/pom.xml +++ b/apis/rackspace-cloudidentity/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.api diff --git a/apis/s3/pom.xml b/apis/s3/pom.xml index 3759c5eab4..936486037b 100644 --- a/apis/s3/pom.xml +++ b/apis/s3/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.api diff --git a/apis/s3/src/main/java/org/jclouds/s3/S3.java b/apis/s3/src/main/java/org/jclouds/s3/S3.java new file mode 100644 index 0000000000..f3090dd868 --- /dev/null +++ b/apis/s3/src/main/java/org/jclouds/s3/S3.java @@ -0,0 +1,85 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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.s3; + +import org.jclouds.collect.IterableWithMarker; +import org.jclouds.collect.IterableWithMarkers; +import org.jclouds.collect.PagedIterable; +import org.jclouds.collect.PagedIterables; +import org.jclouds.s3.domain.ListBucketResponse; +import org.jclouds.s3.domain.ObjectMetadata; +import org.jclouds.s3.options.ListBucketOptions; + +import com.google.common.base.Function; + +/** + * Utilities for using S3. + * + * @author Adrian Cole + */ +public class S3 { + + /** + * List all objects in a bucket, in a way that manages pagination, based on + * the criteria in the {@link ListBucketOptions} passed in. + * + * ex. + * + *

+    * continueAfterEachPage = listBucket(s3Client, bucket, options).concat();
+    *
+    * 
+ * + * @param s3Client + * the {@link S3Client} to use for the requests + * @param bucket + * the bucket to list + * @param options + * the {@link ListBucketOptions} describing the listBucket requests + * + * @return iterable of objects fitting the criteria + * @see PagedIterable + */ + public static PagedIterable listBucket(final S3Client s3Client, final String bucket, + final ListBucketOptions options) { + return PagedIterables.advance(ToIterableWithMarker.INSTANCE.apply(s3Client.listBucket(bucket, options)), + new Function>() { + + @Override + public IterableWithMarker apply(Object input) { + return ToIterableWithMarker.INSTANCE.apply(s3Client.listBucket(bucket, + options.clone().afterMarker(input.toString()))); + } + + @Override + public String toString() { + return "listBucket(" + options + ")"; + } + }); + } + + private enum ToIterableWithMarker implements Function> { + INSTANCE; + @Override + public IterableWithMarker apply(ListBucketResponse in) { + return IterableWithMarkers.from(in, in.getNextMarker()); + } + } + +} diff --git a/apis/s3/src/main/java/org/jclouds/s3/S3AsyncClient.java b/apis/s3/src/main/java/org/jclouds/s3/S3AsyncClient.java index 749d28c80d..724f1e23e2 100644 --- a/apis/s3/src/main/java/org/jclouds/s3/S3AsyncClient.java +++ b/apis/s3/src/main/java/org/jclouds/s3/S3AsyncClient.java @@ -99,7 +99,7 @@ import com.google.inject.Provides; * All commands return a ListenableFuture of the result from S3. Any exceptions incurred during * processing will be backend in an {@link ExecutionException} as documented in * {@link ListenableFuture#get()}. - * + * * @author Adrian Cole * @author James Murty * @see S3Client @@ -187,7 +187,6 @@ public interface S3AsyncClient { */ @DELETE @Path("/") - @Endpoint(Bucket.class) @ExceptionParser(ReturnTrueOn404OrNotFoundFalseOnIllegalState.class) ListenableFuture deleteBucketIfEmpty( @Bucket @EndpointParam(parser = DefaultEndpointThenInvalidateRegion.class) @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators(BucketNameValidator.class) String bucketName); @@ -197,12 +196,11 @@ public interface S3AsyncClient { */ @HEAD @Path("/") - @Endpoint(Bucket.class) @QueryParams(keys = "max-keys", values = "0") @ExceptionParser(ReturnFalseOnContainerNotFound.class) ListenableFuture bucketExists( - @Bucket @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators(BucketNameValidator.class) String bucketName); - + @Bucket @EndpointParam(parser = AssignCorrectHostnameForBucket.class) @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators(BucketNameValidator.class) String bucketName); + /** * @see S3Client#getBucketLocation @@ -213,7 +211,7 @@ public interface S3AsyncClient { @Endpoint(Bucket.class) @XMLResponseParser(LocationConstraintHandler.class) ListenableFuture getBucketLocation( - @Bucket @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators(BucketNameValidator.class) String bucketName); + @Bucket @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators(BucketNameValidator.class) String bucketName); /** * @see S3Client#getBucketPayer diff --git a/apis/s3/src/main/java/org/jclouds/s3/functions/DefaultEndpointThenInvalidateRegion.java b/apis/s3/src/main/java/org/jclouds/s3/functions/DefaultEndpointThenInvalidateRegion.java index 680f16500b..d7eaffa870 100644 --- a/apis/s3/src/main/java/org/jclouds/s3/functions/DefaultEndpointThenInvalidateRegion.java +++ b/apis/s3/src/main/java/org/jclouds/s3/functions/DefaultEndpointThenInvalidateRegion.java @@ -24,7 +24,6 @@ import javax.inject.Inject; import javax.inject.Singleton; import org.jclouds.javax.annotation.Nullable; -import org.jclouds.location.functions.RegionToEndpointOrProviderIfNull; import org.jclouds.s3.Bucket; import com.google.common.base.Function; @@ -32,17 +31,17 @@ import com.google.common.base.Optional; import com.google.common.cache.LoadingCache; /** - * + * * @author Adrian Cole */ @Singleton public class DefaultEndpointThenInvalidateRegion implements Function { private final LoadingCache> bucketToRegionCache; - private final RegionToEndpointOrProviderIfNull r2; + private final AssignCorrectHostnameForBucket r2; @Inject - public DefaultEndpointThenInvalidateRegion(RegionToEndpointOrProviderIfNull r2, + public DefaultEndpointThenInvalidateRegion(AssignCorrectHostnameForBucket r2, @Bucket LoadingCache> bucketToRegionCache) { this.r2 = r2; this.bucketToRegionCache = bucketToRegionCache; @@ -51,7 +50,7 @@ public class DefaultEndpointThenInvalidateRegion implements Function */ -public class ListBucketOptions extends BaseHttpRequestOptions { +public class ListBucketOptions extends BaseHttpRequestOptions implements Cloneable { public static final ListBucketOptions NONE = new ListBucketOptions(); /** @@ -138,4 +138,11 @@ public class ListBucketOptions extends BaseHttpRequestOptions { } } + + @Override + public ListBucketOptions clone() { + ListBucketOptions newOptions = new ListBucketOptions(); + newOptions.queryParameters.putAll(queryParameters); + return newOptions; + } } diff --git a/apis/s3/src/main/java/org/jclouds/s3/util/S3Utils.java b/apis/s3/src/main/java/org/jclouds/s3/util/S3Utils.java index 43928bfee4..0f4cb16734 100644 --- a/apis/s3/src/main/java/org/jclouds/s3/util/S3Utils.java +++ b/apis/s3/src/main/java/org/jclouds/s3/util/S3Utils.java @@ -62,7 +62,7 @@ public class S3Utils { */ public static boolean deleteAndVerifyContainerGone(S3Client sync, String container) { sync.deleteBucketIfEmpty(container); - return sync.bucketExists(container); + return !sync.bucketExists(container); } private static final Predicate ANNOTATIONTYPE_BUCKET = new Predicate() { diff --git a/apis/s3/src/test/java/org/jclouds/s3/S3Test.java b/apis/s3/src/test/java/org/jclouds/s3/S3Test.java new file mode 100644 index 0000000000..0a1f11d8e6 --- /dev/null +++ b/apis/s3/src/test/java/org/jclouds/s3/S3Test.java @@ -0,0 +1,93 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.s3; + +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expect; +import static org.testng.Assert.assertEquals; + +import org.easymock.EasyMock; +import org.jclouds.collect.PagedIterable; +import org.jclouds.s3.domain.ListBucketResponse; +import org.jclouds.s3.domain.ObjectMetadata; +import org.jclouds.s3.domain.internal.ListBucketResponseImpl; +import org.jclouds.s3.options.ListBucketOptions; +import org.jclouds.s3.xml.ListBucketHandlerTest; +import org.testng.annotations.Test; + +/** + * Tests behavior of {@code S3}. + * + * @author Adrian Cole + */ +public class S3Test { + + /** + * Tests {@link S3#listBucket(S3Client, String, ListBucketOptions)} where a + * single response returns all results. + * + * @throws Exception + * if anything goes wrong + */ + @Test + public void testSinglePageResult() throws Exception { + S3Client api = createMock(S3Client.class); + ListBucketOptions options = new ListBucketOptions(); + ListBucketResponse response = new ListBucketHandlerTest().expected(); + + expect(api.listBucket("bucket", options)).andReturn(response).once(); + + EasyMock.replay(api); + + PagedIterable result = S3.listBucket(api, "bucket", options); + + // number of pages + assertEquals(result.size(), 1); + // number of objects + assertEquals(result.get(0).size(), 10); + } + + /** + * Tests {@link S3#listBucket(S3Client, String, ListBucketOptions)} where + * retrieving all results requires multiple requests. + * + * @throws Exception + * if anything goes wrong + */ + @Test + public void testMultiPageResult() throws Exception { + String nextMarker = "FOO"; + S3Client api = createMock(S3Client.class); + ListBucketOptions options = new ListBucketOptions(); + ListBucketResponse response2 = new ListBucketHandlerTest().expected(); + ListBucketResponse response1 = new ListBucketResponseImpl(response2.getName(), response2, response2.getPrefix(), + null, nextMarker, response2.getMaxKeys(), response2.getDelimiter(), false, response2.getCommonPrefixes()); + + expect(api.listBucket("bucket", options)).andReturn(response1).once(); + expect(api.listBucket("bucket", options.afterMarker(nextMarker))).andReturn(response2).once(); + + EasyMock.replay(api); + + PagedIterable result = S3.listBucket(api, "bucket", options); + + // number of objects + assertEquals(result.concat().size(), 20); + } + +} diff --git a/apis/s3/src/test/java/org/jclouds/s3/blobstore/S3BlobRequestSignerTest.java b/apis/s3/src/test/java/org/jclouds/s3/blobstore/S3BlobRequestSignerTest.java deleted file mode 100644 index 06b43d3949..0000000000 --- a/apis/s3/src/test/java/org/jclouds/s3/blobstore/S3BlobRequestSignerTest.java +++ /dev/null @@ -1,128 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.s3.blobstore; - -import static org.testng.Assert.assertEquals; - -import java.io.IOException; -import java.util.Date; - -import javax.inject.Provider; - -import org.jclouds.blobstore.BlobRequestSigner; -import org.jclouds.blobstore.domain.Blob; -import org.jclouds.blobstore.domain.BlobBuilder; -import org.jclouds.date.TimeStamp; -import org.jclouds.http.HttpRequest; -import org.jclouds.rest.ConfiguresRestClient; -import org.jclouds.rest.internal.RestAnnotationProcessor; -import org.jclouds.s3.S3AsyncClient; -import org.jclouds.s3.S3Client; -import org.jclouds.s3.config.S3RestClientModule; -import org.jclouds.s3.internal.BaseS3AsyncClientTest; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -import com.google.common.base.Supplier; -import com.google.inject.Module; -import com.google.inject.TypeLiteral; - -/** - * Tests behavior of {@code S3BlobRequestSigner} - * - * @author Adrian Cole - */ -// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire -@Test(groups = "unit", testName = "S3BlobRequestSignerTest") -public class S3BlobRequestSignerTest extends BaseS3AsyncClientTest { - - @Override - protected TypeLiteral> createTypeLiteral() { - return new TypeLiteral>() { - }; - } - - private BlobRequestSigner signer; - private Provider blobFactory; - - public void testSignGetBlob() throws ArrayIndexOutOfBoundsException, SecurityException, IllegalArgumentException, - NoSuchMethodException, IOException { - HttpRequest request = signer.signGetBlob("container", "name"); - - assertRequestLineEquals(request, "GET https://container.s3.amazonaws.com/name HTTP/1.1"); - assertNonPayloadHeadersEqual( - request, - "Authorization: AWS identity:0uvBv1wEskuhFHYJF/L6kEV9A7o=\nDate: Thu, 05 Jun 2008 16:38:19 GMT\nHost: container.s3.amazonaws.com\n"); - assertPayloadEquals(request, null, null, false); - - assertEquals(request.getFilters().size(), 0); - } - - public void testSignRemoveBlob() throws ArrayIndexOutOfBoundsException, SecurityException, IllegalArgumentException, - NoSuchMethodException, IOException { - HttpRequest request = signer.signRemoveBlob("container", "name"); - - assertRequestLineEquals(request, "DELETE https://container.s3.amazonaws.com/name HTTP/1.1"); - assertNonPayloadHeadersEqual( - request, - "Authorization: AWS identity:4FnyjdX/ULdDMRbVlLNjZfEo9RQ=\nDate: Thu, 05 Jun 2008 16:38:19 GMT\nHost: container.s3.amazonaws.com\n"); - assertPayloadEquals(request, null, null, false); - - assertEquals(request.getFilters().size(), 0); - } - - public void testSignPutBlob() throws ArrayIndexOutOfBoundsException, SecurityException, IllegalArgumentException, - NoSuchMethodException, IOException { - Blob blob = blobFactory.get().name("name").forSigning().contentLength(2l).contentMD5(new byte[] { 0, 2, 4, 8 }).contentType( - "text/plain").expires(new Date(1000)).build(); - - HttpRequest request = signer.signPutBlob("container", blob); - - assertRequestLineEquals(request, "PUT https://container.s3.amazonaws.com/name HTTP/1.1"); - assertNonPayloadHeadersEqual( - request, - "Authorization: AWS identity:j9Dy/lmmvlCKjA4lkqZenLxMkR4=\nDate: Thu, 05 Jun 2008 16:38:19 GMT\nHost: container.s3.amazonaws.com\n"); - - assertContentHeadersEqual(request, "text/plain", null, null, null, (long) 2l, new byte[] { 0, 2, 4, 8 }, new Date(1000)); - - assertEquals(request.getFilters().size(), 0); - } - - @BeforeClass - protected void setupFactory() throws IOException { - super.setupFactory(); - this.blobFactory = injector.getProvider(BlobBuilder.class); - this.signer = injector.getInstance(BlobRequestSigner.class); - } - - @Override - protected Module createModule() { - return new TestS3RestClientModule(); - } - - @ConfiguresRestClient - private static final class TestS3RestClientModule extends S3RestClientModule { - - @Override - protected String provideTimeStamp(@TimeStamp Supplier cache) { - return "Thu, 05 Jun 2008 16:38:19 GMT"; - } - } - -} diff --git a/apis/s3/src/test/java/org/jclouds/s3/blobstore/S3BlobSignerExpectTest.java b/apis/s3/src/test/java/org/jclouds/s3/blobstore/S3BlobSignerExpectTest.java new file mode 100644 index 0000000000..2d074d2b43 --- /dev/null +++ b/apis/s3/src/test/java/org/jclouds/s3/blobstore/S3BlobSignerExpectTest.java @@ -0,0 +1,129 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.s3.blobstore; + +import org.jclouds.blobstore.internal.BaseBlobSignerExpectTest; +import org.jclouds.date.TimeStamp; +import org.jclouds.http.HttpRequest; +import org.jclouds.rest.ConfiguresRestClient; +import org.jclouds.s3.S3AsyncClient; +import org.jclouds.s3.S3Client; +import org.jclouds.s3.config.S3RestClientModule; +import org.testng.SkipException; +import org.testng.annotations.Test; + +import com.google.common.base.Supplier; +import com.google.inject.Module; + +/** + * Tests behavior of {@code S3BlobRequestSigner} + * + * @author Adrian Cole + */ +@Test(groups = "unit", testName = "S3BlobSignerExpectTest") +public class S3BlobSignerExpectTest extends BaseBlobSignerExpectTest { + + public S3BlobSignerExpectTest() { + provider = "s3"; + } + + @Override + protected HttpRequest getBlob() { + return HttpRequest.builder().method("GET") + .endpoint("https://container.s3.amazonaws.com/name") + .addHeader("Host", "container.s3.amazonaws.com") + .addHeader("Date", "Thu, 05 Jun 2008 16:38:19 GMT") + .addHeader("Authorization", "AWS identity:0uvBv1wEskuhFHYJF/L6kEV9A7o=").build(); + } + + @Override + @Test + public void testSignGetBlobWithTime() { + throw new SkipException("not yet implemented"); + } + + //TODO + @Override + protected HttpRequest getBlobWithTime() { + return HttpRequest.builder().method("GET") + .endpoint("https://container.s3.amazonaws.com/name") + .addHeader("Host", "container.s3.amazonaws.com") + .addHeader("Date", "Thu, 05 Jun 2008 16:38:19 GMT") + .addHeader("Authorization", "AWS identity:0uvBv1wEskuhFHYJF/L6kEV9A7o=").build(); + } + + @Override + protected HttpRequest getBlobWithOptions() { + return HttpRequest.builder().method("GET") + .endpoint("https://container.s3.amazonaws.com/name") + .addHeader("Range", "bytes=0-1") + .addHeader("Host", "container.s3.amazonaws.com") + .addHeader("Date", "Thu, 05 Jun 2008 16:38:19 GMT") + .addHeader("Authorization", "AWS identity:0uvBv1wEskuhFHYJF/L6kEV9A7o=").build(); + } + + @Override + protected HttpRequest putBlob() { + return HttpRequest.builder().method("PUT") + .endpoint("https://container.s3.amazonaws.com/name") + .addHeader("Host", "container.s3.amazonaws.com") + .addHeader("Date", "Thu, 05 Jun 2008 16:38:19 GMT") + .addHeader("Authorization", "AWS identity:j9Dy/lmmvlCKjA4lkqZenLxMkR4=").build(); + } + + @Override + @Test + public void testSignPutBlobWithTime() throws Exception { + throw new SkipException("not yet implemented"); + } + + //TODO + @Override + protected HttpRequest putBlobWithTime() { + return HttpRequest.builder().method("PUT") + .endpoint("https://container.s3.amazonaws.com/name") + .addHeader("Host", "container.s3.amazonaws.com") + .addHeader("Date", "Thu, 05 Jun 2008 16:38:19 GMT") + .addHeader("Authorization", "AWS identity:0uvBv1wEskuhFHYJF/L6kEV9A7o=").build(); + } + + @Override + protected HttpRequest removeBlob() { + return HttpRequest.builder().method("DELETE") + .endpoint("https://container.s3.amazonaws.com/name") + .addHeader("Host", "container.s3.amazonaws.com") + .addHeader("Date", "Thu, 05 Jun 2008 16:38:19 GMT") + .addHeader("Authorization", "AWS identity:4FnyjdX/ULdDMRbVlLNjZfEo9RQ=").build(); + } + + @Override + protected Module createModule() { + return new TestS3RestClientModule(); + } + + @ConfiguresRestClient + private static final class TestS3RestClientModule extends S3RestClientModule { + + @Override + protected String provideTimeStamp(@TimeStamp Supplier cache) { + return "Thu, 05 Jun 2008 16:38:19 GMT"; + } + } + +} diff --git a/apis/s3/src/test/java/org/jclouds/s3/functions/DefaultEndpointThenInvalidateRegionTest.java b/apis/s3/src/test/java/org/jclouds/s3/functions/DefaultEndpointThenInvalidateRegionTest.java index 514ee8c9ec..c8c8fd52e8 100644 --- a/apis/s3/src/test/java/org/jclouds/s3/functions/DefaultEndpointThenInvalidateRegionTest.java +++ b/apis/s3/src/test/java/org/jclouds/s3/functions/DefaultEndpointThenInvalidateRegionTest.java @@ -25,7 +25,6 @@ import static org.easymock.EasyMock.verify; import java.net.URI; -import org.jclouds.location.functions.RegionToEndpointOrProviderIfNull; import org.testng.annotations.Test; import com.google.common.base.Optional; @@ -40,10 +39,10 @@ public class DefaultEndpointThenInvalidateRegionTest { @SuppressWarnings("unchecked") @Test void testInvalidate() throws Exception { - RegionToEndpointOrProviderIfNull r2 = createMock(RegionToEndpointOrProviderIfNull.class); + AssignCorrectHostnameForBucket r2 = createMock(AssignCorrectHostnameForBucket.class); LoadingCache> bucketToRegionCache = createMock(LoadingCache.class); - expect(r2.apply(null)).andReturn(URI.create("http://east-url")); + expect(r2.apply("mybucket")).andReturn(URI.create("http://east-url")); bucketToRegionCache.invalidate("mybucket"); replay(r2, bucketToRegionCache); diff --git a/apis/s3/src/test/java/org/jclouds/s3/options/ListBucketOptionsTest.java b/apis/s3/src/test/java/org/jclouds/s3/options/ListBucketOptionsTest.java index 7d2839bd95..1a2939dccc 100644 --- a/apis/s3/src/test/java/org/jclouds/s3/options/ListBucketOptionsTest.java +++ b/apis/s3/src/test/java/org/jclouds/s3/options/ListBucketOptionsTest.java @@ -24,12 +24,11 @@ import static org.jclouds.s3.options.ListBucketOptions.Builder.maxResults; import static org.jclouds.s3.options.ListBucketOptions.Builder.withPrefix; import static org.testng.Assert.assertEquals; -import java.util.Collections; - import org.jclouds.http.options.HttpRequestOptions; import org.jclouds.s3.reference.S3Constants; import org.testng.annotations.Test; +import com.google.common.collect.ImmutableList; import com.google.common.collect.Multimap; /** @@ -49,8 +48,8 @@ public class ListBucketOptionsTest { public void testPrefix() { ListBucketOptions options = new ListBucketOptions(); options.withPrefix("test"); - assertEquals(options.buildQueryParameters().get(S3Constants.PREFIX), Collections - .singletonList("test")); + assertEquals(options.buildQueryParameters().get(S3Constants.PREFIX), + ImmutableList.of("test")); } @Test @@ -65,7 +64,7 @@ public class ListBucketOptionsTest { options.withPrefix("test"); Multimap map = options.buildQueryParameters(); assertEquals(map.size(), 1); - assertEquals(map.get("prefix"), Collections.singletonList("test")); + assertEquals(map.get("prefix"), ImmutableList.of("test")); } @Test @@ -74,8 +73,8 @@ public class ListBucketOptionsTest { options.withPrefix("test").maxResults(1); Multimap map = options.buildQueryParameters(); assertEquals(map.size(), 2); - assertEquals(map.get("prefix"), Collections.singletonList("test")); - assertEquals(map.get("max-keys"), Collections.singletonList("1")); + assertEquals(map.get("prefix"), ImmutableList.of("test")); + assertEquals(map.get("max-keys"), ImmutableList.of("1")); } @Test @@ -84,22 +83,22 @@ public class ListBucketOptionsTest { options.withPrefix("/test").delimiter("/"); Multimap map = options.buildQueryParameters(); assertEquals(map.size(), 2); - assertEquals(map.get("prefix"), Collections.singletonList("/test")); - assertEquals(map.get("delimiter"), Collections.singletonList("/")); + assertEquals(map.get("prefix"), ImmutableList.of("/test")); + assertEquals(map.get("delimiter"), ImmutableList.of("/")); } @Test public void testNullPrefix() { ListBucketOptions options = new ListBucketOptions(); - assertEquals(options.buildQueryParameters().get(S3Constants.PREFIX), Collections.EMPTY_LIST); + assertEquals(options.buildQueryParameters().get(S3Constants.PREFIX), ImmutableList.of()); } @Test public void testPrefixStatic() { ListBucketOptions options = withPrefix("test"); - assertEquals(options.buildQueryParameters().get(S3Constants.PREFIX), Collections - .singletonList("test")); + assertEquals(options.buildQueryParameters().get(S3Constants.PREFIX), + ImmutableList.of("test")); } @Test(expectedExceptions = NullPointerException.class) @@ -111,21 +110,21 @@ public class ListBucketOptionsTest { public void testMarker() { ListBucketOptions options = new ListBucketOptions(); options.afterMarker("test"); - assertEquals(options.buildQueryParameters().get(S3Constants.MARKER), Collections - .singletonList("test")); + assertEquals(options.buildQueryParameters().get(S3Constants.MARKER), + ImmutableList.of("test")); } @Test public void testNullMarker() { ListBucketOptions options = new ListBucketOptions(); - assertEquals(options.buildQueryParameters().get(S3Constants.MARKER), Collections.EMPTY_LIST); + assertEquals(options.buildQueryParameters().get(S3Constants.MARKER), ImmutableList.of()); } @Test public void testMarkerStatic() { ListBucketOptions options = afterMarker("test"); - assertEquals(options.buildQueryParameters().get(S3Constants.MARKER), Collections - .singletonList("test")); + assertEquals(options.buildQueryParameters().get(S3Constants.MARKER), + ImmutableList.of("test")); } @Test(expectedExceptions = NullPointerException.class) @@ -137,21 +136,21 @@ public class ListBucketOptionsTest { public void testMaxKeys() { ListBucketOptions options = new ListBucketOptions(); options.maxResults(1000); - assertEquals(options.buildQueryParameters().get(S3Constants.MAX_KEYS), Collections - .singletonList("1000")); + assertEquals(options.buildQueryParameters().get(S3Constants.MAX_KEYS), + ImmutableList.of("1000")); } @Test public void testNullMaxKeys() { ListBucketOptions options = new ListBucketOptions(); - assertEquals(options.buildQueryParameters().get(S3Constants.MAX_KEYS), Collections.EMPTY_LIST); + assertEquals(options.buildQueryParameters().get(S3Constants.MAX_KEYS), ImmutableList.of()); } @Test public void testMaxKeysStatic() { ListBucketOptions options = maxResults(1000); - assertEquals(options.buildQueryParameters().get(S3Constants.MAX_KEYS), Collections - .singletonList("1000")); + assertEquals(options.buildQueryParameters().get(S3Constants.MAX_KEYS), + ImmutableList.of("1000")); } @Test(expectedExceptions = IllegalStateException.class) @@ -163,22 +162,22 @@ public class ListBucketOptionsTest { public void testDelimiter() { ListBucketOptions options = new ListBucketOptions(); options.delimiter("test"); - assertEquals(options.buildQueryParameters().get(S3Constants.DELIMITER), Collections - .singletonList("test")); + assertEquals(options.buildQueryParameters().get(S3Constants.DELIMITER), + ImmutableList.of("test")); } @Test public void testNullDelimiter() { ListBucketOptions options = new ListBucketOptions(); assertEquals(options.buildQueryParameters().get(S3Constants.DELIMITER), - Collections.EMPTY_LIST); + ImmutableList.of()); } @Test public void testDelimiterStatic() { ListBucketOptions options = delimiter("test"); - assertEquals(options.buildQueryParameters().get(S3Constants.DELIMITER), Collections - .singletonList("test")); + assertEquals(options.buildQueryParameters().get(S3Constants.DELIMITER), + ImmutableList.of("test")); } @Test(expectedExceptions = NullPointerException.class) diff --git a/apis/s3/src/test/java/org/jclouds/s3/xml/ListBucketHandlerTest.java b/apis/s3/src/test/java/org/jclouds/s3/xml/ListBucketHandlerTest.java index 69f6301eb2..da2a282876 100644 --- a/apis/s3/src/test/java/org/jclouds/s3/xml/ListBucketHandlerTest.java +++ b/apis/s3/src/test/java/org/jclouds/s3/xml/ListBucketHandlerTest.java @@ -26,6 +26,7 @@ import java.util.TreeSet; import org.jclouds.crypto.CryptoStreams; import org.jclouds.date.DateService; +import org.jclouds.date.internal.SimpleDateFormatDateService; import org.jclouds.http.HttpException; import org.jclouds.http.HttpRequest; import org.jclouds.http.functions.BaseHandlerTest; @@ -36,7 +37,6 @@ import org.jclouds.s3.domain.ObjectMetadata; import org.jclouds.s3.domain.ObjectMetadataBuilder; import org.jclouds.s3.domain.internal.ListBucketResponseImpl; import org.jclouds.util.Strings2; -import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import com.google.common.collect.ImmutableList; @@ -51,21 +51,19 @@ import com.google.common.collect.ImmutableList; public class ListBucketHandlerTest extends BaseHandlerTest { public static final String listBucketWithPrefixAppsSlash = "adriancole.org.jclouds.s3.amazons3testdelimiterapps/1000falseapps/02009-05-07T18:27:08.000Z"c82e6a0025c31c5de5947fda62ac51ab"8e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0ferncamSTANDARDapps/12009-05-07T18:27:09.000Z"944fab2c5a9a6bacf07db5e688310d7a"8e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0ferncamSTANDARDapps/22009-05-07T18:27:09.000Z"a227b8888045c8fd159fb495214000f0"8e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0ferncamSTANDARDapps/32009-05-07T18:27:09.000Z"c9caa76c3dec53e2a192608ce73eef03"8e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0ferncamSTANDARDapps/42009-05-07T18:27:09.000Z"1ce5d0dcc6154a647ea90c7bdf82a224"8e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0ferncamSTANDARDapps/52009-05-07T18:27:09.000Z"79433524d87462ee05708a8ef894ed55"8e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0ferncamSTANDARDapps/62009-05-07T18:27:10.000Z"dd00a060b28ddca8bc5a21a49e306f67"8e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0ferncamSTANDARDapps/72009-05-07T18:27:10.000Z"8cd06eca6e819a927b07a285d750b100"8e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0ferncamSTANDARDapps/82009-05-07T18:27:10.000Z"174495094d0633b92cbe46603eee6bad"8e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0ferncamSTANDARDapps/92009-05-07T18:27:10.000Z"cd8a19b26fea8a827276df0ad11c580d"8e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0ferncamSTANDARD"; public static final String listBucketWithSlashDelimiterAndCommonPrefixApps = " / apps/"; - private DateService dateService; - - @BeforeTest - @Override - protected void setUpInjector() { - super.setUpInjector(); - dateService = injector.getInstance(DateService.class); - assert dateService != null; - } + private DateService dateService = new SimpleDateFormatDateService(); public void testApplyInputStream() { InputStream is = getClass().getResourceAsStream("/list_bucket.xml"); ListBucketResponse result = createParser().parse(is); + ListBucketResponse expected = expected(); + + assertEquals(result.toString(), expected.toString()); + } + + public ListBucketResponse expected() { CanonicalUser owner = new CanonicalUser("e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0", "ferncam"); String bucket = "adriancole.org.jclouds.aws.s3.amazons3testdelimiter"; @@ -111,8 +109,7 @@ public class ListBucketHandlerTest extends BaseHandlerTest { "\"cd8a19b26fea8a827276df0ad11c580d\"").owner(owner).contentMD5( CryptoStreams.hex("cd8a19b26fea8a827276df0ad11c580d")).contentLength(8l).build()), "apps/", null, null, 1000, null, false, new TreeSet()); - - assertEquals(result.toString(), expected.toString()); + return expected; } ParseSax createParser() { diff --git a/labs/sqs/pom.xml b/apis/sqs/pom.xml similarity index 98% rename from labs/sqs/pom.xml rename to apis/sqs/pom.xml index 43f9c737c9..f15522c46e 100644 --- a/labs/sqs/pom.xml +++ b/apis/sqs/pom.xml @@ -24,10 +24,10 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml - org.jclouds.labs + org.jclouds.api sqs jcloud sqs api jclouds components to access an implementation of Simple Queue Service diff --git a/apis/sqs/src/main/java/org/jclouds/sqs/SQS.java b/apis/sqs/src/main/java/org/jclouds/sqs/SQS.java new file mode 100644 index 0000000000..80e4936434 --- /dev/null +++ b/apis/sqs/src/main/java/org/jclouds/sqs/SQS.java @@ -0,0 +1,84 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.sqs; + +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkState; + +import org.jclouds.collect.AdvanceUntilEmptyIterable; +import org.jclouds.javax.annotation.Nullable; +import org.jclouds.sqs.domain.Message; +import org.jclouds.sqs.features.MessageApi; +import org.jclouds.sqs.options.ReceiveMessageOptions; + +import com.google.common.annotations.Beta; +import com.google.common.base.Optional; +import com.google.common.base.Supplier; +import com.google.common.collect.FluentIterable; + +/** + * Utilities for interacting with SQS + * + * @author Adrian Cole + */ +@Beta +public class SQS { + + /** + * Returns an iterable that lazy fetches messages until there are none left. + * Note that this method will make multiple network calls. + * + * @param api + * api targeted at the queue in question + * @param messagesPerPage + * how many messages to receive per request (current max: 10) + * @param options + * controls attributes and visibility options + * @return an iterable that lazy fetches messages until there are none left + */ + public static FluentIterable receiveAllAtRate(MessageApi api, int messagesPerPage, + ReceiveMessageOptions options) { + return AdvanceUntilEmptyIterable.create(new MoreMessages(api, messagesPerPage, options)).concat(); + } + + /** + * returns another response of messages on {@link MoreMessages#get} + * + */ + private static class MoreMessages implements Supplier> { + + private static final ReceiveMessageOptions NO_OPTIONS = new ReceiveMessageOptions(); + private MessageApi api; + private int max; + private ReceiveMessageOptions options; + + private MoreMessages(MessageApi api, int max, @Nullable ReceiveMessageOptions options) { + this.api = checkNotNull(api, "message api"); + checkState(max > 0, "max messages per request must be a positive number"); + this.max = max; + this.options = Optional.fromNullable(options).or(NO_OPTIONS); + } + + @Override + public FluentIterable get() { + return api.receive(max, options); + } + + } +} diff --git a/apis/sqs/src/main/java/org/jclouds/sqs/SQSApi.java b/apis/sqs/src/main/java/org/jclouds/sqs/SQSApi.java new file mode 100644 index 0000000000..8804e24904 --- /dev/null +++ b/apis/sqs/src/main/java/org/jclouds/sqs/SQSApi.java @@ -0,0 +1,78 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.sqs; + +import java.net.URI; +import java.util.Set; +import java.util.concurrent.TimeUnit; + +import org.jclouds.concurrent.Timeout; +import org.jclouds.javax.annotation.Nullable; +import org.jclouds.location.Region; +import org.jclouds.location.functions.RegionToEndpointOrProviderIfNull; +import org.jclouds.rest.annotations.Delegate; +import org.jclouds.rest.annotations.EndpointParam; +import org.jclouds.sqs.features.MessageApi; +import org.jclouds.sqs.features.PermissionApi; +import org.jclouds.sqs.features.QueueApi; + +import com.google.common.annotations.Beta; +import com.google.inject.Provides; + +/** + * Provides access to SQS via their REST API. + *

+ * + * @author Adrian Cole + * @see SQSAsyncApi + */ +@Beta +@Timeout(duration = 30, timeUnit = TimeUnit.SECONDS) +public interface SQSApi { + + /** + * + * @return the Region codes configured + */ + @Provides + @Region + Set getConfiguredRegions(); + + /** + * Provides synchronous access to Queue features. + */ + @Delegate + QueueApi getQueueApi(); + + @Delegate + QueueApi getQueueApiForRegion(@EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region); + + /** + * Provides synchronous access to Message features. + */ + @Delegate + MessageApi getMessageApiForQueue(@EndpointParam URI queue); + + /** + * Provides synchronous access to Permission features. + */ + @Delegate + PermissionApi getPermissionApiForQueue(@EndpointParam URI queue); + +} diff --git a/labs/sqs/src/main/java/org/jclouds/sqs/SQSApiMetadata.java b/apis/sqs/src/main/java/org/jclouds/sqs/SQSApiMetadata.java similarity index 92% rename from labs/sqs/src/main/java/org/jclouds/sqs/SQSApiMetadata.java rename to apis/sqs/src/main/java/org/jclouds/sqs/SQSApiMetadata.java index 6c23ba0dba..04081df106 100644 --- a/labs/sqs/src/main/java/org/jclouds/sqs/SQSApiMetadata.java +++ b/apis/sqs/src/main/java/org/jclouds/sqs/SQSApiMetadata.java @@ -20,6 +20,8 @@ package org.jclouds.sqs; import static org.jclouds.aws.reference.AWSConstants.PROPERTY_AUTH_TAG; import static org.jclouds.aws.reference.AWSConstants.PROPERTY_HEADER_TAG; +import static org.jclouds.sqs.config.SQSProperties.CREATE_QUEUE_MAX_RETRIES; +import static org.jclouds.sqs.config.SQSProperties.CREATE_QUEUE_RETRY_INTERVAL; import java.net.URI; import java.util.Properties; @@ -62,6 +64,8 @@ public class SQSApiMetadata extends BaseRestApiMetadata { public static Properties defaultProperties() { Properties properties = BaseRestApiMetadata.defaultProperties(); + properties.setProperty(CREATE_QUEUE_MAX_RETRIES, "60"); + properties.setProperty(CREATE_QUEUE_RETRY_INTERVAL, "1000"); properties.setProperty(PROPERTY_AUTH_TAG, "AWS"); properties.setProperty(PROPERTY_HEADER_TAG, "amz"); return properties; diff --git a/apis/sqs/src/main/java/org/jclouds/sqs/SQSAsyncApi.java b/apis/sqs/src/main/java/org/jclouds/sqs/SQSAsyncApi.java new file mode 100644 index 0000000000..c9a8f0ed56 --- /dev/null +++ b/apis/sqs/src/main/java/org/jclouds/sqs/SQSAsyncApi.java @@ -0,0 +1,82 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.sqs; + +import java.net.URI; +import java.util.Set; + +import org.jclouds.aws.filters.FormSigner; +import org.jclouds.javax.annotation.Nullable; +import org.jclouds.location.Region; +import org.jclouds.location.functions.RegionToEndpointOrProviderIfNull; +import org.jclouds.rest.annotations.Delegate; +import org.jclouds.rest.annotations.EndpointParam; +import org.jclouds.rest.annotations.RequestFilters; +import org.jclouds.rest.annotations.VirtualHost; +import org.jclouds.sqs.features.MessageAsyncApi; +import org.jclouds.sqs.features.PermissionAsyncApi; +import org.jclouds.sqs.features.QueueAsyncApi; + +import com.google.common.annotations.Beta; +import com.google.inject.Provides; + +/** + * Provides access to SQS via REST API. + *

+ * + * @see SQS + * documentation + * @author Adrian Cole + */ +@Beta +@RequestFilters(FormSigner.class) +@VirtualHost +public interface SQSAsyncApi { + /** + * + * @return the Region codes configured + */ + @Provides + @Region + Set getConfiguredRegions(); + + /** + * Provides asynchronous access to Queue features. + */ + @Delegate + QueueAsyncApi getQueueApi(); + + @Delegate + QueueAsyncApi getQueueApiForRegion( + @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region); + + /** + * Provides asynchronous access to Message features. + */ + @Delegate + MessageAsyncApi getMessageApiForQueue(@EndpointParam URI queue); + + /** + * Provides asynchronous access to Permission features. + */ + @Delegate + PermissionAsyncApi getPermissionApiForQueue(@EndpointParam URI queue); + +} diff --git a/apis/sqs/src/main/java/org/jclouds/sqs/binders/BindAttributeNamesToIndexedFormParams.java b/apis/sqs/src/main/java/org/jclouds/sqs/binders/BindAttributeNamesToIndexedFormParams.java new file mode 100644 index 0000000000..13edefe1f6 --- /dev/null +++ b/apis/sqs/src/main/java/org/jclouds/sqs/binders/BindAttributeNamesToIndexedFormParams.java @@ -0,0 +1,52 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.sqs.binders; + +import static com.google.common.base.Preconditions.checkNotNull; + +import javax.inject.Singleton; + +import org.jclouds.http.HttpRequest; +import org.jclouds.rest.Binder; + +import com.google.common.collect.ImmutableMultimap; +import com.google.common.collect.ImmutableMultimap.Builder; + +/** + * Binds the Iterable to form parameters named with AttributeName.index + * + * @author Adrian Cole + */ +@Singleton +public class BindAttributeNamesToIndexedFormParams implements Binder { + + @SuppressWarnings("unchecked") + @Override + public R bindToRequest(R request, Object input) { + Iterable values = Iterable.class.cast(checkNotNull(input, "attributeNames")); + Builder builder = ImmutableMultimap.builder(); + int i = 0; + for (Object o : values) { + builder.put("AttributeName." + (i++ + 1), o.toString()); + } + ImmutableMultimap forms = builder.build(); + return (R) (forms.size() == 0 ? request : request.toBuilder().replaceFormParams(forms).build()); + } + +} diff --git a/apis/sqs/src/main/java/org/jclouds/sqs/binders/BindChangeMessageVisibilityBatchRequestEntryToIndexedFormParams.java b/apis/sqs/src/main/java/org/jclouds/sqs/binders/BindChangeMessageVisibilityBatchRequestEntryToIndexedFormParams.java new file mode 100644 index 0000000000..1a722aa84c --- /dev/null +++ b/apis/sqs/src/main/java/org/jclouds/sqs/binders/BindChangeMessageVisibilityBatchRequestEntryToIndexedFormParams.java @@ -0,0 +1,69 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.sqs.binders; + +import java.util.Map; + +import org.jclouds.aws.binders.BindTableToIndexedFormParams; +import org.jclouds.http.HttpRequest; +import org.jclouds.rest.MapBinder; + +import com.google.common.base.Function; +import com.google.common.collect.ImmutableTable; +import com.google.common.collect.ImmutableTable.Builder; +import com.google.common.collect.Maps; + +/** + * @author Adrian Cole + */ +public class BindChangeMessageVisibilityBatchRequestEntryToIndexedFormParams extends BindTableToIndexedFormParams + implements MapBinder { + + protected BindChangeMessageVisibilityBatchRequestEntryToIndexedFormParams() { + super("ChangeMessageVisibilityBatchRequestEntry.%d.Id", + "ChangeMessageVisibilityBatchRequestEntry.%d.ReceiptHandle", + "ChangeMessageVisibilityBatchRequestEntry.%d.VisibilityTimeout"); + } + + public Map idReceiptHandle(Iterable input) { + return Maps.uniqueIndex((Iterable) input, new Function() { + int index = 1; + + @Override + public String apply(String input) { + return index++ + ""; + } + }); + } + + @SuppressWarnings("unchecked") + @Override + public R bindToRequest(R request, Map postParams) { + Map idReceiptHandle = (Map) postParams.get("idReceiptHandle"); + if (idReceiptHandle == null) { + idReceiptHandle = idReceiptHandle((Iterable) postParams.get("receiptHandles")); + } + int visibilityTimeout = (Integer) postParams.get("visibilityTimeout"); + + Builder builder = ImmutableTable.builder(); + for (Map.Entry entry : idReceiptHandle.entrySet()) + builder.put(entry.getKey(), entry.getValue(), visibilityTimeout); + return bindToRequest(request, (Object) builder.build()); + } +} diff --git a/apis/sqs/src/main/java/org/jclouds/sqs/binders/BindDeleteMessageBatchRequestEntryToIndexedFormParams.java b/apis/sqs/src/main/java/org/jclouds/sqs/binders/BindDeleteMessageBatchRequestEntryToIndexedFormParams.java new file mode 100644 index 0000000000..dd1ba5e9ad --- /dev/null +++ b/apis/sqs/src/main/java/org/jclouds/sqs/binders/BindDeleteMessageBatchRequestEntryToIndexedFormParams.java @@ -0,0 +1,31 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.sqs.binders; + +import org.jclouds.aws.binders.BindMapToIndexedFormParams; + +/** + * @author Adrian Cole + */ +public class BindDeleteMessageBatchRequestEntryToIndexedFormParams extends BindMapToIndexedFormParams { + + protected BindDeleteMessageBatchRequestEntryToIndexedFormParams() { + super("DeleteMessageBatchRequestEntry.%d.Id", "DeleteMessageBatchRequestEntry.%d.ReceiptHandle"); + } +} diff --git a/demos/tweetstore/gae-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/config/LoggingConfig.java b/apis/sqs/src/main/java/org/jclouds/sqs/binders/BindSendMessageBatchRequestEntryToIndexedFormParams.java similarity index 67% rename from demos/tweetstore/gae-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/config/LoggingConfig.java rename to apis/sqs/src/main/java/org/jclouds/sqs/binders/BindSendMessageBatchRequestEntryToIndexedFormParams.java index 9852ae59ce..748c7d0fcb 100644 --- a/demos/tweetstore/gae-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/config/LoggingConfig.java +++ b/apis/sqs/src/main/java/org/jclouds/sqs/binders/BindSendMessageBatchRequestEntryToIndexedFormParams.java @@ -16,17 +16,16 @@ * specific language governing permissions and limitations * under the License. */ -package org.jclouds.demo.tweetstore.config; +package org.jclouds.sqs.binders; -import static org.jclouds.logging.LoggingModules.firstOrJDKLoggingModule; - -import org.jclouds.logging.Logger.LoggerFactory; +import org.jclouds.aws.binders.BindMapToIndexedFormParams; /** - * Spring config that provides a logger. - * - * @author Andrew Phillips + * @author Adrian Cole */ -abstract class LoggingConfig { - protected static final LoggerFactory LOGGER_FACTORY = firstOrJDKLoggingModule().createLoggerFactory(); +public class BindSendMessageBatchRequestEntryToIndexedFormParams extends BindMapToIndexedFormParams { + + protected BindSendMessageBatchRequestEntryToIndexedFormParams() { + super("SendMessageBatchRequestEntry.%d.Id", "SendMessageBatchRequestEntry.%d.MessageBody"); + } } diff --git a/apis/sqs/src/main/java/org/jclouds/sqs/binders/BindSendMessageBatchRequestEntryWithDelaysToIndexedFormParams.java b/apis/sqs/src/main/java/org/jclouds/sqs/binders/BindSendMessageBatchRequestEntryWithDelaysToIndexedFormParams.java new file mode 100644 index 0000000000..0727a47989 --- /dev/null +++ b/apis/sqs/src/main/java/org/jclouds/sqs/binders/BindSendMessageBatchRequestEntryWithDelaysToIndexedFormParams.java @@ -0,0 +1,68 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.sqs.binders; + +import java.util.Map; + +import org.jclouds.aws.binders.BindTableToIndexedFormParams; +import org.jclouds.http.HttpRequest; +import org.jclouds.rest.MapBinder; + +import com.google.common.base.Function; +import com.google.common.collect.ImmutableTable; +import com.google.common.collect.ImmutableTable.Builder; +import com.google.common.collect.Maps; + +/** + * @author Adrian Cole + */ +public class BindSendMessageBatchRequestEntryWithDelaysToIndexedFormParams extends BindTableToIndexedFormParams + implements MapBinder { + + protected BindSendMessageBatchRequestEntryWithDelaysToIndexedFormParams() { + super("SendMessageBatchRequestEntry.%d.Id", "SendMessageBatchRequestEntry.%d.MessageBody", + "SendMessageBatchRequestEntry.%d.DelaySeconds"); + } + + public Map idMessageBody(Iterable input) { + return Maps.uniqueIndex((Iterable) input, new Function() { + int index = 1; + + @Override + public String apply(String input) { + return index++ + ""; + } + }); + } + + @SuppressWarnings("unchecked") + @Override + public R bindToRequest(R request, Map postParams) { + Map idMessageBody = (Map) postParams.get("idMessageBody"); + if (idMessageBody == null) { + idMessageBody = idMessageBody((Iterable) postParams.get("messageBodies")); + } + int delaySeconds = (Integer) postParams.get("delaySeconds"); + + Builder builder = ImmutableTable.builder(); + for (Map.Entry entry : idMessageBody.entrySet()) + builder.put(entry.getKey(), entry.getValue(), delaySeconds); + return bindToRequest(request, (Object) builder.build()); + } +} diff --git a/apis/sqs/src/main/java/org/jclouds/sqs/config/SQSProperties.java b/apis/sqs/src/main/java/org/jclouds/sqs/config/SQSProperties.java new file mode 100644 index 0000000000..5833672c79 --- /dev/null +++ b/apis/sqs/src/main/java/org/jclouds/sqs/config/SQSProperties.java @@ -0,0 +1,48 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.sqs.config; + + +/** + * Configuration properties and constants used in SQS connections. + * + * @author Adrian Cole + */ +public interface SQSProperties { + + /** + * Integer property. + *

+ * When creating a queue, you can encounter + * {@code AWS.SimpleQueueService.QueueDeletedRecently}, which is typically a + * resolvable error. default tries are 60, + */ + public static final String CREATE_QUEUE_MAX_RETRIES = "jclouds.sqs.create-queue.max-retries"; + + /** + * Long property. + *

+ * When creating a queue, you can encounter + * {@code AWS.SimpleQueueService.QueueDeletedRecently}, which is typically a + * resolvable error. default interval between tries is 1000 milliseconds (1 + * second). + */ + public static final String CREATE_QUEUE_RETRY_INTERVAL = "jclouds.sqs.create-queue.retry-interval"; + +} diff --git a/apis/sqs/src/main/java/org/jclouds/sqs/config/SQSRestClientModule.java b/apis/sqs/src/main/java/org/jclouds/sqs/config/SQSRestClientModule.java new file mode 100644 index 0000000000..09b4882d07 --- /dev/null +++ b/apis/sqs/src/main/java/org/jclouds/sqs/config/SQSRestClientModule.java @@ -0,0 +1,73 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.sqs.config; + +import java.util.Map; + +import org.jclouds.aws.config.FormSigningRestClientModule; +import org.jclouds.http.HttpErrorHandler; +import org.jclouds.http.HttpRetryHandler; +import org.jclouds.http.annotation.ClientError; +import org.jclouds.http.annotation.Redirection; +import org.jclouds.http.annotation.ServerError; +import org.jclouds.rest.ConfiguresRestClient; +import org.jclouds.sqs.SQSApi; +import org.jclouds.sqs.SQSAsyncApi; +import org.jclouds.sqs.features.MessageApi; +import org.jclouds.sqs.features.MessageAsyncApi; +import org.jclouds.sqs.features.PermissionApi; +import org.jclouds.sqs.features.PermissionAsyncApi; +import org.jclouds.sqs.features.QueueApi; +import org.jclouds.sqs.features.QueueAsyncApi; +import org.jclouds.sqs.handlers.ParseSQSErrorFromXmlContent; +import org.jclouds.sqs.handlers.SQSErrorRetryHandler; + +import com.google.common.collect.ImmutableMap; +import com.google.common.reflect.TypeToken; + +/** + * Configures the SQS connection. + * + * @author Adrian Cole + */ +@ConfiguresRestClient +public class SQSRestClientModule extends FormSigningRestClientModule { + public static final Map, Class> DELEGATE_MAP = ImmutableMap., Class> builder()// + .put(QueueApi.class, QueueAsyncApi.class) + .put(MessageApi.class, MessageAsyncApi.class) + .put(PermissionApi.class, PermissionAsyncApi.class) + .build(); + + public SQSRestClientModule() { + super(TypeToken.of(SQSApi.class), TypeToken.of(SQSAsyncApi.class), DELEGATE_MAP); + } + + @Override + protected void bindErrorHandlers() { + bind(HttpErrorHandler.class).annotatedWith(Redirection.class).to(ParseSQSErrorFromXmlContent.class); + bind(HttpErrorHandler.class).annotatedWith(ClientError.class).to(ParseSQSErrorFromXmlContent.class); + bind(HttpErrorHandler.class).annotatedWith(ServerError.class).to(ParseSQSErrorFromXmlContent.class); + } + + @Override + protected void bindRetryHandlers() { + bind(HttpRetryHandler.class).annotatedWith(ClientError.class).to(SQSErrorRetryHandler.class); + } + +} diff --git a/apis/sqs/src/main/java/org/jclouds/sqs/domain/Action.java b/apis/sqs/src/main/java/org/jclouds/sqs/domain/Action.java new file mode 100644 index 0000000000..7a1f886e63 --- /dev/null +++ b/apis/sqs/src/main/java/org/jclouds/sqs/domain/Action.java @@ -0,0 +1,80 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.sqs.domain; + +import com.google.common.base.CaseFormat; + +/** + * + * The action you want to allow for the specified principal. + * + * @see + * @author Adrian Cole + */ +public enum Action { + /** + * This permission type grants the following actions to a principal on a + * shared queue: receive messages, send messages, delete messages, change a + * message's visibility, get a queue's attributes. + */ + ALL, + /** + * This grants permission to receive messages in the queue. + */ + RECEIVE_MESSAGE, + /** + * This grants permission to send messages to the queue. SendMessageBatch + * inherits permissions associated with SendMessage. + */ + SEND_MESSAGE, + /** + * This grants permission to delete messages from the queue. + * DeleteMessageBatch inherits permissions associated with DeleteMessage. + */ + DELETE_MESSAGE, + /** + * This grants permission to extend or terminate the read lock timeout of a + * specified message. ChangeMessageVisibilityBatch inherits permissions + * associated with ChangeMessageVisibility. For more information about + * visibility timeout, see Visibility Timeout. For more information about + * this permission type, see the ChangeMessageVisibility operation. + */ + CHANGE_MESSAGE_VISIBILITY, + /** + * This grants permission to receive all of the queue attributes except the + * policy, which can only be accessed by the queue's owner. For more + * information, see the GetQueueAttributes operation. + */ + GET_QUEUE_ATTRIBUTES, + /** + * This grants permission to get the url of a queue by name. + */ + GET_QUEUE_URL; + + public String value() { + return this == ALL ? "*" : CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name()); + } + + @Override + public String toString() { + return value(); + } +} diff --git a/apis/sqs/src/main/java/org/jclouds/sqs/domain/Attribute.java b/apis/sqs/src/main/java/org/jclouds/sqs/domain/Attribute.java new file mode 100644 index 0000000000..048c6922d1 --- /dev/null +++ b/apis/sqs/src/main/java/org/jclouds/sqs/domain/Attribute.java @@ -0,0 +1,88 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.sqs.domain; + +/** + * + * The action you want to allow for the specified principal. + * + * @see + * @author Adrian Cole + */ +public interface Attribute { + + /** + * approximate number of visible messages in a queue. + */ + public static final String APPROXIMATE_NUMBER_OF_MESSAGES = "ApproximateNumberOfMessages"; + /** + * approximate number of messages that are not timed-out and not deleted. + */ + public static final String APPROXIMATE_NUMBER_OF_MESSAGES_NOT_VISIBLE = "ApproximateNumberOfMessagesNotVisible"; + + /** + * approximate number of messages that are not visible because you have set a + * positive delay value on the queue + */ + public static final String APPROXIMATE_NUMBER_OF_MESSAGES_DELAYED = "ApproximateNumberOfMessagesDelayed"; + + /** + * visibility timeout for the queue. + */ + public static final String VISIBILITY_TIMEOUT = "VisibilityTimeout"; + + /** + * time when the queue was created (epoch time in seconds). + */ + public static final String CREATED_TIMESTAMP = "CreatedTimestamp"; + + /** + * time when the queue was last changed (epoch time in seconds). + */ + public static final String LAST_MODIFIED_TIMESTAMP = "LastModifiedTimestamp"; + + /** + * queue's policy. + */ + public static final String POLICY = "Policy"; + + /** + * limit of how many bytes a message can contain before Amazon SQS rejects + * it. + */ + public static final String MAXIMUM_MESSAGE_SIZE = "MaximumMessageSize"; + + /** + * number of seconds Amazon SQS retains a message. + */ + public static final String MESSAGE_RETENTION_PERIOD = "MessageRetentionPeriod"; + + /** + * queue's Amazon resource name (ARN). + */ + public static final String QUEUE_ARN = "QueueArn"; + + /** + * The time in seconds that the delivery of all messages in the queue will be + * delayed. + */ + public static final String DELAY_SECONDS = "DelaySeconds"; +} diff --git a/apis/sqs/src/main/java/org/jclouds/sqs/domain/BatchError.java b/apis/sqs/src/main/java/org/jclouds/sqs/domain/BatchError.java new file mode 100644 index 0000000000..45696f4d70 --- /dev/null +++ b/apis/sqs/src/main/java/org/jclouds/sqs/domain/BatchError.java @@ -0,0 +1,155 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.sqs.domain; + +import static com.google.common.base.Preconditions.checkNotNull; + +import com.google.common.base.Objects; + +/** + * + * @see doc + * + * @author Adrian Cole + */ +public class BatchError { + + public static Builder builder() { + return new Builder(); + } + + public Builder toBuilder() { + return builder().fromErrorEntry(this); + } + + public static class Builder { + + private String id; + private boolean senderFault; + private String code; + private String message; + + /** + * @see BatchError#getId() + */ + public Builder id(String id) { + this.id = id; + return this; + } + + /** + * @see BatchError#isSenderFault() + */ + public Builder senderFault(boolean senderFault) { + this.senderFault = senderFault; + return this; + } + + /** + * @see BatchError#getCode() + */ + public Builder code(String code) { + this.code = code; + return this; + } + + /** + * @see BatchError#getMessage() + */ + public Builder message(String message) { + this.message = message; + return this; + } + + public BatchError build() { + return new BatchError(id, senderFault, code, message); + } + + public Builder fromErrorEntry(BatchError in) { + return id(in.getId()).senderFault(in.isSenderFault()).code(in.getCode()).message(in.getMessage()); + } + } + + private final String id; + private final boolean senderFault; + private final String code; + private final String message; + + private BatchError(String id, boolean senderFault, String code, String message) { + this.id = checkNotNull(id, "id"); + this.senderFault = checkNotNull(senderFault, "senderFault of %s", id); + this.code = checkNotNull(code, "code of %s", id); + this.message = checkNotNull(message, "message of %s", id); + } + + /** + * The Id name that you assigned to the message. + */ + public String getId() { + return id; + } + + /** + * + */ + public boolean isSenderFault() { + return senderFault; + } + + /** + * A short string description of the error. + */ + public String getCode() { + return code; + } + + /** + * A description of the error. + */ + public String getMessage() { + return message; + } + + @Override + public int hashCode() { + return Objects.hashCode(id); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null || getClass() != obj.getClass()) + return false; + BatchError that = BatchError.class.cast(obj); + return Objects.equal(this.id, that.id); + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return Objects.toStringHelper(this).omitNullValues().add("id", id).add("senderFault", senderFault) + .add("message", message).add("code", code).toString(); + } + +} diff --git a/apis/sqs/src/main/java/org/jclouds/sqs/domain/BatchResult.java b/apis/sqs/src/main/java/org/jclouds/sqs/domain/BatchResult.java new file mode 100644 index 0000000000..cbb2d4b496 --- /dev/null +++ b/apis/sqs/src/main/java/org/jclouds/sqs/domain/BatchResult.java @@ -0,0 +1,146 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.sqs.domain; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.Map; + +import com.google.common.base.Function; +import com.google.common.base.Objects; +import com.google.common.collect.ForwardingMap; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Maps; + +/** + * + * @see doc + * + * @author Adrian Cole + */ +public class BatchResult extends ForwardingMap { + + public static Builder builder() { + return new Builder(); + } + + public Builder toBuilder() { + return BatchResult. builder().fromBatchResult(this); + } + + public static class Builder { + + private ImmutableMap.Builder results = ImmutableMap. builder(); + private ImmutableSet.Builder errors = ImmutableSet. builder(); + + /** + * @see BatchResult#getErrors() + */ + public Builder addError(BatchError error) { + this.errors.add(checkNotNull(error, "error")); + return this; + } + + /** + * @see BatchResult#getErrors() + */ + public Builder errors(Iterable errors) { + this.errors = ImmutableSet. builder().addAll(checkNotNull(errors, "errors")); + return this; + } + + /** + * @see BatchResult#get + */ + public Builder putAll(Map results) { + this.results.putAll(checkNotNull(results, "results")); + return this; + } + + /** + * @see BatchResult#get + */ + public Builder put(String name, V value) { + this.results.put(checkNotNull(name, "name"), checkNotNull(value, "value")); + return this; + } + + public BatchResult build() { + return new BatchResult(results.build(), errors.build()); + } + + public Builder fromBatchResult(BatchResult in) { + return putAll(in).errors(in.getErrors().values()); + } + } + + private final Map results; + private final Map errors; + + private BatchResult(Map results, Iterable errors) { + this.results = ImmutableMap.copyOf(checkNotNull(results, "results")); + this.errors = Maps.uniqueIndex(checkNotNull(errors, "errors"), new Function() { + @Override + public String apply(BatchError in) { + return in.getId(); + } + + }); + } + + @Override + protected Map delegate() { + return results; + } + + /** + * Errors indexed by requestor supplied id + */ + public Map getErrors() { + return errors; + } + + @Override + public int hashCode() { + return Objects.hashCode(results, errors); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null || getClass() != obj.getClass()) + return false; + @SuppressWarnings("unchecked") + BatchResult that = BatchResult.class.cast(obj); + return Objects.equal(this.results, that.results) && Objects.equal(this.errors, that.errors); + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return Objects.toStringHelper(this).omitNullValues().add("results", results).add("errors", errors).toString(); + } + +} diff --git a/labs/sqs/src/main/java/org/jclouds/sqs/domain/Message.java b/apis/sqs/src/main/java/org/jclouds/sqs/domain/Message.java similarity index 100% rename from labs/sqs/src/main/java/org/jclouds/sqs/domain/Message.java rename to apis/sqs/src/main/java/org/jclouds/sqs/domain/Message.java diff --git a/labs/sqs/src/main/java/org/jclouds/sqs/domain/MessageIdAndMD5.java b/apis/sqs/src/main/java/org/jclouds/sqs/domain/MessageIdAndMD5.java similarity index 100% rename from labs/sqs/src/main/java/org/jclouds/sqs/domain/MessageIdAndMD5.java rename to apis/sqs/src/main/java/org/jclouds/sqs/domain/MessageIdAndMD5.java diff --git a/apis/sqs/src/main/java/org/jclouds/sqs/domain/QueueAttributes.java b/apis/sqs/src/main/java/org/jclouds/sqs/domain/QueueAttributes.java new file mode 100644 index 0000000000..d2e1e2c4bc --- /dev/null +++ b/apis/sqs/src/main/java/org/jclouds/sqs/domain/QueueAttributes.java @@ -0,0 +1,314 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.sqs.domain; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.Date; + +import com.google.common.base.Objects; +import com.google.common.base.Optional; + +/** + * + * @author Adrian Cole + * + * @see + */ +public class QueueAttributes { + public static Builder builder() { + return new ConcreteBuilder(); + } + + public Builder toBuilder() { + return new ConcreteBuilder().fromQueueAttributes(this); + } + + public static abstract class Builder> { + protected abstract T self(); + + protected String queueArn; + protected long approximateNumberOfMessages; + protected long approximateNumberOfMessagesNotVisible; + protected long approximateNumberOfMessagesDelayed; + protected int visibilityTimeout; + protected Date createdTimestamp; + protected Date lastModifiedTimestamp; + protected Optional rawPolicy = Optional.absent(); + protected int maximumMessageSize; + protected int messageRetentionPeriod; + protected int delaySeconds; + + /** + * @see QueueAttributes#getQueueArn() + */ + public T queueArn(String queueArn) { + this.queueArn = queueArn; + return self(); + } + + /** + * @see QueueAttributes#getApproximateNumberOfMessages() + */ + public T approximateNumberOfMessages(long approximateNumberOfMessages) { + this.approximateNumberOfMessages = approximateNumberOfMessages; + return self(); + } + + /** + * @see QueueAttributes#getApproximateNumberOfMessagesNotVisible() + */ + public T approximateNumberOfMessagesNotVisible(long approximateNumberOfMessagesNotVisible) { + this.approximateNumberOfMessagesNotVisible = approximateNumberOfMessagesNotVisible; + return self(); + } + + /** + * @see QueueAttributes#getApproximateNumberOfMessagesDelayed() + */ + public T approximateNumberOfMessagesDelayed(long approximateNumberOfMessagesDelayed) { + this.approximateNumberOfMessagesDelayed = approximateNumberOfMessagesDelayed; + return self(); + } + + /** + * @see QueueAttributes#getVisibilityTimeout() + */ + public T visibilityTimeout(int visibilityTimeout) { + this.visibilityTimeout = visibilityTimeout; + return self(); + } + + /** + * @see QueueAttributes#getCreatedTimestamp() + */ + public T createdTimestamp(Date createdTimestamp) { + this.createdTimestamp = createdTimestamp; + return self(); + } + + /** + * @see QueueAttributes#getLastModifiedTimestamp() + */ + public T lastModifiedTimestamp(Date lastModifiedTimestamp) { + this.lastModifiedTimestamp = lastModifiedTimestamp; + return self(); + } + + /** + * @see QueueAttributes#getRawPolicy() + */ + public T rawPolicy(String rawPolicy) { + this.rawPolicy = Optional.fromNullable(rawPolicy); + return self(); + } + + /** + * @see QueueAttributes#getMaximumMessageSize() + */ + public T maximumMessageSize(int maximumMessageSize) { + this.maximumMessageSize = maximumMessageSize; + return self(); + } + + /** + * @see QueueAttributes#getMessageRetentionPeriod() + */ + public T messageRetentionPeriod(int messageRetentionPeriod) { + this.messageRetentionPeriod = messageRetentionPeriod; + return self(); + } + + /** + * @see QueueAttributes#getDelaySeconds() + */ + public T delaySeconds(int delaySeconds) { + this.delaySeconds = delaySeconds; + return self(); + } + + public QueueAttributes build() { + return new QueueAttributes(queueArn, approximateNumberOfMessages, approximateNumberOfMessagesNotVisible, + approximateNumberOfMessagesDelayed, visibilityTimeout, createdTimestamp, lastModifiedTimestamp, + rawPolicy, maximumMessageSize, messageRetentionPeriod, delaySeconds); + } + + public T fromQueueAttributes(QueueAttributes in) { + return queueArn(in.queueArn).approximateNumberOfMessages(in.approximateNumberOfMessages) + .approximateNumberOfMessagesNotVisible(in.approximateNumberOfMessagesNotVisible) + .approximateNumberOfMessagesDelayed(in.approximateNumberOfMessagesDelayed) + .visibilityTimeout(in.visibilityTimeout).createdTimestamp(in.createdTimestamp) + .lastModifiedTimestamp(in.lastModifiedTimestamp).rawPolicy(in.rawPolicy.orNull()) + .maximumMessageSize(in.maximumMessageSize).messageRetentionPeriod(in.messageRetentionPeriod) + .delaySeconds(in.delaySeconds); + + } + } + + private static class ConcreteBuilder extends Builder { + @Override + protected ConcreteBuilder self() { + return this; + } + } + + protected final long approximateNumberOfMessages; + protected final long approximateNumberOfMessagesNotVisible; + protected final int visibilityTimeout; + protected final Date createdTimestamp; + protected final Date lastModifiedTimestamp; + protected final long approximateNumberOfMessagesDelayed; + protected final Optional rawPolicy; + protected final int maximumMessageSize; + protected final int messageRetentionPeriod; + protected final String queueArn; + protected int delaySeconds; + + protected QueueAttributes(String queueArn, long approximateNumberOfMessages, + long approximateNumberOfMessagesNotVisible, long approximateNumberOfMessagesDelayed, int visibilityTimeout, + Date createdTimestamp, Date lastModifiedTimestamp, Optional rawPolicy, int maximumMessageSize, + int messageRetentionPeriod, int delaySeconds) { + this.queueArn = checkNotNull(queueArn, "queueArn"); + this.approximateNumberOfMessages = approximateNumberOfMessages; + this.approximateNumberOfMessagesNotVisible = approximateNumberOfMessagesNotVisible; + this.approximateNumberOfMessagesDelayed = approximateNumberOfMessagesDelayed; + this.visibilityTimeout = visibilityTimeout; + this.createdTimestamp = checkNotNull(createdTimestamp, "createdTimestamp of %s", queueArn); + this.lastModifiedTimestamp = checkNotNull(lastModifiedTimestamp, "lastModifiedTimestamp of %s", queueArn); + this.rawPolicy = checkNotNull(rawPolicy, "rawPolicy of %s", queueArn); + this.maximumMessageSize = maximumMessageSize; + this.messageRetentionPeriod = messageRetentionPeriod; + this.delaySeconds = delaySeconds; + } + + /** + * @see Attribute#QUEUE_ARN + */ + public String getQueueArn() { + return queueArn; + } + + /** + * @see Attribute#APPROXIMATE_NUMBER_OF_MESSAGES + */ + public long getApproximateNumberOfMessages() { + return approximateNumberOfMessages; + } + + /** + * @see Attribute#APPROXIMATE_NUMBER_OF_MESSAGES_NOT_VISIBLE + */ + public long getApproximateNumberOfMessagesNotVisible() { + return approximateNumberOfMessagesNotVisible; + } + + /** + * @see Attribute#APPROXIMATE_NUMBER_OF_MESSAGES_DELAYED + */ + public long getApproximateNumberOfMessagesDelayed() { + return approximateNumberOfMessagesDelayed; + } + + /** + * @see Attribute#VISIBILITY_TIMEOUT + */ + public int getVisibilityTimeout() { + return visibilityTimeout; + } + + /** + * @see Attribute#CREATED_TIMESTAMP + */ + public Date getCreatedTimestamp() { + return createdTimestamp; + } + + /** + * @see Attribute#LAST_MODIFIED_TIMESTAMP + */ + public Date getLastModifiedTimestamp() { + return lastModifiedTimestamp; + } + + /** + * Note this is in raw Json + * + * @see Attribute#POLICY + */ + public Optional getRawPolicy() { + return rawPolicy; + } + + /** + * @see Attribute#MAXIMUM_MESSAGE_SIZE + */ + public int getMaximumMessageSize() { + return maximumMessageSize; + } + + /** + * @see Attribute#MESSAGE_RETENTION_PERIOD + */ + public int getMessageRetentionPeriod() { + return messageRetentionPeriod; + } + + /** + * @see Attribute#DELAY_SECONDS + */ + public int getDelaySeconds() { + return delaySeconds; + } + + @Override + public int hashCode() { + return Objects.hashCode(queueArn); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + QueueAttributes other = (QueueAttributes) obj; + return Objects.equal(this.queueArn, other.queueArn); + + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return Objects.toStringHelper(this).omitNullValues().add("queueArn", queueArn) + .add("approximateNumberOfMessages", approximateNumberOfMessages) + .add("approximateNumberOfMessagesNotVisible", approximateNumberOfMessagesNotVisible) + .add("approximateNumberOfMessagesDelayed", approximateNumberOfMessagesDelayed) + .add("visibilityTimeout", visibilityTimeout).add("createdTimestamp", createdTimestamp) + .add("lastModifiedTimestamp", lastModifiedTimestamp).add("rawPolicy", rawPolicy.orNull()) + .add("maximumMessageSize", maximumMessageSize).add("messageRetentionPeriod", messageRetentionPeriod) + .add("delaySeconds", delaySeconds).toString(); + } + +} diff --git a/apis/sqs/src/main/java/org/jclouds/sqs/features/MessageApi.java b/apis/sqs/src/main/java/org/jclouds/sqs/features/MessageApi.java new file mode 100644 index 0000000000..1ff505b034 --- /dev/null +++ b/apis/sqs/src/main/java/org/jclouds/sqs/features/MessageApi.java @@ -0,0 +1,419 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.sqs.features; + +import java.net.URI; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +import org.jclouds.concurrent.Timeout; +import org.jclouds.sqs.domain.BatchResult; +import org.jclouds.sqs.domain.Message; +import org.jclouds.sqs.domain.MessageIdAndMD5; +import org.jclouds.sqs.options.ReceiveMessageOptions; +import org.jclouds.sqs.options.SendMessageOptions; + +import com.google.common.collect.FluentIterable; +import com.google.common.collect.Table; + +/** + * Provides access to SQS via their REST API. + *

+ * + * @see MessageAsyncApi + * @author Adrian Cole + */ +@Timeout(duration = 30, timeUnit = TimeUnit.SECONDS) +public interface MessageApi { + + /** + * The DeleteMessage action deletes the specified message from the specified + * queue. You specify the message by using the message's receipt handle and + * not the message ID you received when you sent the message. Even if the + * message is locked by another reader due to the visibility timeout setting, + * it is still deleted from the queue. If you leave a message in the queue + * for more than 4 days, SQS automatically deletes it. + * + *

Note

+ * + * The receipt handle is associated with a specific instance of receiving the + * message. If you receive a message more than once, the receipt handle you + * get each time you receive the message is different. When you request + * DeleteMessage, if you don't provide the most recently received receipt + * handle for the message, the request will still succeed, but the message + * might not be deleted. + * + *

Important

+ * + * It is possible you will receive a message even after you have deleted it. + * This might happen on rare occasions if one of the servers storing a copy + * of the message is unavailable when you request to delete the message. The + * copy remains on the server and might be returned to you again on a + * subsequent receive request. You should create your system to be idempotent + * so that receiving a particular message more than once is not a problem. + * + * @param queue + * the queue the message is in + * @param receiptHandle + * The receipt handle associated with the message you want to + * delete. + */ + void delete(String receiptHandle); + + /** + * Currently, you can send up to 10 {@link #delete} requests. + * + *

Example usage

+ * + *
+    * BatchResult results = api.delete(ImmutableMap.builder()
+    *                                  .put("id1", "handle1")
+    *                                  .put("id2", "handle2")
+    *                                  .build());
+    * 
+    * if (results.keySet().equals(ImmutableSet.of("id", "id2"))
+    *    // all ok
+    * else
+    *   results.getErrors();
+    * 
+ * + * @param idReceiptHandle + * id for correlating the result to receipt handle + * @return result that contains success or errors of the operation + * @see #delete(String) + */ + BatchResult delete(Map idReceiptHandle); + + /** + * Same as {@link #delete(Map)}, except that we generate numeric ids starting + * with {@code 1} + * + * @param receiptHandles + * receipt handles to delete + * @see #delete(Map) + */ + BatchResult delete(Iterable receiptHandles); + + /** + * The ChangeMessageVisibility action changes the visibility timeout of a + * specified message in a queue to a new value. The maximum allowed timeout + * value you can set the value to is 12 hours. This means you can't extend + * the timeout of a message in an existing queue to more than a total + * visibility timeout of 12 hours. (For more information visibility timeout, + * see Visibility Timeout in the Amazon SQS Developer Guide.) + * + * For example, let's say the timeout for the queue is 30 seconds, and you + * receive a message. Once you're 20 seconds into the timeout for that + * message (i.e., you have 10 seconds left), you extend it by 60 seconds by + * calling ChangeMessageVisibility with VisibilityTimeoutset to 60 seconds. + * You have then changed the remaining visibility timeout from 10 seconds to + * 60 seconds. + * + *

Important

+ * + * If you attempt to set the VisibilityTimeout to an amount more than the + * maximum time left, Amazon SQS returns an error. It will not automatically + * recalculate and increase the timeout to the maximum time remaining. + * + *

Important

+ * + * Unlike with a queue, when you change the visibility timeout for a specific + * message, that timeout value is applied immediately but is not saved in + * memory for that message. If you don't delete a message after it is + * received, the visibility timeout for the message the next time it is + * received reverts to the original timeout value, not the value you set with + * the ChangeMessageVisibility action. + * + * @param queue + * the queue the message is in + * @param receiptHandle + * The receipt handle associated with the message whose visibility + * timeout you want to change. This parameter is returned by the + * ReceiveMessage action. + * @param visibilityTimeout + * The new value for the message's visibility timeout (in seconds) + * from 0 to 43200 (maximum 12 hours) + */ + void changeVisibility(String receiptHandle, int visibilityTimeout); + + /** + * Currently, you can send up to 10 {@link #changeVisibility} requests. + * + * action.

Example usage

+ * + *
+    * BatchResult results = api.changeVisibility(ImmutableTable.builder()
+    *                                  .put("id1", "handle1", 45)
+    *                                  .put("id2", "handle2", 10)
+    *                                  .build());
+    * 
+    * if (results.keySet().equals(ImmutableSet.of("id", "id2"))
+    *    // all ok
+    * else
+    *   results.getErrors();
+    * 
+ * + * @param idReceiptHandleVisibilityTimeout + * id for correlating the result, receipt handle, and visibility + * timeout + * @return result that contains success or errors of the operation + * @see #changeVisibility(String, int) + */ + BatchResult changeVisibility(Table idReceiptHandleVisibilityTimeout); + + /** + * Same as {@link #changeVisibility(Table)}, except that we generate numeric + * ids starting with {@code 1} + * + * @param receiptHandleVisibilityTimeout + * receipt handle to visibility timeout + * @see #changeVisibility(Table) + */ + BatchResult changeVisibility(Map receiptHandleVisibilityTimeout); + + /** + * Currently, you can send up to 10 {@link #changeVisibility} requests. + * + * action.

Example usage

+ * + *
+    * BatchResult results = api.changeVisibility(ImmutableMap.builder()
+    *                                  .put("id1", "handle1")
+    *                                  .put("id2", "handle2")
+    *                                  .build(), 45);
+    * 
+    * if (results.keySet().equals(ImmutableSet.of("id", "id2"))
+    *    // all ok
+    * else
+    *   results.getErrors();
+    * 
+ * + * @param idReceiptHandle + * id for correlating the result to receipt handle + * @param visibilityTimeout + * The new value for the message's visibility timeout (in seconds). + * @return result that contains success or errors of the operation + * @see #changeVisibility(String, int) + */ + BatchResult changeVisibility(Map idReceiptHandle, int visibilityTimeout); + + /** + * Same as {@link #changeVisibility(Map, int)}, except that we generate + * numeric ids starting with {@code 1} + * + * @param receiptHandles + * receipt handles to change visibility + * @see #changeVisibility(Map, int) + */ + BatchResult changeVisibility(Iterable receiptHandles, int visibilityTimeout); + + /** + * The SendMessage action delivers a message to the specified queue. The + * maximum allowed message size is 64 KB. + * + *

Important

+ * + * The following list shows the characters (in Unicode) allowed in your + * message, according to the W3C XML specification (for more information, go + * to http://www.w3.org/TR/REC-xml/#charsets). If you send any characters not + * included in the list, your request will be rejected. + * + * + * {@code #x9 | #xA | #xD | [#x20 to #xD7FF] | [#xE000 to #xFFFD] | [#x10000 to #x10FFFF]} + * + * @param queue + * queue you want to send to + * + * @param message + * Type: String maximum 64 KB in size. For a list of allowed + * characters, see the preceding important note. + * @return id of the message and md5 of the content sent + */ + MessageIdAndMD5 send(String message); + + /** + * Same as {@link #send(Map)} except you can set a delay for each message in + * the request. + * + *

Example usage

+ * + *
+    * BatchResult results = api.sendWithDelays(ImmutableTable.builder()
+    *                                  .put("id1", "test message one", 1)
+    *                                  .put("id2", "test message two", 10)
+    *                                  .build());
+    * 
+    * if (results.keySet().equals(ImmutableSet.of("id", "id2"))
+    *    // all ok
+    * else
+    *   results.getErrors();
+    * 
+ * + * @param idMessageBodyDelaySeconds + * id for correlating the result, message body, and delay seconds + * + * @return result that contains success or errors of the operation + * @see #send(String, SendMessageOptions) + */ + BatchResult sendWithDelays(Table idMessageBodyDelaySeconds); + + /** + * Same as {@link #sendWithDelays(Table)}, except that we generate numeric + * ids starting with {@code 1} + * + * @param messageBodyDelaySeconds + * message body to the delay desired + * @see #sendWithDelays(Table) + */ + BatchResult sendWithDelays(Map messageBodyDelaySeconds); + + /** + * Same as {@link #send(Map)} except you set a delay for all messages in the + * request + * + * @param delaySeconds + * The number of seconds to delay a specific message. Messages with + * a positive DelaySeconds value become available for processing + * after the delay time is finished. + * + * @see #send(String, SendMessageOptions) + */ + BatchResult sendWithDelay(Map idMessageBody, int delaySeconds); + + /** + * Same as {@link #sendWithDelay(Map, int)}, except that we generate numeric + * ids starting with {@code 1} + * + * @param messageBodies + * message bodies to send + * @see #sendWithDelay(Map, int) + */ + BatchResult sendWithDelay(Iterable messageBodies, int delaySeconds); + + /** + * The SendMessageBatch action delivers up to ten messages to the specified + * queue. The maximum allowed individual message size is 64 KiB (65,536 + * bytes). + * + * The maximum total payload size (i.e., the sum of all a batch's individual + * message lengths) is also 64 KiB (65,536 bytes). + * + * Currently, you can send up to 10 {@link #send} requests. + * + * action.

Example usage

+ * + *
+    * BatchResult results = api.send(ImmutableMap.builder()
+    *                                  .put("id1", "test message one")
+    *                                  .put("id2", "test message two")
+    *                                  .build());
+    * 
+    * if (results.keySet().equals(ImmutableSet.of("id", "id2"))
+    *    // all ok
+    * else
+    *   results.getErrors();
+    * 
+ * + * @param idMessageBody + * id for correlating the result to message body + * + * @return result that contains success or errors of the operation + * @see #send(String) + */ + BatchResult send(Map idMessageBody); + + /** + * Same as {@link #send(Map)}, except that we generate numeric ids starting + * with {@code 1} + * + * @param messageBodies + * message bodies to send + * @see #send(Map) + */ + BatchResult send(Iterable messageBodies); + + /** + * same as {@link #sendMessage(URI, String)} except you can control options + * such as delay seconds. + * + * @param options + * options such as delay seconds + * @see #sendMessage(URI, String) + */ + MessageIdAndMD5 send(String message, SendMessageOptions options); + + /** + * The ReceiveMessage action retrieves one or more messages from the + * specified queue. The ReceiveMessage action does not delete the message + * after it is retrieved. To delete a message, you must use the DeleteMessage + * action. For more information about message deletion in the message life + * cycle, see Message Lifecycle. + * + *

Note

+ * + * Due to the distributed nature of the queue, a weighted random set of + * machines is sampled on a ReceiveMessage call. That means only the messages + * on the sampled machines are returned. If the number of messages in the + * queue is small (less than 1000), it is likely you will get fewer messages + * than you requested per ReceiveMessage call. If the number of messages in + * the queue is extremely small, you might not receive any messages in a + * particular ReceiveMessage response; in which case you should repeat the + * request. + * + * @param queue + * from where you are receiving messages + * @return message including the receipt handle you can use to delete it + */ + Message receive(); + + /** + * same as {@link #receive(URI)} except you can provide options like + * VisibilityTimeout parameter in your request, which will be applied to the + * messages that SQS returns in the response. If you do not include the + * parameter, the overall visibility timeout for the queue is used for the + * returned messages. + * + * @param options + * options such as VisibilityTimeout + * @see #receive(URI) + */ + Message receive(ReceiveMessageOptions options); + + /** + * same as {@link #receive(URI)} except you can receive multiple messages. + * + * @param max + * maximum messages to receive, current limit is 10 + * @see #receive(URI) + */ + FluentIterable receive(int max); + + /** + * same as {@link #receive(URI, int)} except you can provide options like + * VisibilityTimeout parameter in your request, which will be applied to the + * messages that SQS returns in the response. If you do not include the + * parameter, the overall visibility timeout for the queue is used for the + * returned messages. + * + * @param options + * options such as VisibilityTimeout + * @see #receive(URI, int) + */ + FluentIterable receive(int max, ReceiveMessageOptions options); +} diff --git a/apis/sqs/src/main/java/org/jclouds/sqs/features/MessageAsyncApi.java b/apis/sqs/src/main/java/org/jclouds/sqs/features/MessageAsyncApi.java new file mode 100644 index 0000000000..6438e7b9c8 --- /dev/null +++ b/apis/sqs/src/main/java/org/jclouds/sqs/features/MessageAsyncApi.java @@ -0,0 +1,275 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.sqs.features; + +import static org.jclouds.sqs.reference.SQSParameters.ACTION; +import static org.jclouds.sqs.reference.SQSParameters.VERSION; + +import java.util.Map; + +import javax.ws.rs.FormParam; +import javax.ws.rs.POST; +import javax.ws.rs.Path; + +import org.jclouds.Constants; +import org.jclouds.aws.filters.FormSigner; +import org.jclouds.rest.annotations.BinderParam; +import org.jclouds.rest.annotations.ExceptionParser; +import org.jclouds.rest.annotations.FormParams; +import org.jclouds.rest.annotations.MapBinder; +import org.jclouds.rest.annotations.PayloadParam; +import org.jclouds.rest.annotations.RequestFilters; +import org.jclouds.rest.annotations.ResponseParser; +import org.jclouds.rest.annotations.VirtualHost; +import org.jclouds.rest.annotations.XMLResponseParser; +import org.jclouds.rest.functions.ReturnVoidOnNotFoundOr404; +import org.jclouds.sqs.binders.BindChangeMessageVisibilityBatchRequestEntryToIndexedFormParams; +import org.jclouds.sqs.binders.BindDeleteMessageBatchRequestEntryToIndexedFormParams; +import org.jclouds.sqs.binders.BindSendMessageBatchRequestEntryToIndexedFormParams; +import org.jclouds.sqs.binders.BindSendMessageBatchRequestEntryWithDelaysToIndexedFormParams; +import org.jclouds.sqs.domain.BatchResult; +import org.jclouds.sqs.domain.Message; +import org.jclouds.sqs.domain.MessageIdAndMD5; +import org.jclouds.sqs.options.ReceiveMessageOptions; +import org.jclouds.sqs.options.SendMessageOptions; +import org.jclouds.sqs.xml.ChangeMessageVisibilityBatchResponseHandler; +import org.jclouds.sqs.xml.DeleteMessageBatchResponseHandler; +import org.jclouds.sqs.xml.MessageHandler; +import org.jclouds.sqs.xml.ReceiveMessageResponseHandler; +import org.jclouds.sqs.xml.RegexMessageIdAndMD5Handler; +import org.jclouds.sqs.xml.SendMessageBatchResponseHandler; + +import com.google.common.collect.FluentIterable; +import com.google.common.collect.Table; +import com.google.common.util.concurrent.ListenableFuture; + +/** + * Provides access to SQS via their REST API. + *

+ * + * @author Adrian Cole + */ +@RequestFilters(FormSigner.class) +@FormParams(keys = VERSION, values = "{" + Constants.PROPERTY_API_VERSION + "}") +@VirtualHost +public interface MessageAsyncApi { + + /** + * @see MessageApi#delete(String) + */ + @POST + @Path("/") + @FormParams(keys = ACTION, values = "DeleteMessage") + @ExceptionParser(ReturnVoidOnNotFoundOr404.class) + ListenableFuture delete(@FormParam("ReceiptHandle") String receiptHandle); + + /** + * @see MessageApi#delete(Map) + */ + @POST + @Path("/") + @FormParams(keys = ACTION, values = "DeleteMessageBatch") + @XMLResponseParser(DeleteMessageBatchResponseHandler.class) + ListenableFuture> delete( + @BinderParam(BindDeleteMessageBatchRequestEntryToIndexedFormParams.class) Map idReceiptHandle); + + /** + * @see MessageApi#delete(Iterable) + */ + @POST + @Path("/") + @FormParams(keys = ACTION, values = "DeleteMessageBatch") + @XMLResponseParser(DeleteMessageBatchResponseHandler.class) + ListenableFuture> delete( + @BinderParam(BindDeleteMessageBatchRequestEntryToIndexedFormParams.class) Iterable receiptHandles); + + /** + * @see MessageApi#changeVisibility(String, int) + */ + @POST + @Path("/") + @FormParams(keys = ACTION, values = "ChangeMessageVisibility") + ListenableFuture changeVisibility(@FormParam("ReceiptHandle") String receiptHandle, + @FormParam("VisibilityTimeout") int visibilityTimeout); + + /** + * @see MessageApi#changeVisibility(Table) + */ + @POST + @Path("/") + @FormParams(keys = ACTION, values = "ChangeMessageVisibilityBatch") + @XMLResponseParser(ChangeMessageVisibilityBatchResponseHandler.class) + ListenableFuture> changeVisibility( + @BinderParam(BindChangeMessageVisibilityBatchRequestEntryToIndexedFormParams.class) Table idReceiptHandleVisibilityTimeout); + + /** + * @see MessageApi#changeVisibility(Map) + */ + @POST + @Path("/") + @FormParams(keys = ACTION, values = "ChangeMessageVisibilityBatch") + @XMLResponseParser(ChangeMessageVisibilityBatchResponseHandler.class) + ListenableFuture> changeVisibility( + @BinderParam(BindChangeMessageVisibilityBatchRequestEntryToIndexedFormParams.class) Map receiptHandleVisibilityTimeout); + + /** + * @see MessageApi#changeVisibility(Map, int) + */ + @POST + @Path("/") + @FormParams(keys = ACTION, values = "ChangeMessageVisibilityBatch") + @MapBinder(BindChangeMessageVisibilityBatchRequestEntryToIndexedFormParams.class) + @XMLResponseParser(ChangeMessageVisibilityBatchResponseHandler.class) + ListenableFuture> changeVisibility( + @PayloadParam("idReceiptHandle") Map idReceiptHandle, + @PayloadParam("visibilityTimeout") int visibilityTimeout); + + /** + * @see MessageApi#changeVisibility(Iterable, int) + */ + @POST + @Path("/") + @FormParams(keys = ACTION, values = "ChangeMessageVisibilityBatch") + @MapBinder(BindChangeMessageVisibilityBatchRequestEntryToIndexedFormParams.class) + @XMLResponseParser(ChangeMessageVisibilityBatchResponseHandler.class) + ListenableFuture> changeVisibility( + @PayloadParam("receiptHandles") Iterable receiptHandles, + @PayloadParam("visibilityTimeout") int visibilityTimeout); + + /** + * @see MessageApi#send(String) + */ + @POST + @Path("/") + @FormParams(keys = ACTION, values = "SendMessage") + @ResponseParser(RegexMessageIdAndMD5Handler.class) + ListenableFuture send(@FormParam("MessageBody") String message); + + /** + * @see MessageApi#send(String, SendMessageOptions) + */ + @POST + @Path("/") + @FormParams(keys = ACTION, values = "SendMessage") + @ResponseParser(RegexMessageIdAndMD5Handler.class) + ListenableFuture send(@FormParam("MessageBody") String message, SendMessageOptions options); + + /** + * @see MessageApi#sendWithDelays(Table) + */ + @POST + @Path("/") + @FormParams(keys = ACTION, values = "SendMessageBatch") + @ResponseParser(RegexMessageIdAndMD5Handler.class) + @XMLResponseParser(SendMessageBatchResponseHandler.class) + ListenableFuture> sendWithDelays( + @BinderParam(BindSendMessageBatchRequestEntryWithDelaysToIndexedFormParams.class) Table idMessageBodyDelaySeconds); + + /** + * @see MessageApi#sendWithDelays(Map) + */ + @POST + @Path("/") + @FormParams(keys = ACTION, values = "SendMessageBatch") + @ResponseParser(RegexMessageIdAndMD5Handler.class) + @XMLResponseParser(SendMessageBatchResponseHandler.class) + ListenableFuture> sendWithDelays( + @BinderParam(BindSendMessageBatchRequestEntryWithDelaysToIndexedFormParams.class) Map messageBodyDelaySeconds); + + /** + * @see MessageApi#sendWithDelay(Map, int) + */ + @POST + @Path("/") + @FormParams(keys = ACTION, values = "SendMessageBatch") + @MapBinder(BindSendMessageBatchRequestEntryWithDelaysToIndexedFormParams.class) + @XMLResponseParser(SendMessageBatchResponseHandler.class) + ListenableFuture> sendWithDelay( + @PayloadParam("idMessageBody") Map idMessageBody, + @PayloadParam("delaySeconds") int delaySeconds); + + /** + * @see MessageApi#sendWithDelay(Iterable, int) + */ + @POST + @Path("/") + @FormParams(keys = ACTION, values = "SendMessageBatch") + @MapBinder(BindSendMessageBatchRequestEntryWithDelaysToIndexedFormParams.class) + @XMLResponseParser(SendMessageBatchResponseHandler.class) + ListenableFuture> sendWithDelay( + @PayloadParam("messageBodies") Iterable messageBodies, @PayloadParam("delaySeconds") int delaySeconds); + + /** + * @see MessageApi#send(Map) + */ + @POST + @Path("/") + @FormParams(keys = ACTION, values = "SendMessageBatch") + @XMLResponseParser(SendMessageBatchResponseHandler.class) + ListenableFuture> send( + @BinderParam(BindSendMessageBatchRequestEntryToIndexedFormParams.class) Map idMessageBody); + + /** + * @see MessageApi#send(Iterable) + */ + @POST + @Path("/") + @FormParams(keys = ACTION, values = "SendMessageBatch") + @XMLResponseParser(SendMessageBatchResponseHandler.class) + ListenableFuture> send( + @BinderParam(BindSendMessageBatchRequestEntryToIndexedFormParams.class) Iterable messageBodies); + + /** + * @see MessageApi#receive() + */ + @POST + @Path("/") + @FormParams(keys = ACTION, values = "ReceiveMessage") + @XMLResponseParser(MessageHandler.class) + ListenableFuture receive(); + + /** + * @see MessageApi#receive(ReceiveMessageOptions) + */ + @POST + @Path("/") + @FormParams(keys = ACTION, values = "ReceiveMessage") + @XMLResponseParser(MessageHandler.class) + ListenableFuture receive(ReceiveMessageOptions options); + + /** + * @see MessageApi#receive(int) + */ + @POST + @Path("/") + @FormParams(keys = ACTION, values = "ReceiveMessage") + @XMLResponseParser(ReceiveMessageResponseHandler.class) + ListenableFuture> receive(@FormParam("MaxNumberOfMessages") int max); + + /** + * @see MessageApi#receive(int, ReceiveMessageOptions) + */ + @POST + @Path("/") + @FormParams(keys = ACTION, values = "ReceiveMessage") + @XMLResponseParser(ReceiveMessageResponseHandler.class) + ListenableFuture> receive(@FormParam("MaxNumberOfMessages") int max, + ReceiveMessageOptions options); + +} diff --git a/antcontrib/src/main/java/org/jclouds/tools/ant/logging/config/AntLoggingModule.java b/apis/sqs/src/main/java/org/jclouds/sqs/features/Messages.java similarity index 57% rename from antcontrib/src/main/java/org/jclouds/tools/ant/logging/config/AntLoggingModule.java rename to apis/sqs/src/main/java/org/jclouds/sqs/features/Messages.java index de61dc431d..7c9813af26 100644 --- a/antcontrib/src/main/java/org/jclouds/tools/ant/logging/config/AntLoggingModule.java +++ b/apis/sqs/src/main/java/org/jclouds/sqs/features/Messages.java @@ -16,33 +16,37 @@ * specific language governing permissions and limitations * under the License. */ -package org.jclouds.tools.ant.logging.config; +package org.jclouds.sqs.features; import static com.google.common.base.Preconditions.checkNotNull; -import org.apache.tools.ant.Project; -import org.jclouds.logging.Logger.LoggerFactory; -import org.jclouds.logging.config.LoggingModule; -import org.jclouds.tools.ant.logging.AntLogger; +import org.jclouds.sqs.domain.Message; + +import com.google.common.base.Function; /** - * Configures logging of type {@link AntLogger} + * Utilities for {@link Message}s * * @author Adrian Cole - * */ -public class AntLoggingModule extends LoggingModule { - - private final Project project; - private final String[] upgrades; - - public AntLoggingModule(Project project, String ... upgrades) { - this.project = project; - this.upgrades = upgrades; +public class Messages { + public static Function toReceiptHandle() { + return ToReceiptHandleFunction.INSTANCE; } - @Override - public LoggerFactory createLoggerFactory() { - return new AntLogger.AntLoggerFactory(checkNotNull(project, "project"), upgrades); + // enum singleton pattern + private enum ToReceiptHandleFunction implements Function { + INSTANCE; + + @Override + public String apply(Message o) { + return checkNotNull(o, "message").getReceiptHandle(); + } + + @Override + public String toString() { + return "toReceiptHandle"; + } } + } diff --git a/apis/sqs/src/main/java/org/jclouds/sqs/features/PermissionApi.java b/apis/sqs/src/main/java/org/jclouds/sqs/features/PermissionApi.java new file mode 100644 index 0000000000..2f2498e1a3 --- /dev/null +++ b/apis/sqs/src/main/java/org/jclouds/sqs/features/PermissionApi.java @@ -0,0 +1,87 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.sqs.features; + +import java.util.concurrent.TimeUnit; + +import org.jclouds.concurrent.Timeout; +import org.jclouds.sqs.domain.Action; + +/** + * Provides access to SQS via their REST API. + *

+ * + * @see PermissionAsyncApi + * @author Adrian Cole + */ +@Timeout(duration = 30, timeUnit = TimeUnit.SECONDS) +public interface PermissionApi { + + /** + * The AddPermission action adds a permission to a queue for a specific + * principal. This allows for sharing access to the queue. + * + * When you create a queue, you have full control access rights for the + * queue. Only you (as owner of the queue) can grant or deny permissions to + * the queue. For more information about these permissions, see Shared Queues + * in the Amazon SQS Developer Guide. + * + * Note + * + * AddPermission writes an SQS-generated policy. If you want to write your + * own policy, use SetQueueAttributes to upload your policy. + * + * @param queue + * queue to change permissions on + * @param label + * + * The unique identification of the permission you're setting. + * example: AliceSendMessage + * + * Constraints: Maximum 80 characters; alphanumeric characters, + * hyphens (-), and underscores (_) are allowed. + * @param permission + * The action you want to allow for the specified principal. + * @param accountId + * The AWS account number of the principal who will be given + * permission. The principal must have an AWS account, but does not + * need to be signed up for Amazon SQS. For information about + * locating the AWS account identification, see Your AWS + * Identifiers in the Amazon SQS Developer Guide. + * + * Constraints: Valid 12-digit AWS account number, without hyphens + * + */ + void addPermissionToAccount(String label, Action permission, String accountId); + + /** + * The RemovePermission action revokes any permissions in the queue policy + * that matches the Label parameter. Only the owner of the queue can remove + * permissions. + * + * @param queue + * queue to change permissions on + * + * @param label + * The identification of the permission you want to remove. This is + * the label you added in AddPermission. example: AliceSendMessage + */ + void remove(String label); + +} diff --git a/apis/sqs/src/main/java/org/jclouds/sqs/features/PermissionAsyncApi.java b/apis/sqs/src/main/java/org/jclouds/sqs/features/PermissionAsyncApi.java new file mode 100644 index 0000000000..54902bd0ef --- /dev/null +++ b/apis/sqs/src/main/java/org/jclouds/sqs/features/PermissionAsyncApi.java @@ -0,0 +1,65 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.sqs.features; + +import static org.jclouds.sqs.reference.SQSParameters.ACTION; +import static org.jclouds.sqs.reference.SQSParameters.VERSION; + +import javax.ws.rs.FormParam; +import javax.ws.rs.POST; +import javax.ws.rs.Path; + +import org.jclouds.Constants; +import org.jclouds.aws.filters.FormSigner; +import org.jclouds.rest.annotations.FormParams; +import org.jclouds.rest.annotations.RequestFilters; +import org.jclouds.rest.annotations.VirtualHost; +import org.jclouds.sqs.domain.Action; + +import com.google.common.util.concurrent.ListenableFuture; + +/** + * Provides access to SQS via their REST API. + *

+ * + * @author Adrian Cole + */ +@RequestFilters(FormSigner.class) +@FormParams(keys = VERSION, values = "{" + Constants.PROPERTY_API_VERSION + "}") +@VirtualHost +public interface PermissionAsyncApi { + + /** + * @see PermissionApi#addPermissionToAccount + */ + @POST + @Path("/") + @FormParams(keys = ACTION, values = "AddPermission") + ListenableFuture addPermissionToAccount(@FormParam("Label") String label, + @FormParam("ActionName.1") Action permission, @FormParam("AWSAccountId.1") String accountId); + + /** + * @see PermissionApi#remove + */ + @POST + @Path("/") + @FormParams(keys = ACTION, values = "RemovePermission") + ListenableFuture remove(@FormParam("Label") String label); + +} diff --git a/apis/sqs/src/main/java/org/jclouds/sqs/features/QueueApi.java b/apis/sqs/src/main/java/org/jclouds/sqs/features/QueueApi.java new file mode 100644 index 0000000000..206bd23d86 --- /dev/null +++ b/apis/sqs/src/main/java/org/jclouds/sqs/features/QueueApi.java @@ -0,0 +1,236 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.sqs.features; + +import java.net.URI; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +import org.jclouds.concurrent.Timeout; +import org.jclouds.sqs.domain.QueueAttributes; +import org.jclouds.sqs.options.CreateQueueOptions; +import org.jclouds.sqs.options.ListQueuesOptions; + +import com.google.common.collect.FluentIterable; + +/** + * Provides access to SQS via their REST API. + *

+ * + * @see QueueAsyncApi + * @author Adrian Cole + */ +@Timeout(duration = 30, timeUnit = TimeUnit.SECONDS) +public interface QueueApi { + + /** + * The ListQueues action returns a list of your queues. The maximum number of + * queues that can be returned is 1000. If you specify a value for the + * optional QueueNamePrefix parameter, only queues with a name beginning with + * the specified value are returned + * + * @param region + * Queues are Region-specific. + * @param options + * specify prefix or other options + * + * @see + */ + FluentIterable list(); + + FluentIterable list(ListQueuesOptions options); + + /** + * The GetQueueUrl action returns the Uniform Resource Locater (URL) of a + * queue. This action provides a simple way to retrieve the URL of an SQS + * queue. + * + * @param queueName + * The name of an existing queue. + * @return uri of the queue or null if not found + */ + URI get(String queueName); + + /** + * like {@link #get(String)}, except specifying the owner of the queue. + * + * To access a queue that belongs to another AWS account, use the + * QueueOwnerAWSAccountId parameter to specify the account ID of the queue's + * owner. The queue's owner must grant you permission to access the queue. + * + * @param accountId + * @return The AWS account ID of the account that created the queue. + */ + URI getInAccount(String queueName, String accountId); + + /** + * The CreateQueue action creates a new queue. + * + * When you request CreateQueue, you provide a name for the queue. To + * successfully create a new queue, you must provide a name that is unique + * within the scope of your own queues. + * + *

Note

+ * + * If you delete a queue, you must wait at least 60 seconds before creating a + * queue with the same name. + * + * If you provide the name of an existing queue, along with the exact names + * and values of all the queue's attributes, CreateQueue returns the queue + * URL for the existing queue. If the queue name, attribute names, or + * attribute values do not match an existing queue, CreateQueue returns an + * error. + * + *

Tip

+ * + * Use GetQueueUrl to get a queue's URL. GetQueueUrl requires only the + * QueueName parameter. + * + * @param region + * Queues are Region-specific. + * @param queueName + * The name to use for the queue created. Constraints: Maximum 80 + * characters; alphanumeric characters, hyphens (-), and + * underscores (_) are allowed. + */ + // this will gracefully attempt to resolve name issues + @Timeout(duration = 61, timeUnit = TimeUnit.SECONDS) + URI create(String queueName); + + /** + * same as {@link #create(String, String)} except you can + * control options such as delay seconds. + * + * @param options + * options such as delay seconds + * @see #create(String, String) + */ + @Timeout(duration = 61, timeUnit = TimeUnit.SECONDS) + URI create(String queueName, CreateQueueOptions options); + + /** + * The DeleteQueue action deletes the queue specified by the queue URL, + * regardless of whether the queue is empty. If the specified queue does not + * exist, SQS returns a successful response. + * + *

Caution

+ * + * Use DeleteQueue with care; once you delete your queue, any messages in the + * queue are no longer available. + * + * When you delete a queue, the deletion process takes up to 60 seconds. + * Requests you send involving that queue during the 60 seconds might + * succeed. For example, a SendMessage request might succeed, but after the + * 60 seconds, the queue and that message you sent no longer exist. Also, + * when you delete a queue, you must wait at least 60 seconds before creating + * a queue with the same name. + * + * We reserve the right to delete queues that have had no activity for more + * than 30 days. For more information, see About SQS Queues in the Amazon SQS + * Developer Guide. + * + * @param queue + * queue you want to delete + */ + void delete(URI queue); + + /** + * returns all attributes of a queue. + * + * @param queue + * queue to get the attributes of + */ + QueueAttributes getAttributes(URI queue); + + /** + * The SetQueueAttributes action sets one attribute of a queue per request. + * When you change a queue's attributes, the change can take up to 60 seconds + * to propagate throughout the SQS system. + * + * @param queue + * queue to set the attribute on + * @param name + * + * The name of the attribute you want to set. + * + * VisibilityTimeout - The length of time (in seconds) that a + * message received from a queue will be invisible to other + * receiving components when they ask to receive messages. For more + * information about VisibilityTimeout, see Visibility Timeout in + * the Amazon SQS Developer Guide. + * + * Policy - The formal description of the permissions for a + * resource. For more information about Policy, see Basic Policy + * Structure in the Amazon SQS Developer Guide. + * + * MaximumMessageSize - The limit of how many bytes a message can + * contain before Amazon SQS rejects it. + * + * MessageRetentionPeriod - The number of seconds Amazon SQS + * retains a message. + * + * DelaySeconds - The time in seconds that the delivery of all + * messages in the queue will be delayed. + * @param value + * The value of the attribute you want to set. To delete a queue's + * access control policy, set the policy to "". + * + * Constraints: Constraints are specific for each value. + * + * VisibilityTimeout - An integer from 0 to 43200 (12 hours). The + * default for this attribute is 30 seconds. + * + * Policy - A valid form-url-encoded policy. For more information + * about policy structure, see Basic Policy Structure in the Amazon + * SQS Developer Guide. For more information about + * form-url-encoding, see + * http://www.w3.org/MarkUp/html-spec/html-spec_8.html#SEC8.2.1. + * + * MaximumMessageSize - An integer from 1024 bytes (1 KiB) up to + * 65536 bytes (64 KiB). The default for this attribute is 65536 + * (64 KiB). + * + * MessageRetentionPeriod - Integer representing seconds, from 60 + * (1 minute) to 1209600 (14 days). The default for this attribute + * is 345600 (4 days). + * + * DelaySeconds - An integer from 0 to 900 (15 minutes). The + * default for this attribute is 0. + */ + void setAttribute(URI queue, String name, String value); + + /** + * returns some attributes of a queue. + * + * @param queue + * queue to get the attributes of + */ + Map getAttributes(URI queue, Iterable attributeNames); + + /** + * returns an attribute of a queue. + * + * @param queue + * queue to get the attributes of + */ + String getAttribute(URI queue, String attributeName); + +} diff --git a/apis/sqs/src/main/java/org/jclouds/sqs/features/QueueAsyncApi.java b/apis/sqs/src/main/java/org/jclouds/sqs/features/QueueAsyncApi.java new file mode 100644 index 0000000000..3c8dbf7f5b --- /dev/null +++ b/apis/sqs/src/main/java/org/jclouds/sqs/features/QueueAsyncApi.java @@ -0,0 +1,173 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.sqs.features; + +import static org.jclouds.sqs.reference.SQSParameters.ACTION; +import static org.jclouds.sqs.reference.SQSParameters.VERSION; + +import java.net.URI; +import java.util.Map; + +import javax.ws.rs.FormParam; +import javax.ws.rs.POST; +import javax.ws.rs.Path; + +import org.jclouds.Constants; +import org.jclouds.aws.filters.FormSigner; +import org.jclouds.rest.annotations.BinderParam; +import org.jclouds.rest.annotations.EndpointParam; +import org.jclouds.rest.annotations.ExceptionParser; +import org.jclouds.rest.annotations.FormParams; +import org.jclouds.rest.annotations.RequestFilters; +import org.jclouds.rest.annotations.ResponseParser; +import org.jclouds.rest.annotations.Transform; +import org.jclouds.rest.annotations.VirtualHost; +import org.jclouds.rest.annotations.XMLResponseParser; +import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; +import org.jclouds.rest.functions.ReturnVoidOnNotFoundOr404; +import org.jclouds.sqs.binders.BindAttributeNamesToIndexedFormParams; +import org.jclouds.sqs.domain.QueueAttributes; +import org.jclouds.sqs.functions.MapToQueueAttributes; +import org.jclouds.sqs.options.CreateQueueOptions; +import org.jclouds.sqs.options.ListQueuesOptions; +import org.jclouds.sqs.xml.AttributesHandler; +import org.jclouds.sqs.xml.RegexListQueuesResponseHandler; +import org.jclouds.sqs.xml.RegexQueueHandler; +import org.jclouds.sqs.xml.ValueHandler; + +import com.google.common.collect.FluentIterable; +import com.google.common.util.concurrent.ListenableFuture; + +/** + * Provides access to SQS via their REST API. + *

+ * + * @author Adrian Cole + */ +@RequestFilters(FormSigner.class) +@FormParams(keys = VERSION, values = "{" + Constants.PROPERTY_API_VERSION + "}") +@VirtualHost +public interface QueueAsyncApi { + + /** + * @see QueueApi#list + */ + @POST + @Path("/") + @FormParams(keys = ACTION, values = "ListQueues") + @ResponseParser(RegexListQueuesResponseHandler.class) + ListenableFuture> list(); + + /** + * @see QueueApi#list(ListQueuesOptions) + */ + @POST + @Path("/") + @FormParams(keys = ACTION, values = "ListQueues") + @ResponseParser(RegexListQueuesResponseHandler.class) + ListenableFuture> list(ListQueuesOptions options); + + /** + * @see QueueApi#get(String) + */ + @POST + @Path("/") + @FormParams(keys = ACTION, values = "GetQueueUrl") + @ResponseParser(RegexQueueHandler.class) + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + ListenableFuture get(@FormParam("QueueName") String queueName); + + /** + * @see QueueApi#getInAccount + */ + @POST + @Path("/") + @FormParams(keys = ACTION, values = "GetQueueUrl") + @ResponseParser(RegexQueueHandler.class) + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + ListenableFuture getInAccount(@FormParam("QueueName") String queueName, + @FormParam("QueueOwnerAWSAccountId") String accountId); + + /** + * @see QueueApi#create + */ + @POST + @Path("/") + @FormParams(keys = ACTION, values = "CreateQueue") + @ResponseParser(RegexQueueHandler.class) + ListenableFuture create(@FormParam("QueueName") String queueName); + + /** + * @see QueueApi#create + */ + @POST + @Path("/") + @FormParams(keys = ACTION, values = "CreateQueue") + @ResponseParser(RegexQueueHandler.class) + ListenableFuture create(@FormParam("QueueName") String queueName, CreateQueueOptions options); + + /** + * @see QueueApi#delete + */ + @POST + @Path("/") + @FormParams(keys = ACTION, values = "DeleteQueue") + @ExceptionParser(ReturnVoidOnNotFoundOr404.class) + ListenableFuture delete(@EndpointParam URI queue); + + /** + * @see QueueApi#getAttributes(URI) + */ + @POST + @Path("/") + @FormParams(keys = { ACTION, "AttributeName.1" }, values = { "GetQueueAttributes", "All" }) + @Transform(MapToQueueAttributes.class) + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + @XMLResponseParser(AttributesHandler.class) + ListenableFuture getAttributes(@EndpointParam URI queue); + + /** + * @see QueueApi#getAttributes(URI, Iterable) + */ + @POST + @Path("/") + @FormParams(keys = ACTION, values = "GetQueueAttributes") + @XMLResponseParser(AttributesHandler.class) + ListenableFuture> getAttributes(@EndpointParam URI queue, + @BinderParam(BindAttributeNamesToIndexedFormParams.class) Iterable attributeNames); + + /** + * @see QueueApi#getAttribute + */ + @POST + @Path("/") + @FormParams(keys = ACTION, values = "GetQueueAttributes") + @XMLResponseParser(ValueHandler.class) + ListenableFuture getAttribute(@EndpointParam URI queue, @FormParam("AttributeName.1") String attributeName); + + /** + * @see QueueApi#setAttribute + */ + @POST + @Path("/") + @FormParams(keys = ACTION, values = "SetQueueAttributes") + ListenableFuture setAttribute(@EndpointParam URI queue, @FormParam("Attribute.Name") String name, + @FormParam("Attribute.Value") String value); + +} diff --git a/apis/sqs/src/main/java/org/jclouds/sqs/functions/MapToQueueAttributes.java b/apis/sqs/src/main/java/org/jclouds/sqs/functions/MapToQueueAttributes.java new file mode 100644 index 0000000000..1728bebd34 --- /dev/null +++ b/apis/sqs/src/main/java/org/jclouds/sqs/functions/MapToQueueAttributes.java @@ -0,0 +1,57 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.sqs.functions; + +import java.util.Date; +import java.util.Map; + +import org.jclouds.sqs.domain.Attribute; +import org.jclouds.sqs.domain.QueueAttributes; +import org.jclouds.sqs.domain.QueueAttributes.Builder; + +import com.google.common.base.Function; + +/** + * Converts a Map to a typed QueueAttributes object + * + * @author Adrian Cole + */ +public class MapToQueueAttributes implements Function, QueueAttributes> { + + @Override + public QueueAttributes apply(Map input) { + if (input == null) + return null; + Builder builder = QueueAttributes.builder(); + builder.queueArn(input.get(Attribute.QUEUE_ARN)); + builder.approximateNumberOfMessages(Long.parseLong(input.get(Attribute.APPROXIMATE_NUMBER_OF_MESSAGES))); + builder.approximateNumberOfMessagesNotVisible(Long.parseLong(input + .get(Attribute.APPROXIMATE_NUMBER_OF_MESSAGES_NOT_VISIBLE))); + builder.approximateNumberOfMessagesDelayed(Long.parseLong(input + .get(Attribute.APPROXIMATE_NUMBER_OF_MESSAGES_DELAYED))); + builder.visibilityTimeout(Integer.parseInt(input.get(Attribute.VISIBILITY_TIMEOUT))); + builder.createdTimestamp(new Date(Long.parseLong(input.get(Attribute.CREATED_TIMESTAMP)))); + builder.lastModifiedTimestamp(new Date(Long.parseLong(input.get(Attribute.LAST_MODIFIED_TIMESTAMP)))); + builder.rawPolicy(input.get(Attribute.POLICY)); + builder.maximumMessageSize(Integer.parseInt(input.get(Attribute.MAXIMUM_MESSAGE_SIZE))); + builder.messageRetentionPeriod(Integer.parseInt(input.get(Attribute.MESSAGE_RETENTION_PERIOD))); + builder.delaySeconds(Integer.parseInt(input.get(Attribute.DELAY_SECONDS))); + return builder.build(); + } +} diff --git a/apis/sqs/src/main/java/org/jclouds/sqs/handlers/ParseSQSErrorFromXmlContent.java b/apis/sqs/src/main/java/org/jclouds/sqs/handlers/ParseSQSErrorFromXmlContent.java new file mode 100644 index 0000000000..3eb4d29072 --- /dev/null +++ b/apis/sqs/src/main/java/org/jclouds/sqs/handlers/ParseSQSErrorFromXmlContent.java @@ -0,0 +1,66 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.sqs.handlers; + +import java.util.Set; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.aws.domain.AWSError; +import org.jclouds.aws.handlers.ParseAWSErrorFromXmlContent; +import org.jclouds.aws.util.AWSUtils; +import org.jclouds.http.HttpCommand; +import org.jclouds.http.HttpResponse; +import org.jclouds.rest.ResourceNotFoundException; + +import com.google.common.collect.ImmutableSet; + +/** + * @author Adrian Cole + * + */ +@Singleton +public class ParseSQSErrorFromXmlContent extends ParseAWSErrorFromXmlContent { + protected Set resourceNotFoundCodes = ImmutableSet.of("AWS.SimpleQueueService.NonExistentQueue"); + protected Set illegalStateCodes = ImmutableSet.of("AWS.SimpleQueueService.QueueDeletedRecently", + "AWS.SimpleQueueService.QueueNameExists"); + protected Set illegalArgumentCodes = ImmutableSet.of("InvalidAttributeName", "ReadCountOutOfRange", + "InvalidMessageContents", "MessageTooLong"); + + @Inject + public ParseSQSErrorFromXmlContent(AWSUtils utils) { + super(utils); + } + + @Override + protected Exception refineException(HttpCommand command, HttpResponse response, Exception exception, AWSError error, + String message) { + String errorCode = (error != null && error.getCode() != null) ? error.getCode() : null; + if (resourceNotFoundCodes.contains(errorCode)) + exception = new ResourceNotFoundException(message, exception); + else if (illegalStateCodes.contains(errorCode)) + exception = new IllegalStateException(message, exception); + else if (illegalArgumentCodes.contains(errorCode)) + exception = new IllegalArgumentException(message, exception); + else + exception = super.refineException(command, response, exception, error, message); + return exception; + } +} \ No newline at end of file diff --git a/apis/sqs/src/main/java/org/jclouds/sqs/handlers/SQSErrorRetryHandler.java b/apis/sqs/src/main/java/org/jclouds/sqs/handlers/SQSErrorRetryHandler.java new file mode 100644 index 0000000000..7af16804b2 --- /dev/null +++ b/apis/sqs/src/main/java/org/jclouds/sqs/handlers/SQSErrorRetryHandler.java @@ -0,0 +1,71 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.sqs.handlers; + +import static org.jclouds.sqs.config.SQSProperties.CREATE_QUEUE_MAX_RETRIES; +import static org.jclouds.sqs.config.SQSProperties.CREATE_QUEUE_RETRY_INTERVAL; + +import java.util.Set; +import java.util.concurrent.TimeUnit; + +import javax.inject.Named; + +import org.jclouds.aws.domain.AWSError; +import org.jclouds.aws.handlers.AWSClientErrorRetryHandler; +import org.jclouds.aws.util.AWSUtils; +import org.jclouds.http.HttpCommand; +import org.jclouds.http.HttpResponse; +import org.jclouds.http.annotation.ClientError; +import org.jclouds.http.handlers.BackoffLimitedRetryHandler; + +import com.google.common.annotations.VisibleForTesting; +import com.google.common.util.concurrent.Uninterruptibles; +import com.google.inject.Inject; + +/** + * + * @author Adrian Cole + */ +public class SQSErrorRetryHandler extends AWSClientErrorRetryHandler { + + private final long retryInterval; + private final int maxTries; + + @Inject + public SQSErrorRetryHandler(AWSUtils utils, BackoffLimitedRetryHandler backoffLimitedRetryHandler, + @ClientError Set retryableCodes, @Named(CREATE_QUEUE_MAX_RETRIES) int maxTries, + @Named(CREATE_QUEUE_RETRY_INTERVAL) long retryInterval) { + super(utils, backoffLimitedRetryHandler, retryableCodes); + this.maxTries = maxTries; + this.retryInterval = retryInterval; + } + + @VisibleForTesting + public boolean shouldRetryRequestOnError(HttpCommand command, HttpResponse response, AWSError error) { + if ("AWS.SimpleQueueService.QueueDeletedRecently".equals(error.getCode())) { + if (command.incrementFailureCount() - 1 < maxTries) { + Uninterruptibles.sleepUninterruptibly(retryInterval, TimeUnit.MILLISECONDS); + return true; + } + return false; + } + return super.shouldRetryRequestOnError(command, response, error); + } + +} diff --git a/labs/sqs/src/main/java/org/jclouds/sqs/options/CreateQueueOptions.java b/apis/sqs/src/main/java/org/jclouds/sqs/options/CreateQueueOptions.java similarity index 97% rename from labs/sqs/src/main/java/org/jclouds/sqs/options/CreateQueueOptions.java rename to apis/sqs/src/main/java/org/jclouds/sqs/options/CreateQueueOptions.java index 7cd0694931..6de7df36c8 100644 --- a/labs/sqs/src/main/java/org/jclouds/sqs/options/CreateQueueOptions.java +++ b/apis/sqs/src/main/java/org/jclouds/sqs/options/CreateQueueOptions.java @@ -113,7 +113,7 @@ public class CreateQueueOptions extends BaseHttpRequestOptions implements Clonea */ @Override public int hashCode() { - return Objects.hashCode(attributes); + return Objects.hashCode(attributes.build()); } @Override @@ -133,7 +133,7 @@ public class CreateQueueOptions extends BaseHttpRequestOptions implements Clonea if (getClass() != obj.getClass()) return false; CreateQueueOptions other = CreateQueueOptions.class.cast(obj); - return Objects.equal(this.attributes, other.attributes); + return Objects.equal(this.attributes.build(), other.attributes.build()); } /** diff --git a/labs/sqs/src/main/java/org/jclouds/sqs/options/ListQueuesOptions.java b/apis/sqs/src/main/java/org/jclouds/sqs/options/ListQueuesOptions.java similarity index 100% rename from labs/sqs/src/main/java/org/jclouds/sqs/options/ListQueuesOptions.java rename to apis/sqs/src/main/java/org/jclouds/sqs/options/ListQueuesOptions.java diff --git a/labs/sqs/src/main/java/org/jclouds/sqs/options/ReceiveMessageOptions.java b/apis/sqs/src/main/java/org/jclouds/sqs/options/ReceiveMessageOptions.java similarity index 97% rename from labs/sqs/src/main/java/org/jclouds/sqs/options/ReceiveMessageOptions.java rename to apis/sqs/src/main/java/org/jclouds/sqs/options/ReceiveMessageOptions.java index dcbd6ba3ba..fff43608dd 100644 --- a/labs/sqs/src/main/java/org/jclouds/sqs/options/ReceiveMessageOptions.java +++ b/apis/sqs/src/main/java/org/jclouds/sqs/options/ReceiveMessageOptions.java @@ -128,7 +128,7 @@ public class ReceiveMessageOptions extends BaseHttpRequestOptions implements Clo */ @Override public int hashCode() { - return Objects.hashCode(visibilityTimeout, attributes); + return Objects.hashCode(visibilityTimeout, attributes.build()); } @Override @@ -149,7 +149,7 @@ public class ReceiveMessageOptions extends BaseHttpRequestOptions implements Clo return false; ReceiveMessageOptions other = ReceiveMessageOptions.class.cast(obj); return Objects.equal(this.visibilityTimeout, other.visibilityTimeout) - && Objects.equal(this.attributes, other.attributes); + && Objects.equal(this.attributes.build(), other.attributes.build()); } /** diff --git a/labs/sqs/src/main/java/org/jclouds/sqs/options/SendMessageOptions.java b/apis/sqs/src/main/java/org/jclouds/sqs/options/SendMessageOptions.java similarity index 100% rename from labs/sqs/src/main/java/org/jclouds/sqs/options/SendMessageOptions.java rename to apis/sqs/src/main/java/org/jclouds/sqs/options/SendMessageOptions.java diff --git a/labs/sqs/src/main/java/org/jclouds/sqs/package-info.java b/apis/sqs/src/main/java/org/jclouds/sqs/package-info.java similarity index 100% rename from labs/sqs/src/main/java/org/jclouds/sqs/package-info.java rename to apis/sqs/src/main/java/org/jclouds/sqs/package-info.java diff --git a/labs/sqs/src/main/java/org/jclouds/sqs/reference/SQSParameters.java b/apis/sqs/src/main/java/org/jclouds/sqs/reference/SQSParameters.java similarity index 100% rename from labs/sqs/src/main/java/org/jclouds/sqs/reference/SQSParameters.java rename to apis/sqs/src/main/java/org/jclouds/sqs/reference/SQSParameters.java diff --git a/labs/sqs/src/main/java/org/jclouds/sqs/reference/package-info.java b/apis/sqs/src/main/java/org/jclouds/sqs/reference/package-info.java similarity index 100% rename from labs/sqs/src/main/java/org/jclouds/sqs/reference/package-info.java rename to apis/sqs/src/main/java/org/jclouds/sqs/reference/package-info.java diff --git a/apis/sqs/src/main/java/org/jclouds/sqs/xml/AttributesHandler.java b/apis/sqs/src/main/java/org/jclouds/sqs/xml/AttributesHandler.java new file mode 100644 index 0000000000..eb9ea4c2c4 --- /dev/null +++ b/apis/sqs/src/main/java/org/jclouds/sqs/xml/AttributesHandler.java @@ -0,0 +1,70 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.sqs.xml; + +import static org.jclouds.util.SaxUtils.currentOrNull; + +import java.util.Map; + +import org.jclouds.http.functions.ParseSax; + +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableMap.Builder; + +/** + * @see + * + * @author Adrian Cole + */ +public class AttributesHandler extends ParseSax.HandlerForGeneratedRequestWithResult> { + + private StringBuilder currentText = new StringBuilder(); + private Builder builder = ImmutableMap. builder(); + private String name; + + @Override + public Map getResult() { + try { + return builder.build(); + } catch (NullPointerException e) { + return null; + } finally { + builder = ImmutableMap. builder(); + } + } + + @Override + public void endElement(String uri, String name, String qName) { + if (qName.equals("Name")) { + this.name = currentOrNull(currentText); + } else if (qName.equals("Value")) { + builder.put(this.name, currentOrNull(currentText)); + this.name = null; + } + currentText = new StringBuilder(); + } + + @Override + public void characters(char ch[], int start, int length) { + currentText.append(ch, start, length); + } + +} diff --git a/apis/sqs/src/main/java/org/jclouds/sqs/xml/BatchErrorHandler.java b/apis/sqs/src/main/java/org/jclouds/sqs/xml/BatchErrorHandler.java new file mode 100644 index 0000000000..24889e29e6 --- /dev/null +++ b/apis/sqs/src/main/java/org/jclouds/sqs/xml/BatchErrorHandler.java @@ -0,0 +1,68 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.sqs.xml; + +import static org.jclouds.util.SaxUtils.currentOrNull; + +import org.jclouds.http.functions.ParseSax; +import org.jclouds.sqs.domain.BatchError; + +/** + * @see + * + * @author Adrian Cole + */ +public class BatchErrorHandler extends ParseSax.HandlerForGeneratedRequestWithResult { + + private StringBuilder currentText = new StringBuilder(); + private BatchError.Builder builder = BatchError.builder(); + + @Override + public BatchError getResult() { + try { + return builder.build(); + } catch (NullPointerException e) { + return null; + } finally { + builder = BatchError.builder(); + } + } + + @Override + public void endElement(String uri, String name, String qName) { + if (qName.equals("Id")) { + builder.id(currentOrNull(currentText)); + } else if (qName.equals("SenderFault")) { + builder.senderFault(Boolean.parseBoolean(currentOrNull(currentText))); + } else if (qName.equals("Code")) { + builder.code(currentOrNull(currentText)); + } else if (qName.equals("Message")) { + builder.message(currentOrNull(currentText)); + } + currentText = new StringBuilder(); + } + + @Override + public void characters(char ch[], int start, int length) { + currentText.append(ch, start, length); + } + +} diff --git a/apis/sqs/src/main/java/org/jclouds/sqs/xml/BatchResponseHandler.java b/apis/sqs/src/main/java/org/jclouds/sqs/xml/BatchResponseHandler.java new file mode 100644 index 0000000000..07bd366d42 --- /dev/null +++ b/apis/sqs/src/main/java/org/jclouds/sqs/xml/BatchResponseHandler.java @@ -0,0 +1,106 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.sqs.xml; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.Map; + +import org.jclouds.http.functions.ParseSax; +import org.jclouds.http.functions.ParseSax.HandlerForGeneratedRequestWithResult; +import org.jclouds.sqs.domain.BatchError; +import org.jclouds.sqs.domain.BatchResult; +import org.xml.sax.Attributes; +import org.xml.sax.SAXException; + +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.ImmutableSet.Builder; + +/** + * @see docs + * + * @author Adrian Cole + */ +public class BatchResponseHandler extends ParseSax.HandlerForGeneratedRequestWithResult> { + + private final String resultElement; + private final ParseSax.HandlerForGeneratedRequestWithResult> resultHandler; + private final BatchErrorHandler errorHandler; + + private ImmutableMap.Builder results = ImmutableMap. builder(); + private Builder errors = ImmutableSet. builder(); + + private boolean inResult; + private boolean inError; + + protected BatchResponseHandler(String resultElement, HandlerForGeneratedRequestWithResult> resultHandler, + BatchErrorHandler errorHandler) { + this.resultElement = checkNotNull(resultElement, "resultElement");; + this.resultHandler = checkNotNull(resultHandler, "resultHandler");; + this.errorHandler = checkNotNull(errorHandler, "errorHandler");; + } + + @Override + public BatchResult getResult() { + return BatchResult. builder().putAll(results.build()).errors(errors.build()) + .build(); + } + + @Override + public void startElement(String url, String name, String qName, Attributes attributes) throws SAXException { + if (qName.equals(resultElement)) { + inResult = true; + } else if (qName.equals("BatchResultErrorEntry")) { + inError = true; + } + if (inResult) { + resultHandler.startElement(url, name, qName, attributes); + } else if (inError) { + errorHandler.startElement(url, name, qName, attributes); + } + } + + @Override + public void endElement(String uri, String name, String qName) throws SAXException { + if (qName.equals(resultElement)) { + results.put(resultHandler.getResult()); + inResult = false; + } else if (qName.equals("BatchResultErrorEntry")) { + errors.add(errorHandler.getResult()); + inError = false; + } else if (inResult) { + resultHandler.endElement(uri, name, qName); + } else if (inError) { + errorHandler.endElement(uri, name, qName); + } + } + + @Override + public void characters(char ch[], int start, int length) throws SAXException { + if (inResult) { + resultHandler.characters(ch, start, length); + } else if (inError) { + errorHandler.characters(ch, start, length); + } + } + +} diff --git a/demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/tweetstore/reference/TweetStoreConstants.java b/apis/sqs/src/main/java/org/jclouds/sqs/xml/ChangeMessageVisibilityBatchResponseHandler.java similarity index 60% rename from demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/tweetstore/reference/TweetStoreConstants.java rename to apis/sqs/src/main/java/org/jclouds/sqs/xml/ChangeMessageVisibilityBatchResponseHandler.java index 42ec480ae2..819f67158f 100644 --- a/demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/tweetstore/reference/TweetStoreConstants.java +++ b/apis/sqs/src/main/java/org/jclouds/sqs/xml/ChangeMessageVisibilityBatchResponseHandler.java @@ -16,19 +16,21 @@ * specific language governing permissions and limitations * under the License. */ -package org.jclouds.demo.tweetstore.reference; +package org.jclouds.sqs.xml; + +import javax.inject.Inject; /** - * Configuration properties and constants used in TweetStore connections. + * @see docs * * @author Adrian Cole */ -public interface TweetStoreConstants { - static final String PROPERTY_TWEETSTORE_BLOBSTORES = "jclouds.tweetstore.blobstores"; - static final String PROPERTY_TWEETSTORE_CONTAINER = "jclouds.tweetstore.container"; - /** - * Note that this has to conform to restrictions of all blobstores. for - * example, azure doesn't support periods. - */ - static final String SENDER_NAME = "sendername"; +public class ChangeMessageVisibilityBatchResponseHandler extends BatchResponseHandler { + @Inject + protected ChangeMessageVisibilityBatchResponseHandler(IdHandler resultHandler, BatchErrorHandler errorHandler) { + super("ChangeMessageVisibilityBatchResultEntry", resultHandler, errorHandler); + } + } diff --git a/labs/sqs/src/main/java/org/jclouds/sqs/config/SQSRestClientModule.java b/apis/sqs/src/main/java/org/jclouds/sqs/xml/DeleteMessageBatchResponseHandler.java similarity index 62% rename from labs/sqs/src/main/java/org/jclouds/sqs/config/SQSRestClientModule.java rename to apis/sqs/src/main/java/org/jclouds/sqs/xml/DeleteMessageBatchResponseHandler.java index bcf8de4c65..1933851b15 100644 --- a/labs/sqs/src/main/java/org/jclouds/sqs/config/SQSRestClientModule.java +++ b/apis/sqs/src/main/java/org/jclouds/sqs/xml/DeleteMessageBatchResponseHandler.java @@ -16,25 +16,22 @@ * specific language governing permissions and limitations * under the License. */ -package org.jclouds.sqs.config; +package org.jclouds.sqs.xml; -import org.jclouds.aws.config.FormSigningRestClientModule; -import org.jclouds.rest.ConfiguresRestClient; -import org.jclouds.sqs.SQSApi; -import org.jclouds.sqs.SQSAsyncApi; - -import com.google.common.reflect.TypeToken; +import javax.inject.Inject; /** - * Configures the SQS connection. + * @see docs * * @author Adrian Cole */ -@ConfiguresRestClient -public class SQSRestClientModule extends FormSigningRestClientModule { +public class DeleteMessageBatchResponseHandler extends BatchResponseHandler { - public SQSRestClientModule() { - super(TypeToken.of(SQSApi.class), TypeToken.of(SQSAsyncApi.class)); + @Inject + protected DeleteMessageBatchResponseHandler(IdHandler resultHandler, BatchErrorHandler errorHandler) { + super("DeleteMessageBatchResultEntry", resultHandler, errorHandler); } } diff --git a/demos/tweetstore/gae-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/reference/TweetStoreConstants.java b/apis/sqs/src/main/java/org/jclouds/sqs/xml/IdHandler.java similarity index 56% rename from demos/tweetstore/gae-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/reference/TweetStoreConstants.java rename to apis/sqs/src/main/java/org/jclouds/sqs/xml/IdHandler.java index 42ec480ae2..35d9f42191 100644 --- a/demos/tweetstore/gae-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/reference/TweetStoreConstants.java +++ b/apis/sqs/src/main/java/org/jclouds/sqs/xml/IdHandler.java @@ -16,19 +16,31 @@ * specific language governing permissions and limitations * under the License. */ -package org.jclouds.demo.tweetstore.reference; +package org.jclouds.sqs.xml; + +import java.util.Map; + +import javax.inject.Inject; + +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Iterables; /** - * Configuration properties and constants used in TweetStore connections. + * @see * * @author Adrian Cole */ -public interface TweetStoreConstants { - static final String PROPERTY_TWEETSTORE_BLOBSTORES = "jclouds.tweetstore.blobstores"; - static final String PROPERTY_TWEETSTORE_CONTAINER = "jclouds.tweetstore.container"; - /** - * Note that this has to conform to restrictions of all blobstores. for - * example, azure doesn't support periods. - */ - static final String SENDER_NAME = "sendername"; +public class IdHandler extends TextFromSingleElementHandler> { + @Inject + protected IdHandler(String elementName) { + super("Id"); + } + + @Override + public Map.Entry apply(String in) { + return Iterables.getOnlyElement(ImmutableMap.of(in, in).entrySet()); + } + } diff --git a/labs/sqs/src/main/java/org/jclouds/sqs/xml/MessageHandler.java b/apis/sqs/src/main/java/org/jclouds/sqs/xml/MessageHandler.java similarity index 100% rename from labs/sqs/src/main/java/org/jclouds/sqs/xml/MessageHandler.java rename to apis/sqs/src/main/java/org/jclouds/sqs/xml/MessageHandler.java diff --git a/labs/sqs/src/main/java/org/jclouds/sqs/xml/ReceiveMessageResponseHandler.java b/apis/sqs/src/main/java/org/jclouds/sqs/xml/ReceiveMessageResponseHandler.java similarity index 86% rename from labs/sqs/src/main/java/org/jclouds/sqs/xml/ReceiveMessageResponseHandler.java rename to apis/sqs/src/main/java/org/jclouds/sqs/xml/ReceiveMessageResponseHandler.java index 7976476acc..e30c82b607 100644 --- a/labs/sqs/src/main/java/org/jclouds/sqs/xml/ReceiveMessageResponseHandler.java +++ b/apis/sqs/src/main/java/org/jclouds/sqs/xml/ReceiveMessageResponseHandler.java @@ -20,15 +20,14 @@ package org.jclouds.sqs.xml; import static org.jclouds.util.SaxUtils.equalsOrSuffix; -import java.util.Set; - import org.jclouds.http.functions.ParseSax; import org.jclouds.sqs.domain.Message; import org.xml.sax.Attributes; import org.xml.sax.SAXException; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.ImmutableSet.Builder; +import com.google.common.collect.FluentIterable; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableList.Builder; import com.google.inject.Inject; /** @@ -38,11 +37,11 @@ import com.google.inject.Inject; * * @author Adrian Cole */ -public class ReceiveMessageResponseHandler extends ParseSax.HandlerForGeneratedRequestWithResult> { +public class ReceiveMessageResponseHandler extends ParseSax.HandlerForGeneratedRequestWithResult> { private final MessageHandler messageHandler; - private Builder messages = ImmutableSet. builder(); + private Builder messages = ImmutableList. builder(); private boolean inMessages; @@ -52,8 +51,8 @@ public class ReceiveMessageResponseHandler extends ParseSax.HandlerForGeneratedR } @Override - public Set getResult() { - return messages.build(); + public FluentIterable getResult() { + return FluentIterable.from(messages.build()); } @Override diff --git a/labs/sqs/src/main/java/org/jclouds/sqs/xml/RegexListQueuesResponseHandler.java b/apis/sqs/src/main/java/org/jclouds/sqs/xml/RegexListQueuesResponseHandler.java similarity index 90% rename from labs/sqs/src/main/java/org/jclouds/sqs/xml/RegexListQueuesResponseHandler.java rename to apis/sqs/src/main/java/org/jclouds/sqs/xml/RegexListQueuesResponseHandler.java index 58b580f9d1..dfcccc0b00 100644 --- a/labs/sqs/src/main/java/org/jclouds/sqs/xml/RegexListQueuesResponseHandler.java +++ b/apis/sqs/src/main/java/org/jclouds/sqs/xml/RegexListQueuesResponseHandler.java @@ -19,7 +19,6 @@ package org.jclouds.sqs.xml; import java.net.URI; -import java.util.Set; import javax.inject.Inject; import javax.inject.Singleton; @@ -29,6 +28,7 @@ import org.jclouds.http.functions.ReturnStringIf2xx; import org.jclouds.sqs.xml.internal.BaseRegexQueueHandler; import com.google.common.base.Function; +import com.google.common.collect.FluentIterable; /** * @@ -38,7 +38,7 @@ import com.google.common.base.Function; * @author Adrian Cole */ @Singleton -public class RegexListQueuesResponseHandler extends BaseRegexQueueHandler implements Function> { +public class RegexListQueuesResponseHandler extends BaseRegexQueueHandler implements Function> { private final ReturnStringIf2xx returnStringIf200; @Inject @@ -47,7 +47,7 @@ public class RegexListQueuesResponseHandler extends BaseRegexQueueHandler implem } @Override - public Set apply(HttpResponse response) { + public FluentIterable apply(HttpResponse response) { return parse(returnStringIf200.apply(response)); } diff --git a/labs/sqs/src/main/java/org/jclouds/sqs/xml/RegexMessageIdAndMD5Handler.java b/apis/sqs/src/main/java/org/jclouds/sqs/xml/RegexMessageIdAndMD5Handler.java similarity index 92% rename from labs/sqs/src/main/java/org/jclouds/sqs/xml/RegexMessageIdAndMD5Handler.java rename to apis/sqs/src/main/java/org/jclouds/sqs/xml/RegexMessageIdAndMD5Handler.java index 9baf8a5531..c7cf3c0ca2 100644 --- a/labs/sqs/src/main/java/org/jclouds/sqs/xml/RegexMessageIdAndMD5Handler.java +++ b/apis/sqs/src/main/java/org/jclouds/sqs/xml/RegexMessageIdAndMD5Handler.java @@ -40,7 +40,7 @@ import com.google.inject.Singleton; */ @Singleton public class RegexMessageIdAndMD5Handler implements Function { - Pattern pattern = Pattern.compile("([\\S&&[^<]]+)\\s*([\\S&&[^<]]+)", Pattern.DOTALL); + private static final Pattern pattern = Pattern.compile("([\\S&&[^<]]+)\\s*([\\S&&[^<]]+)", Pattern.DOTALL); private final ReturnStringIf2xx returnStringIf200; @Inject diff --git a/labs/sqs/src/main/java/org/jclouds/sqs/xml/RegexQueueHandler.java b/apis/sqs/src/main/java/org/jclouds/sqs/xml/RegexQueueHandler.java similarity index 96% rename from labs/sqs/src/main/java/org/jclouds/sqs/xml/RegexQueueHandler.java rename to apis/sqs/src/main/java/org/jclouds/sqs/xml/RegexQueueHandler.java index e79a763b74..1308545044 100644 --- a/labs/sqs/src/main/java/org/jclouds/sqs/xml/RegexQueueHandler.java +++ b/apis/sqs/src/main/java/org/jclouds/sqs/xml/RegexQueueHandler.java @@ -42,7 +42,7 @@ public class RegexQueueHandler extends BaseRegexQueueHandler implements Function private final ReturnStringIf2xx returnStringIf200; @Inject - RegexQueueHandler(ReturnStringIf2xx returnStringIf200) { + public RegexQueueHandler(ReturnStringIf2xx returnStringIf200) { this.returnStringIf200 = returnStringIf200; } diff --git a/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/reference/TweetStoreConstants.java b/apis/sqs/src/main/java/org/jclouds/sqs/xml/SendMessageBatchResponseHandler.java similarity index 58% rename from demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/reference/TweetStoreConstants.java rename to apis/sqs/src/main/java/org/jclouds/sqs/xml/SendMessageBatchResponseHandler.java index 42ec480ae2..bb7780e29b 100644 --- a/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/reference/TweetStoreConstants.java +++ b/apis/sqs/src/main/java/org/jclouds/sqs/xml/SendMessageBatchResponseHandler.java @@ -16,19 +16,25 @@ * specific language governing permissions and limitations * under the License. */ -package org.jclouds.demo.tweetstore.reference; +package org.jclouds.sqs.xml; + +import javax.inject.Inject; + +import org.jclouds.sqs.domain.MessageIdAndMD5; /** - * Configuration properties and constants used in TweetStore connections. + * @see docs * * @author Adrian Cole */ -public interface TweetStoreConstants { - static final String PROPERTY_TWEETSTORE_BLOBSTORES = "jclouds.tweetstore.blobstores"; - static final String PROPERTY_TWEETSTORE_CONTAINER = "jclouds.tweetstore.container"; - /** - * Note that this has to conform to restrictions of all blobstores. for - * example, azure doesn't support periods. - */ - static final String SENDER_NAME = "sendername"; +public class SendMessageBatchResponseHandler extends BatchResponseHandler { + + @Inject + protected SendMessageBatchResponseHandler(SendMessageBatchResultEntryHandler resultHandler, + BatchErrorHandler errorHandler) { + super("SendMessageBatchResultEntry", resultHandler, errorHandler); + } + } diff --git a/apis/sqs/src/main/java/org/jclouds/sqs/xml/SendMessageBatchResultEntryHandler.java b/apis/sqs/src/main/java/org/jclouds/sqs/xml/SendMessageBatchResultEntryHandler.java new file mode 100644 index 0000000000..0474e2e75f --- /dev/null +++ b/apis/sqs/src/main/java/org/jclouds/sqs/xml/SendMessageBatchResultEntryHandler.java @@ -0,0 +1,74 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.sqs.xml; + +import static org.jclouds.util.SaxUtils.currentOrNull; + +import java.util.Map; +import java.util.Map.Entry; + +import org.jclouds.crypto.CryptoStreams; +import org.jclouds.http.functions.ParseSax; +import org.jclouds.sqs.domain.MessageIdAndMD5; + +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Iterables; +import com.google.common.hash.HashCodes; + +/** + * @see + * + * @author Adrian Cole + */ +public class SendMessageBatchResultEntryHandler extends + ParseSax.HandlerForGeneratedRequestWithResult> { + + private StringBuilder currentText = new StringBuilder(); + private MessageIdAndMD5.Builder builder = MessageIdAndMD5.builder(); + private String id; + + @Override + public Entry getResult() { + try { + return Iterables.getOnlyElement(ImmutableMap.of(id, builder.build()).entrySet()); + } finally { + builder = MessageIdAndMD5.builder(); + } + } + + @Override + public void endElement(String uri, String name, String qName) { + if (qName.equals("Id")) { + this.id = currentOrNull(currentText); + } else if (qName.equals("MessageId")) { + builder.id(currentOrNull(currentText)); + } else if (qName.equals("MD5OfMessageBody")) { + builder.md5(HashCodes.fromBytes(CryptoStreams.hex(currentOrNull(currentText)))); + } + currentText = new StringBuilder(); + } + + @Override + public void characters(char ch[], int start, int length) { + currentText.append(ch, start, length); + } + +} diff --git a/apis/sqs/src/main/java/org/jclouds/sqs/xml/TextFromSingleElementHandler.java b/apis/sqs/src/main/java/org/jclouds/sqs/xml/TextFromSingleElementHandler.java new file mode 100644 index 0000000000..cfde3d14df --- /dev/null +++ b/apis/sqs/src/main/java/org/jclouds/sqs/xml/TextFromSingleElementHandler.java @@ -0,0 +1,63 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.sqs.xml; + +import static com.google.common.base.Preconditions.checkNotNull; +import static org.jclouds.util.SaxUtils.currentOrNull; + +import org.jclouds.http.functions.ParseSax; + +import com.google.common.base.Function; + +/** + * looks for a single value in the xml + * + * @author Adrian Cole + */ +public abstract class TextFromSingleElementHandler extends ParseSax.HandlerForGeneratedRequestWithResult + implements Function { + private final String elementName; + + protected TextFromSingleElementHandler(String elementName) { + this.elementName = checkNotNull(elementName, "elementName"); + } + + private StringBuilder currentText = new StringBuilder(); + private String text; + + @Override + public V getResult() { + return apply(text); + } + + // this could be done with regex, if we had an unescaper + @Override + public void endElement(String uri, String name, String qName) { + if (qName.equals(elementName)) { + text = currentOrNull(currentText); + } + currentText = new StringBuilder(); + } + + @Override + public void characters(char ch[], int start, int length) { + currentText.append(ch, start, length); + } + +} diff --git a/apis/sqs/src/main/java/org/jclouds/sqs/xml/ValueHandler.java b/apis/sqs/src/main/java/org/jclouds/sqs/xml/ValueHandler.java new file mode 100644 index 0000000000..c3764d3a83 --- /dev/null +++ b/apis/sqs/src/main/java/org/jclouds/sqs/xml/ValueHandler.java @@ -0,0 +1,41 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.sqs.xml; + +import javax.inject.Inject; + +/** + * @see + * + * @author Adrian Cole + */ +public class ValueHandler extends TextFromSingleElementHandler { + @Inject + protected ValueHandler(String elementName) { + super("Value"); + } + + @Override + public String apply(String in) { + return in; + } + +} diff --git a/labs/sqs/src/main/java/org/jclouds/sqs/xml/internal/BaseRegexQueueHandler.java b/apis/sqs/src/main/java/org/jclouds/sqs/xml/internal/BaseRegexQueueHandler.java similarity index 89% rename from labs/sqs/src/main/java/org/jclouds/sqs/xml/internal/BaseRegexQueueHandler.java rename to apis/sqs/src/main/java/org/jclouds/sqs/xml/internal/BaseRegexQueueHandler.java index a2c7a5f464..c4b541ea7f 100644 --- a/labs/sqs/src/main/java/org/jclouds/sqs/xml/internal/BaseRegexQueueHandler.java +++ b/apis/sqs/src/main/java/org/jclouds/sqs/xml/internal/BaseRegexQueueHandler.java @@ -19,13 +19,13 @@ package org.jclouds.sqs.xml.internal; import java.net.URI; -import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.inject.Singleton; import com.google.common.base.Strings; +import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet.Builder; @@ -38,9 +38,9 @@ import com.google.common.collect.ImmutableSet.Builder; */ @Singleton public class BaseRegexQueueHandler { - protected final Pattern pattern = Pattern.compile("(https://[\\S&&[^<]]+)"); + protected final Pattern pattern = Pattern.compile("(https?://[\\S&&[^<]]+)"); - public Set parse(String in) { + public FluentIterable parse(String in) { Builder queues = ImmutableSet. builder(); Matcher matcher = pattern.matcher(in); while (matcher.find()) { @@ -48,7 +48,7 @@ public class BaseRegexQueueHandler { if (!Strings.isNullOrEmpty(uriText)) queues.add(URI.create(uriText)); } - return queues.build(); + return FluentIterable.from(queues.build()); } } diff --git a/labs/sqs/src/main/resources/META-INF/services/org.jclouds.apis.ApiMetadata b/apis/sqs/src/main/resources/META-INF/services/org.jclouds.apis.ApiMetadata similarity index 100% rename from labs/sqs/src/main/resources/META-INF/services/org.jclouds.apis.ApiMetadata rename to apis/sqs/src/main/resources/META-INF/services/org.jclouds.apis.ApiMetadata diff --git a/labs/sqs/src/test/java/org/jclouds/sqs/SQSApiMetadataTest.java b/apis/sqs/src/test/java/org/jclouds/sqs/SQSApiMetadataTest.java similarity index 100% rename from labs/sqs/src/test/java/org/jclouds/sqs/SQSApiMetadataTest.java rename to apis/sqs/src/test/java/org/jclouds/sqs/SQSApiMetadataTest.java diff --git a/apis/sqs/src/test/java/org/jclouds/sqs/SQSTest.java b/apis/sqs/src/test/java/org/jclouds/sqs/SQSTest.java new file mode 100644 index 0000000000..26b31b16c6 --- /dev/null +++ b/apis/sqs/src/test/java/org/jclouds/sqs/SQSTest.java @@ -0,0 +1,88 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.sqs; + +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expect; + +import org.easymock.EasyMock; +import org.jclouds.sqs.domain.Message; +import org.jclouds.sqs.features.MessageApi; +import org.jclouds.sqs.options.ReceiveMessageOptions; +import org.testng.Assert; +import org.testng.annotations.Test; + +import com.google.common.collect.FluentIterable; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Iterables; + +/** + * Tests behavior of {@code SQS}. + * + * @author Adrian Cole + */ +@Test(testName = "SQSTest", singleThreaded = true) +public class SQSTest { + + /** + * Tests {@link SQS#receiveAllAtRate} where a single response returns all + * results. + */ + @Test + public void testSinglePageResult() throws Exception { + MessageApi messageClient = createMock(MessageApi.class); + ReceiveMessageOptions options = new ReceiveMessageOptions(); + FluentIterable aMessage = FluentIterable.from(ImmutableSet.of(createMock(Message.class))); + FluentIterable noMessages = FluentIterable.from(ImmutableSet.of()); + + expect(messageClient.receive(1, options)) + .andReturn(aMessage) + .once(); + + expect(messageClient.receive(1, options)) + .andReturn(noMessages) + .once(); + + EasyMock.replay(messageClient); + + Assert.assertEquals(1, Iterables.size(SQS.receiveAllAtRate(messageClient, 1, options))); + } + + /** + * Tests {@link SQS#receiveAllAtRate} where retrieving all results requires multiple requests. + */ + @Test + public void testMultiPageResult() throws Exception { + MessageApi messageClient = createMock(MessageApi.class); + ReceiveMessageOptions options = new ReceiveMessageOptions(); + FluentIterable aMessage = FluentIterable.from(ImmutableSet.of(createMock(Message.class))); + FluentIterable noMessages = FluentIterable.from(ImmutableSet.of()); + + expect(messageClient.receive(1, options)) + .andReturn(aMessage) + .times(2); + expect(messageClient.receive(1, options)) + .andReturn(noMessages) + .once(); + + EasyMock.replay(messageClient); + + Assert.assertEquals(2, Iterables.size(SQS.receiveAllAtRate(messageClient, 1, options))); + } +} diff --git a/apis/sqs/src/test/java/org/jclouds/sqs/features/BulkMessageApiLiveTest.java b/apis/sqs/src/test/java/org/jclouds/sqs/features/BulkMessageApiLiveTest.java new file mode 100644 index 0000000000..3c9ad94259 --- /dev/null +++ b/apis/sqs/src/test/java/org/jclouds/sqs/features/BulkMessageApiLiveTest.java @@ -0,0 +1,126 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.sqs.features; + +import static org.jclouds.sqs.options.ReceiveMessageOptions.Builder.attribute; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNull; + +import java.net.URI; +import java.util.Map.Entry; +import java.util.Set; + +import org.jclouds.sqs.SQS; +import org.jclouds.sqs.domain.BatchResult; +import org.jclouds.sqs.domain.Message; +import org.jclouds.sqs.domain.MessageIdAndMD5; +import org.jclouds.sqs.internal.BaseSQSApiLiveTest; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import com.google.common.base.Charsets; +import com.google.common.base.Function; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableMap.Builder; +import com.google.common.collect.Iterables; +import com.google.common.hash.Hashing; + +/** + * + * @author Adrian Cole + */ +@Test(groups = "live", singleThreaded = true, testName = "BulkMessageApiLiveTest") +public class BulkMessageApiLiveTest extends BaseSQSApiLiveTest { + + private ImmutableMap idPayload; + + public BulkMessageApiLiveTest() { + prefix = prefix + "-bulk"; + + Builder builder = ImmutableMap. builder(); + for (int i = 0; i < 10; i++) { + String message = "hardyharhar" + i; + builder.put(i + "", message); + } + idPayload = builder.build(); + } + + @BeforeClass(groups = { "integration", "live" }) + @Override + public void setupContext() { + super.setupContext(); + recreateQueueInRegion(prefix, null); + } + + public void testSendMessages() { + for (URI queue : queues) { + BatchResult acks = api().getMessageApiForQueue(queue).send(idPayload); + + assertEquals(acks.size(), idPayload.size(), "error sending " + acks); + assertEquals(acks.keySet(), idPayload.keySet()); + + for (Entry entry : acks.entrySet()) { + assertEquals(entry.getValue().getMD5(), + Hashing.md5().hashString(idPayload.get(entry.getKey()), Charsets.UTF_8), "bad md5 for: " + entry); + } + } + } + + private Iterable receiptHandles; + + @Test(dependsOnMethods = "testSendMessages") + public void testChangeMessageVisibility() { + for (URI queue : queues) { + MessageApi api = api().getMessageApiForQueue(queue); + + Set messages = collectMessages(api); + + receiptHandles = Iterables.transform(messages, new Function() { + @Override + public String apply(Message in) { + return in.getReceiptHandle(); + } + }); + + // hidden message, so we can't see it + assertNull(api.receive()); + + // this should unhide it + BatchResult acks = api.changeVisibility(receiptHandles, 0); + assertEquals(acks.size(), messages.size(), "error changing visibility " + acks); + + // so we can see it again + assertEquals(collectMessages(api).size(), messages.size()); + } + } + + protected Set collectMessages(MessageApi api) { + return SQS.receiveAllAtRate(api, idPayload.size(), attribute("None").visibilityTimeout(5)).toImmutableSet(); + } + + @Test(dependsOnMethods = "testChangeMessageVisibility") + public void testDeleteMessage() throws InterruptedException { + for (URI queue : queues) { + BatchResult acks = api().getMessageApiForQueue(queue).delete(receiptHandles); + assertEquals(acks.size(), Iterables.size(receiptHandles), "error deleting messages " + acks); + assertNoMessages(queue); + } + } + +} diff --git a/apis/sqs/src/test/java/org/jclouds/sqs/features/MessageApiExpectTest.java b/apis/sqs/src/test/java/org/jclouds/sqs/features/MessageApiExpectTest.java new file mode 100644 index 0000000000..da2fa1b138 --- /dev/null +++ b/apis/sqs/src/test/java/org/jclouds/sqs/features/MessageApiExpectTest.java @@ -0,0 +1,542 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.sqs.features; + +import static org.testng.Assert.assertEquals; + +import org.jclouds.http.HttpRequest; +import org.jclouds.http.HttpResponse; +import org.jclouds.sqs.SQSApi; +import org.jclouds.sqs.internal.BaseSQSApiExpectTest; +import org.jclouds.sqs.parse.ChangeMessageVisibilityBatchResponseTest; +import org.jclouds.sqs.parse.DeleteMessageBatchResponseTest; +import org.jclouds.sqs.parse.ReceiveMessageResponseTest; +import org.jclouds.sqs.parse.SendMessageBatchResponseTest; +import org.jclouds.sqs.parse.SendMessageResponseTest; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.ImmutableTable; +import com.google.common.collect.Iterables; + +/** + * @author Adrian Cole + */ +@Test(groups = "unit", testName = "MessageApiExpectTest") +public class MessageApiExpectTest extends BaseSQSApiExpectTest { + + public HttpRequest sendMessage = HttpRequest.builder() + .method("POST") + .endpoint("https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/") + .addHeader("Host", "sqs.us-east-1.amazonaws.com") + .addFormParam("Action", "SendMessage") + .addFormParam("MessageBody", "hardyharhar") + .addFormParam("Signature", "PVzszzgIcT1xt9%2BEzGzWB2Bt8zDadBc48HsgF89AoJE%3D") + .addFormParam("SignatureMethod", "HmacSHA256") + .addFormParam("SignatureVersion", "2") + .addFormParam("Timestamp", "2009-11-08T15%3A54%3A08.897Z") + .addFormParam("Version", "2011-10-01") + .addFormParam("AWSAccessKeyId", "identity").build(); + + public void testSendMessageWhenResponseIs2xx() throws Exception { + + HttpResponse sendMessageResponse = HttpResponse.builder().statusCode(200) + .payload(payloadFromResourceWithContentType("/send_message.xml", "text/xml")).build(); + + SQSApi apiWhenExist = requestSendsResponse(sendMessage, sendMessageResponse); + + assertEquals(apiWhenExist.getMessageApiForQueue(queue).send("hardyharhar").toString(), + new SendMessageResponseTest().expected().toString()); + } + + public HttpRequest sendMessageIterable = HttpRequest.builder() + .method("POST") + .endpoint("https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/") + .addHeader("Host", "sqs.us-east-1.amazonaws.com") + .addFormParam("Action", "SendMessageBatch") + .addFormParam("SendMessageBatchRequestEntry.1.Id", "1") + .addFormParam("SendMessageBatchRequestEntry.1.MessageBody", "payload1") + .addFormParam("SendMessageBatchRequestEntry.2.Id", "2") + .addFormParam("SendMessageBatchRequestEntry.2.MessageBody", "payload2") + .addFormParam("Signature", "2AYMDMLhoLncALJgBfHBGfOkaTB5ut3PeFRJeWffxdI%3D") + .addFormParam("SignatureMethod", "HmacSHA256") + .addFormParam("SignatureVersion", "2") + .addFormParam("Timestamp", "2009-11-08T15%3A54%3A08.897Z") + .addFormParam("Version", "2011-10-01") + .addFormParam("AWSAccessKeyId", "identity").build(); + + public void testSendMessageIterableWhenResponseIs2xx() throws Exception { + + HttpResponse sendMessageResponse = HttpResponse.builder() + .statusCode(200) + .payload(payloadFromResourceWithContentType("/send_message_batch.xml", "text/xml")).build(); + + SQSApi apiWhenExist = requestSendsResponse(sendMessageIterable, sendMessageResponse); + + assertEquals(apiWhenExist.getMessageApiForQueue(queue).send(ImmutableSet.of("payload1", "payload2")) + .toString(), new SendMessageBatchResponseTest().expected().toString()); + } + + public HttpRequest sendMessageMap = HttpRequest.builder() + .method("POST") + .endpoint("https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/") + .addHeader("Host", "sqs.us-east-1.amazonaws.com") + .addFormParam("Action", "SendMessageBatch") + .addFormParam("SendMessageBatchRequestEntry.1.Id", "foo1") + .addFormParam("SendMessageBatchRequestEntry.1.MessageBody", "payload1") + .addFormParam("SendMessageBatchRequestEntry.2.Id", "foo2") + .addFormParam("SendMessageBatchRequestEntry.2.MessageBody", "payload2") + .addFormParam("Signature", "f9v8e%2FrPXTI3zhBYMhg7U8yCfvPqHjAV8bFjhGL6%2BXc%3D") + .addFormParam("SignatureMethod", "HmacSHA256") + .addFormParam("SignatureVersion", "2") + .addFormParam("Timestamp", "2009-11-08T15%3A54%3A08.897Z") + .addFormParam("Version", "2011-10-01") + .addFormParam("AWSAccessKeyId", "identity").build(); + + public void testSendMessageMapWhenResponseIs2xx() throws Exception { + + HttpResponse sendMessageResponse = HttpResponse.builder() + .statusCode(200) + .payload(payloadFromResourceWithContentType("/send_message_batch.xml", "text/xml")).build(); + + SQSApi apiWhenExist = requestSendsResponse(sendMessageMap, sendMessageResponse); + + assertEquals( + apiWhenExist.getMessageApiForQueue(queue) + .send(ImmutableMap.of("foo1", "payload1", "foo2", "payload2")).toString(), + new SendMessageBatchResponseTest().expected().toString()); + } + + public HttpRequest sendMessageWithDelayMap = HttpRequest.builder() + .method("POST") + .endpoint("https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/") + .addHeader("Host", "sqs.us-east-1.amazonaws.com") + .addFormParam("Action", "SendMessageBatch") + .addFormParam("SendMessageBatchRequestEntry.1.DelaySeconds", "10") + .addFormParam("SendMessageBatchRequestEntry.1.Id", "foo1") + .addFormParam("SendMessageBatchRequestEntry.1.MessageBody", "payload1") + .addFormParam("SendMessageBatchRequestEntry.2.DelaySeconds", "10") + .addFormParam("SendMessageBatchRequestEntry.2.Id", "foo2") + .addFormParam("SendMessageBatchRequestEntry.2.MessageBody", "payload2") + .addFormParam("Signature", "COjjEaJ76EwziEFtkT2FuSRSbrCIu%2FhlJf1Zmu7cYoU%3D") + .addFormParam("SignatureMethod", "HmacSHA256") + .addFormParam("SignatureVersion", "2") + .addFormParam("Timestamp", "2009-11-08T15%3A54%3A08.897Z") + .addFormParam("Version", "2011-10-01") + .addFormParam("AWSAccessKeyId", "identity").build(); + + public void testSendMessageWithDelayMapWhenResponseIs2xx() throws Exception { + + HttpResponse sendMessageResponse = HttpResponse.builder() + .statusCode(200) + .payload(payloadFromResourceWithContentType("/send_message_batch.xml", "text/xml")).build(); + + SQSApi apiWhenExist = requestSendsResponse(sendMessageWithDelayMap, sendMessageResponse); + + assertEquals(apiWhenExist.getMessageApiForQueue(queue).sendWithDelay(ImmutableMap.builder() + .put("foo1", "payload1") + .put("foo2", "payload2") + .build(), 10) + .toString(), new SendMessageBatchResponseTest().expected().toString()); + } + + public HttpRequest sendMessageWithDelayIterable = HttpRequest.builder() + .method("POST") + .endpoint("https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/") + .addHeader("Host", "sqs.us-east-1.amazonaws.com") + .addFormParam("Action", "SendMessageBatch") + .addFormParam("SendMessageBatchRequestEntry.1.DelaySeconds", "10") + .addFormParam("SendMessageBatchRequestEntry.1.Id", "1") + .addFormParam("SendMessageBatchRequestEntry.1.MessageBody", "payload1") + .addFormParam("SendMessageBatchRequestEntry.2.DelaySeconds", "10") + .addFormParam("SendMessageBatchRequestEntry.2.Id", "2") + .addFormParam("SendMessageBatchRequestEntry.2.MessageBody", "payload2") + .addFormParam("Signature", "8AVNvSVXPSnoXjJAc6h1rysMBBZPnSycbnmD2%2FqpdV8%3D") + .addFormParam("SignatureMethod", "HmacSHA256") + .addFormParam("SignatureVersion", "2") + .addFormParam("Timestamp", "2009-11-08T15%3A54%3A08.897Z") + .addFormParam("Version", "2011-10-01") + .addFormParam("AWSAccessKeyId", "identity").build(); + + public void testSendMessageWithDelayIterableWhenResponseIs2xx() throws Exception { + + HttpResponse sendMessageResponse = HttpResponse.builder() + .statusCode(200) + .payload(payloadFromResourceWithContentType("/send_message_batch.xml", "text/xml")).build(); + + SQSApi apiWhenExist = requestSendsResponse(sendMessageWithDelayIterable, sendMessageResponse); + + assertEquals( + apiWhenExist.getMessageApiForQueue(queue).sendWithDelay(ImmutableSet.of("payload1", "payload2"), 10) + .toString(), new SendMessageBatchResponseTest().expected().toString()); + } + public HttpRequest sendMessageWithDelaysTable = HttpRequest.builder() + .method("POST") + .endpoint("https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/") + .addHeader("Host", "sqs.us-east-1.amazonaws.com") + .addFormParam("Action", "SendMessageBatch") + .addFormParam("SendMessageBatchRequestEntry.1.DelaySeconds", "1") + .addFormParam("SendMessageBatchRequestEntry.1.Id", "foo1") + .addFormParam("SendMessageBatchRequestEntry.1.MessageBody", "payload1") + .addFormParam("SendMessageBatchRequestEntry.2.DelaySeconds", "10") + .addFormParam("SendMessageBatchRequestEntry.2.Id", "foo2") + .addFormParam("SendMessageBatchRequestEntry.2.MessageBody", "payload2") + .addFormParam("Signature", "M2X8Al%2BbyyDM%2B9kdN28rMn1yJWl78hJ5i4GnaMZ1sYg%3D") + .addFormParam("SignatureMethod", "HmacSHA256") + .addFormParam("SignatureVersion", "2") + .addFormParam("Timestamp", "2009-11-08T15%3A54%3A08.897Z") + .addFormParam("Version", "2011-10-01") + .addFormParam("AWSAccessKeyId", "identity").build(); + + public void testSendMessageWithDelaysTableWhenResponseIs2xx() throws Exception { + + HttpResponse sendMessageResponse = HttpResponse.builder() + .statusCode(200) + .payload(payloadFromResourceWithContentType("/send_message_batch.xml", "text/xml")).build(); + + SQSApi apiWhenExist = requestSendsResponse(sendMessageWithDelaysTable, sendMessageResponse); + + assertEquals(apiWhenExist.getMessageApiForQueue(queue).sendWithDelays(ImmutableTable.builder() + .put("foo1", "payload1", 1) + .put("foo2", "payload2", 10) + .build()) + .toString(), new SendMessageBatchResponseTest().expected().toString()); + } + + public HttpRequest sendMessageWithDelaysMap = HttpRequest.builder() + .method("POST") + .endpoint("https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/") + .addHeader("Host", "sqs.us-east-1.amazonaws.com") + .addFormParam("Action", "SendMessageBatch") + .addFormParam("SendMessageBatchRequestEntry.1.DelaySeconds", "1") + .addFormParam("SendMessageBatchRequestEntry.1.Id", "1") + .addFormParam("SendMessageBatchRequestEntry.1.MessageBody", "payload1") + .addFormParam("SendMessageBatchRequestEntry.2.DelaySeconds", "10") + .addFormParam("SendMessageBatchRequestEntry.2.Id", "2") + .addFormParam("SendMessageBatchRequestEntry.2.MessageBody", "payload2") + .addFormParam("Signature", "nbA4UnKDAuQCiCcvQHH%2F1UjMMeo2s3d94A27Q3t9SlI%3D") + .addFormParam("SignatureMethod", "HmacSHA256") + .addFormParam("SignatureVersion", "2") + .addFormParam("Timestamp", "2009-11-08T15%3A54%3A08.897Z") + .addFormParam("Version", "2011-10-01") + .addFormParam("AWSAccessKeyId", "identity").build(); + + public void testSendMessageWithDelaysMapWhenResponseIs2xx() throws Exception { + + HttpResponse sendMessageResponse = HttpResponse.builder() + .statusCode(200) + .payload(payloadFromResourceWithContentType("/send_message_batch.xml", "text/xml")).build(); + + SQSApi apiWhenExist = requestSendsResponse(sendMessageWithDelaysMap, sendMessageResponse); + + assertEquals( + apiWhenExist.getMessageApiForQueue(queue).sendWithDelays(ImmutableMap.of("payload1", 1, "payload2", 10)) + .toString(), new SendMessageBatchResponseTest().expected().toString()); + } + + public HttpRequest receiveMessage = HttpRequest.builder() + .method("POST") + .endpoint("https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/") + .addHeader("Host", "sqs.us-east-1.amazonaws.com") + .addFormParam("Action", "ReceiveMessage") + .addFormParam("Signature", "UURXsAjggoaz5P1h2EFswRd8Ji9euHmXhHvrAmIqM1E%3D") + .addFormParam("SignatureMethod", "HmacSHA256") + .addFormParam("SignatureVersion", "2") + .addFormParam("Timestamp", "2009-11-08T15%3A54%3A08.897Z") + .addFormParam("Version", "2011-10-01") + .addFormParam("AWSAccessKeyId", "identity").build(); + + public void testReceiveMessageWhenResponseIs2xx() throws Exception { + + HttpResponse receiveMessageResponse = HttpResponse.builder().statusCode(200) + .payload(payloadFromResourceWithContentType("/messages.xml", "text/xml")).build(); + + SQSApi apiWhenExist = requestSendsResponse(receiveMessage, receiveMessageResponse); + + assertEquals(apiWhenExist.getMessageApiForQueue(queue).receive().toString(), + Iterables.get(new ReceiveMessageResponseTest().expected(), 0).toString()); + } + + + public HttpRequest receiveMessages = HttpRequest.builder() + .method("POST") + .endpoint("https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/") + .addHeader("Host", "sqs.us-east-1.amazonaws.com") + .addFormParam("Action", "ReceiveMessage") + .addFormParam("MaxNumberOfMessages", "10") + .addFormParam("Signature", "pZ9B4%2BTBvQA4n0joP4t8ue5x0xmKMd9prpVLVoT%2F7qU%3D") + .addFormParam("SignatureMethod", "HmacSHA256") + .addFormParam("SignatureVersion", "2") + .addFormParam("Timestamp", "2009-11-08T15%3A54%3A08.897Z") + .addFormParam("Version", "2011-10-01") + .addFormParam("AWSAccessKeyId", "identity").build(); + + public void testReceiveMessagesWhenResponseIs2xx() throws Exception { + + HttpResponse receiveMessagesResponse = HttpResponse.builder().statusCode(200) + .payload(payloadFromResourceWithContentType("/messages.xml", "text/xml")).build(); + + SQSApi apiWhenExist = requestSendsResponse(receiveMessages, receiveMessagesResponse); + + assertEquals(apiWhenExist.getMessageApiForQueue(queue).receive(10).toString(), new ReceiveMessageResponseTest() + .expected().toString()); + } + + public HttpRequest deleteMessage = HttpRequest.builder() + .method("POST") + .endpoint("https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/") + .addHeader("Host", "sqs.us-east-1.amazonaws.com") + .addFormParam("Action", "DeleteMessage") + .addFormParam("ReceiptHandle", "eXJYhj5rDr9cAe") + .addFormParam("Signature", "9%2FkuCc2i78gMsmul%2BRsOPcdQ1OLUKrItqgGIRRBJb8M%3D") + .addFormParam("SignatureMethod", "HmacSHA256") + .addFormParam("SignatureVersion", "2") + .addFormParam("Timestamp", "2009-11-08T15%3A54%3A08.897Z") + .addFormParam("Version", "2011-10-01") + .addFormParam("AWSAccessKeyId", "identity").build(); + + public void testDeleteMessageWhenResponseIs2xx() throws Exception { + + HttpResponse deleteMessageResponse = HttpResponse.builder() + .statusCode(200) + .payload( + payloadFromStringWithContentType( + "b5293cb5-d306-4a17-9048-b263635abe42", + "text/xml")).build(); + + SQSApi apiWhenExist = requestSendsResponse(deleteMessage, deleteMessageResponse); + + apiWhenExist.getMessageApiForQueue(queue).delete("eXJYhj5rDr9cAe"); + } + + public HttpRequest deleteMessageIterable = HttpRequest.builder() + .method("POST") + .endpoint("https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/") + .addHeader("Host", "sqs.us-east-1.amazonaws.com") + .addFormParam("Action", "DeleteMessageBatch") + .addFormParam("DeleteMessageBatchRequestEntry.1.Id", "1") + .addFormParam("DeleteMessageBatchRequestEntry.1.ReceiptHandle", "eXJYhj5rDr9cAe") + .addFormParam("DeleteMessageBatchRequestEntry.2.Id", "2") + .addFormParam("DeleteMessageBatchRequestEntry.2.ReceiptHandle", "fffeeerrr") + .addFormParam("Signature", "S4xIobjm3LOkJvibeI2X54nxKJw9r1a5zj%2FdvHlfDMY%3D") + .addFormParam("SignatureMethod", "HmacSHA256") + .addFormParam("SignatureVersion", "2") + .addFormParam("Timestamp", "2009-11-08T15%3A54%3A08.897Z") + .addFormParam("Version", "2011-10-01") + .addFormParam("AWSAccessKeyId", "identity").build(); + + public void testDeleteMessageIterableWhenResponseIs2xx() throws Exception { + + HttpResponse deleteMessageResponse = HttpResponse.builder() + .statusCode(200) + .payload(payloadFromResourceWithContentType("/delete_message_batch.xml", "text/xml")).build(); + + SQSApi apiWhenExist = requestSendsResponse(deleteMessageIterable, deleteMessageResponse); + + assertEquals(apiWhenExist.getMessageApiForQueue(queue).delete(ImmutableSet.of("eXJYhj5rDr9cAe", "fffeeerrr")) + .toString(), new DeleteMessageBatchResponseTest().expected().toString()); + } + + public HttpRequest deleteMessageMap = HttpRequest.builder() + .method("POST") + .endpoint("https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/") + .addHeader("Host", "sqs.us-east-1.amazonaws.com") + .addFormParam("Action", "DeleteMessageBatch") + .addFormParam("DeleteMessageBatchRequestEntry.1.Id", "foo1") + .addFormParam("DeleteMessageBatchRequestEntry.1.ReceiptHandle", "eXJYhj5rDr9cAe") + .addFormParam("DeleteMessageBatchRequestEntry.2.Id", "foo2") + .addFormParam("DeleteMessageBatchRequestEntry.2.ReceiptHandle", "fffeeerrr") + .addFormParam("Signature", "kwHC3F3ZoJvfibhZWVTeIwFHUzoaVMR4OViyJbsmuV0%3D") + .addFormParam("SignatureMethod", "HmacSHA256") + .addFormParam("SignatureVersion", "2") + .addFormParam("Timestamp", "2009-11-08T15%3A54%3A08.897Z") + .addFormParam("Version", "2011-10-01") + .addFormParam("AWSAccessKeyId", "identity").build(); + + public void testDeleteMessageMapWhenResponseIs2xx() throws Exception { + + HttpResponse deleteMessageResponse = HttpResponse.builder() + .statusCode(200) + .payload(payloadFromResourceWithContentType("/delete_message_batch.xml", "text/xml")).build(); + + SQSApi apiWhenExist = requestSendsResponse(deleteMessageMap, deleteMessageResponse); + + assertEquals( + apiWhenExist.getMessageApiForQueue(queue) + .delete(ImmutableMap.of("foo1", "eXJYhj5rDr9cAe", "foo2", "fffeeerrr")).toString(), + new DeleteMessageBatchResponseTest().expected().toString()); + } + + public HttpRequest changeMessageVisibility = HttpRequest.builder() + .method("POST") + .endpoint("https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/") + .addHeader("Host", "sqs.us-east-1.amazonaws.com") + .addFormParam("Action", "ChangeMessageVisibility") + .addFormParam("ReceiptHandle", "eXJYhj5rDr9cAe") + .addFormParam("Signature", "gvmSHleGLkmszYU6aURCBImuec2k0O3pg3tAYhDvkNs%3D") + .addFormParam("SignatureMethod", "HmacSHA256") + .addFormParam("SignatureVersion", "2") + .addFormParam("Timestamp", "2009-11-08T15%3A54%3A08.897Z") + .addFormParam("Version", "2011-10-01") + .addFormParam("VisibilityTimeout", "10") + .addFormParam("AWSAccessKeyId", "identity").build(); + + public void testChangeMessageVisibilityWhenResponseIs2xx() throws Exception { + + HttpResponse changeMessageVisibilityResponse = HttpResponse.builder() + .statusCode(200) + .payload( + payloadFromStringWithContentType( + "b5293cb5-d306-4a17-9048-b263635abe42", + "text/xml")).build(); + + SQSApi apiWhenExist = requestSendsResponse(changeMessageVisibility, changeMessageVisibilityResponse); + + apiWhenExist.getMessageApiForQueue(queue).changeVisibility("eXJYhj5rDr9cAe", 10); + } + + public HttpRequest changeMessageVisibilityTable = HttpRequest.builder() + .method("POST") + .endpoint("https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/") + .addHeader("Host", "sqs.us-east-1.amazonaws.com") + .addFormParam("Action", "ChangeMessageVisibilityBatch") + .addFormParam("ChangeMessageVisibilityBatchRequestEntry.1.Id", "foo1") + .addFormParam("ChangeMessageVisibilityBatchRequestEntry.1.ReceiptHandle", "aaaaaaaaa") + .addFormParam("ChangeMessageVisibilityBatchRequestEntry.1.VisibilityTimeout", "1") + .addFormParam("ChangeMessageVisibilityBatchRequestEntry.2.Id", "foo2") + .addFormParam("ChangeMessageVisibilityBatchRequestEntry.2.ReceiptHandle", "bbbbbbbbb") + .addFormParam("ChangeMessageVisibilityBatchRequestEntry.2.VisibilityTimeout", "10") + .addFormParam("Signature", "KjDusYiiC3hTdy3ZxLwBRHryrNoNaFb2AHJqUDu3mtQ%3D") + .addFormParam("SignatureMethod", "HmacSHA256") + .addFormParam("SignatureVersion", "2") + .addFormParam("Timestamp", "2009-11-08T15%3A54%3A08.897Z") + .addFormParam("Version", "2011-10-01") + .addFormParam("AWSAccessKeyId", "identity").build(); + + public void testChangeMessageVisibilityTableWhenResponseIs2xx() throws Exception { + + HttpResponse sendMessageResponse = HttpResponse.builder() + .statusCode(200) + .payload(payloadFromResourceWithContentType("/change_message_visibility_batch.xml", "text/xml")).build(); + + SQSApi apiWhenExist = requestSendsResponse(changeMessageVisibilityTable, sendMessageResponse); + + assertEquals(apiWhenExist.getMessageApiForQueue(queue).changeVisibility(ImmutableTable.builder() + .put("foo1", "aaaaaaaaa", 1) + .put("foo2", "bbbbbbbbb", 10) + .build()) + .toString(), new ChangeMessageVisibilityBatchResponseTest().expected().toString()); + } + + public HttpRequest changeMessageVisibilityMap = HttpRequest.builder() + .method("POST") + .endpoint("https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/") + .addHeader("Host", "sqs.us-east-1.amazonaws.com") + .addFormParam("Action", "ChangeMessageVisibilityBatch") + .addFormParam("ChangeMessageVisibilityBatchRequestEntry.1.Id", "1") + .addFormParam("ChangeMessageVisibilityBatchRequestEntry.1.ReceiptHandle", "aaaaaaaaa") + .addFormParam("ChangeMessageVisibilityBatchRequestEntry.1.VisibilityTimeout", "1") + .addFormParam("ChangeMessageVisibilityBatchRequestEntry.2.Id", "2") + .addFormParam("ChangeMessageVisibilityBatchRequestEntry.2.ReceiptHandle", "bbbbbbbbb") + .addFormParam("ChangeMessageVisibilityBatchRequestEntry.2.VisibilityTimeout", "10") + .addFormParam("Signature", "zj2cftkpHtiYb9iOjPR3AhcVhoobi0JvOy22PvQJtho%3D") + .addFormParam("SignatureMethod", "HmacSHA256") + .addFormParam("SignatureVersion", "2") + .addFormParam("Timestamp", "2009-11-08T15%3A54%3A08.897Z") + .addFormParam("Version", "2011-10-01") + .addFormParam("AWSAccessKeyId", "identity").build(); + + public void testChangeMessageVisibilityMapWhenResponseIs2xx() throws Exception { + + HttpResponse sendMessageResponse = HttpResponse.builder() + .statusCode(200) + .payload(payloadFromResourceWithContentType("/change_message_visibility_batch.xml", "text/xml")).build(); + + SQSApi apiWhenExist = requestSendsResponse(changeMessageVisibilityMap, sendMessageResponse); + + assertEquals( + apiWhenExist.getMessageApiForQueue(queue).changeVisibility(ImmutableMap.of("aaaaaaaaa", 1, "bbbbbbbbb", 10)) + .toString(), new ChangeMessageVisibilityBatchResponseTest().expected().toString()); + } + + public HttpRequest changeMessageVisibilityMapInt = HttpRequest.builder() + .method("POST") + .endpoint("https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/") + .addHeader("Host", "sqs.us-east-1.amazonaws.com") + .addFormParam("Action", "ChangeMessageVisibilityBatch") + .addFormParam("ChangeMessageVisibilityBatchRequestEntry.1.Id", "foo1") + .addFormParam("ChangeMessageVisibilityBatchRequestEntry.1.ReceiptHandle", "aaaaaaaaa") + .addFormParam("ChangeMessageVisibilityBatchRequestEntry.1.VisibilityTimeout", "10") + .addFormParam("ChangeMessageVisibilityBatchRequestEntry.2.Id", "foo2") + .addFormParam("ChangeMessageVisibilityBatchRequestEntry.2.ReceiptHandle", "bbbbbbbbb") + .addFormParam("ChangeMessageVisibilityBatchRequestEntry.2.VisibilityTimeout", "10") + .addFormParam("Signature", "y%2FgaaxoE5wrG2P7NIAyfDo7DTgRx2PLJUi9%2FzNnWQ6A%3D") + .addFormParam("SignatureMethod", "HmacSHA256") + .addFormParam("SignatureVersion", "2") + .addFormParam("Timestamp", "2009-11-08T15%3A54%3A08.897Z") + .addFormParam("Version", "2011-10-01") + .addFormParam("AWSAccessKeyId", "identity").build(); + + public void testChangeMessageVisibilityMapIntWhenResponseIs2xx() throws Exception { + + HttpResponse sendMessageResponse = HttpResponse.builder() + .statusCode(200) + .payload(payloadFromResourceWithContentType("/change_message_visibility_batch.xml", "text/xml")).build(); + + SQSApi apiWhenExist = requestSendsResponse(changeMessageVisibilityMapInt, sendMessageResponse); + + assertEquals(apiWhenExist.getMessageApiForQueue(queue).changeVisibility(ImmutableMap.builder() + .put("foo1", "aaaaaaaaa") + .put("foo2", "bbbbbbbbb") + .build(), 10) + .toString(), new ChangeMessageVisibilityBatchResponseTest().expected().toString()); + } + + public HttpRequest changeMessageVisibilityIterableInt = HttpRequest.builder() + .method("POST") + .endpoint("https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/") + .addHeader("Host", "sqs.us-east-1.amazonaws.com") + .addFormParam("Action", "ChangeMessageVisibilityBatch") + .addFormParam("ChangeMessageVisibilityBatchRequestEntry.1.Id", "1") + .addFormParam("ChangeMessageVisibilityBatchRequestEntry.1.ReceiptHandle", "aaaaaaaaa") + .addFormParam("ChangeMessageVisibilityBatchRequestEntry.1.VisibilityTimeout", "10") + .addFormParam("ChangeMessageVisibilityBatchRequestEntry.2.Id", "2") + .addFormParam("ChangeMessageVisibilityBatchRequestEntry.2.ReceiptHandle", "bbbbbbbbb") + .addFormParam("ChangeMessageVisibilityBatchRequestEntry.2.VisibilityTimeout", "10") + .addFormParam("Signature", "f5aq7zdKFErM3%2BIdtDX5NOzPO7mqCRzPGj2wUUEWjgE%3D") + .addFormParam("SignatureMethod", "HmacSHA256") + .addFormParam("SignatureVersion", "2") + .addFormParam("Timestamp", "2009-11-08T15%3A54%3A08.897Z") + .addFormParam("Version", "2011-10-01") + .addFormParam("AWSAccessKeyId", "identity").build(); + + public void testChangeMessageVisibilityIterableIntWhenResponseIs2xx() throws Exception { + + HttpResponse sendMessageResponse = HttpResponse.builder() + .statusCode(200) + .payload(payloadFromResourceWithContentType("/change_message_visibility_batch.xml", "text/xml")).build(); + + SQSApi apiWhenExist = requestSendsResponse(changeMessageVisibilityIterableInt, sendMessageResponse); + + assertEquals( + apiWhenExist.getMessageApiForQueue(queue).changeVisibility(ImmutableSet.of("aaaaaaaaa", "bbbbbbbbb"), 10) + .toString(), new ChangeMessageVisibilityBatchResponseTest().expected().toString()); + } +} diff --git a/apis/sqs/src/test/java/org/jclouds/sqs/features/MessageApiLiveTest.java b/apis/sqs/src/test/java/org/jclouds/sqs/features/MessageApiLiveTest.java new file mode 100644 index 0000000000..0e2a3ea77c --- /dev/null +++ b/apis/sqs/src/test/java/org/jclouds/sqs/features/MessageApiLiveTest.java @@ -0,0 +1,94 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.sqs.features; + +import static org.jclouds.sqs.options.ReceiveMessageOptions.Builder.attribute; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNull; + +import java.net.URI; + +import org.jclouds.sqs.internal.BaseSQSApiLiveTest; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import com.google.common.base.Charsets; +import com.google.common.hash.HashCode; +import com.google.common.hash.Hashing; + +/** + * + * @author Adrian Cole + */ +@Test(groups = "live", singleThreaded = true, testName = "MessageApiLiveTest") +public class MessageApiLiveTest extends BaseSQSApiLiveTest { + + public MessageApiLiveTest() { + prefix = prefix + "-message"; + } + + @BeforeClass(groups = { "integration", "live" }) + @Override + public void setupContext() { + super.setupContext(); + recreateQueueInRegion(prefix, null); + } + + String message = "hardyharhar"; + HashCode md5 = Hashing.md5().hashString(message, Charsets.UTF_8); + + public void testSendMessage() { + for (URI queue : queues) { + assertEquals(api().getMessageApiForQueue(queue).send(message).getMD5(), md5); + } + } + + @Test(dependsOnMethods = "testSendMessage") + public void testReceiveMessageWithoutHidingMessage() { + for (URI queue : queues) { + assertEquals(api().getMessageApiForQueue(queue).receive(attribute("All").visibilityTimeout(0)).getMD5(), md5); + } + } + + String receiptHandle; + + @Test(dependsOnMethods = "testReceiveMessageWithoutHidingMessage") + public void testChangeMessageVisibility() { + for (URI queue : queues) { + MessageApi api = api().getMessageApiForQueue(queue); + // start hiding it at 5 seconds + receiptHandle = api.receive(attribute("None").visibilityTimeout(5)).getReceiptHandle(); + // hidden message, so we can't see it + assertNull(api.receive()); + // this should unhide it + api.changeVisibility(receiptHandle, 0); + // so we can see it again + assertEquals(api.receive(attribute("All").visibilityTimeout(0)).getMD5(), md5); + } + } + + @Test(dependsOnMethods = "testChangeMessageVisibility") + public void testDeleteMessage() throws InterruptedException { + for (URI queue : queues) { + api().getMessageApiForQueue(queue).delete(receiptHandle); + assertNoMessages(queue); + } + } + +} diff --git a/apis/sqs/src/test/java/org/jclouds/sqs/features/PermissionApiExpectTest.java b/apis/sqs/src/test/java/org/jclouds/sqs/features/PermissionApiExpectTest.java new file mode 100644 index 0000000000..037de11b3a --- /dev/null +++ b/apis/sqs/src/test/java/org/jclouds/sqs/features/PermissionApiExpectTest.java @@ -0,0 +1,89 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.sqs.features; + +import org.jclouds.http.HttpRequest; +import org.jclouds.http.HttpResponse; +import org.jclouds.sqs.SQSApi; +import org.jclouds.sqs.domain.Action; +import org.jclouds.sqs.internal.BaseSQSApiExpectTest; +import org.testng.annotations.Test; + +/** + * @author Adrian Cole + */ +@Test(groups = "unit", testName = "PermissionApiExpectTest") +public class PermissionApiExpectTest extends BaseSQSApiExpectTest { + + public HttpRequest addPermission = HttpRequest.builder() + .method("POST") + .endpoint("https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/") + .addHeader("Host", "sqs.us-east-1.amazonaws.com") + .addFormParam("Action", "AddPermission") + .addFormParam("ActionName.1", "ReceiveMessage") + .addFormParam("AWSAccountId.1", "125074342641") + .addFormParam("Label", "testLabel") + .addFormParam("Signature", "J9sV4q1rJ7dWYJDQp9JxsfEKNXQhpQBYIwBYi1IeXV0%3D") + .addFormParam("SignatureMethod", "HmacSHA256") + .addFormParam("SignatureVersion", "2") + .addFormParam("Timestamp", "2009-11-08T15%3A54%3A08.897Z") + .addFormParam("Version", "2011-10-01") + .addFormParam("AWSAccessKeyId", "identity").build(); + + public void testAddPermissionWhenResponseIs2xx() throws Exception { + + HttpResponse addPermissionResponse = HttpResponse.builder() + .statusCode(200) + .payload( + payloadFromStringWithContentType( + "b5293cb5-d306-4a17-9048-b263635abe42", + "text/xml")).build(); + + SQSApi apiWhenExist = requestSendsResponse(addPermission, addPermissionResponse); + + apiWhenExist.getPermissionApiForQueue(queue).addPermissionToAccount("testLabel", Action.RECEIVE_MESSAGE, "125074342641"); + } + + public HttpRequest removePermission = HttpRequest.builder() + .method("POST") + .endpoint("https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/") + .addHeader("Host", "sqs.us-east-1.amazonaws.com") + .addFormParam("Action", "RemovePermission") + .addFormParam("Label", "testLabel") + .addFormParam("Signature", "VOA0L1uRVKQDQL1Klt0cYUajGoxN4Ur%2B7ISQ2I4RpRs%3D") + .addFormParam("SignatureMethod", "HmacSHA256") + .addFormParam("SignatureVersion", "2") + .addFormParam("Timestamp", "2009-11-08T15%3A54%3A08.897Z") + .addFormParam("Version", "2011-10-01") + .addFormParam("AWSAccessKeyId", "identity").build(); + + public void testRemovePermissionWhenResponseIs2xx() throws Exception { + + HttpResponse removePermissionResponse = HttpResponse.builder() + .statusCode(200) + .payload( + payloadFromStringWithContentType( + "b5293cb5-d306-4a17-9048-b263635abe42", + "text/xml")).build(); + + SQSApi apiWhenExist = requestSendsResponse(removePermission, removePermissionResponse); + + apiWhenExist.getPermissionApiForQueue(queue).remove("testLabel"); + } +} diff --git a/apis/sqs/src/test/java/org/jclouds/sqs/features/PermissionApiLiveTest.java b/apis/sqs/src/test/java/org/jclouds/sqs/features/PermissionApiLiveTest.java new file mode 100644 index 0000000000..07deb5f006 --- /dev/null +++ b/apis/sqs/src/test/java/org/jclouds/sqs/features/PermissionApiLiveTest.java @@ -0,0 +1,115 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.sqs.features; + +import static org.jclouds.concurrent.MoreExecutors.sameThreadExecutor; +import static org.jclouds.providers.AnonymousProviderMetadata.forClientMappedToAsyncClientOnEndpoint; +import static org.jclouds.sqs.reference.SQSParameters.ACTION; +import static org.testng.Assert.assertEquals; + +import java.net.URI; +import java.util.concurrent.TimeUnit; + +import javax.ws.rs.POST; +import javax.ws.rs.Path; + +import org.jclouds.ContextBuilder; +import org.jclouds.concurrent.Timeout; +import org.jclouds.concurrent.config.ExecutorServiceModule; +import org.jclouds.rest.annotations.FormParams; +import org.jclouds.rest.annotations.XMLResponseParser; +import org.jclouds.sqs.domain.Action; +import org.jclouds.sqs.domain.QueueAttributes; +import org.jclouds.sqs.internal.BaseSQSApiLiveTest; +import org.jclouds.sqs.xml.ValueHandler; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableSet; +import com.google.common.util.concurrent.ListenableFuture; +import com.google.inject.Module; + +/** + * + * + * @author Adrian Cole + */ +@Test(groups = "live", singleThreaded = true, testName = "PermissionApiLiveTest") +public class PermissionApiLiveTest extends BaseSQSApiLiveTest { + + public PermissionApiLiveTest() { + prefix = prefix + "-permission"; + } + + @BeforeClass(groups = { "integration", "live" }) + @Override + public void setupContext() { + super.setupContext(); + recreateQueueInRegion(prefix, null); + } + + @Timeout(duration = 5, timeUnit = TimeUnit.SECONDS) + static interface AnonymousAttributesApi { + String getQueueArn(); + } + + static interface AnonymousAttributesAsyncApi { + @POST + @Path("/") + @FormParams(keys = { ACTION, "AttributeName.1" }, values = { "GetQueueAttributes", "QueueArn" }) + @XMLResponseParser(ValueHandler.class) + ListenableFuture getQueueArn(); + } + + public void testAddAnonymousPermission() throws InterruptedException { + for (URI queue : queues) { + QueueAttributes attributes = api().getQueueApi().getAttributes(queue); + assertNoPermissions(queue); + + String accountToAuthorize = getOwner(queue); + api().getPermissionApiForQueue(queue).addPermissionToAccount("fubar", Action.GET_QUEUE_ATTRIBUTES, + accountToAuthorize); + + String policyForAuthorizationByAccount = assertPolicyPresent(queue); + + String policyForAnonymous = policyForAuthorizationByAccount.replace("\"" + accountToAuthorize + "\"", "\"*\""); + api().getQueueApi().setAttribute(queue, "Policy", policyForAnonymous); + + assertEquals(getAnonymousAttributesApi(queue).getQueueArn(), attributes.getQueueArn()); + } + } + + @Test(dependsOnMethods = "testAddAnonymousPermission") + public void testRemovePermission() throws InterruptedException { + for (URI queue : queues) { + api().getPermissionApiForQueue(queue).remove("fubar"); + assertNoPermissions(queue); + } + } + + private AnonymousAttributesApi getAnonymousAttributesApi(URI queue) { + return ContextBuilder + .newBuilder( + forClientMappedToAsyncClientOnEndpoint(AnonymousAttributesApi.class, + AnonymousAttributesAsyncApi.class, queue.toASCIIString())) + .modules(ImmutableSet. of(new ExecutorServiceModule(sameThreadExecutor(), sameThreadExecutor()))) + .buildInjector().getInstance(AnonymousAttributesApi.class); + } + +} diff --git a/apis/sqs/src/test/java/org/jclouds/sqs/features/QueueApiExpectTest.java b/apis/sqs/src/test/java/org/jclouds/sqs/features/QueueApiExpectTest.java new file mode 100644 index 0000000000..c17691ce9a --- /dev/null +++ b/apis/sqs/src/test/java/org/jclouds/sqs/features/QueueApiExpectTest.java @@ -0,0 +1,237 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.sqs.features; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNull; + +import java.net.URI; + +import org.jclouds.http.HttpRequest; +import org.jclouds.http.HttpResponse; +import org.jclouds.sqs.SQSApi; +import org.jclouds.sqs.functions.MapToQueueAttributesTest; +import org.jclouds.sqs.internal.BaseSQSApiExpectTest; +import org.jclouds.sqs.parse.CreateQueueResponseTest; +import org.jclouds.sqs.parse.GetQueueAttributesResponseTest; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableSet; + +/** + * @author Adrian Cole + */ +@Test(groups = "unit", testName = "QueueApiExpectTest") +public class QueueApiExpectTest extends BaseSQSApiExpectTest { + public HttpRequest getQueueUrl = HttpRequest.builder() + .method("POST") + .endpoint("https://sqs.us-east-1.amazonaws.com/") + .addHeader("Host", "sqs.us-east-1.amazonaws.com") + .addFormParam("Action", "GetQueueUrl") + .addFormParam("QueueName", "queueName") + .addFormParam("Signature", "ZjHLpNl6NLqK%2BsqOyEFqEJMWGeOLuNBd3%2B0Z9RGPYWU%3D") + .addFormParam("SignatureMethod", "HmacSHA256") + .addFormParam("SignatureVersion", "2") + .addFormParam("Timestamp", "2009-11-08T15%3A54%3A08.897Z") + .addFormParam("Version", "2011-10-01") + .addFormParam("AWSAccessKeyId", "identity").build(); + + public void testGetQueueUrlWhenResponseIs2xx() throws Exception { + + HttpResponse getQueueUrlResponse = HttpResponse.builder() + .statusCode(200) + .payload(payloadFromResourceWithContentType("/get_queue_url.xml", "text/xml")).build(); + + + SQSApi apiWhenExist = requestSendsResponse(getQueueUrl, getQueueUrlResponse); + + assertEquals(apiWhenExist.getQueueApi().get("queueName"), URI.create("http://sqs.us-east-1.amazonaws.com/123456789012/testQueue")); + } + + public HttpRequest getQueueUrlByOwner = HttpRequest.builder() + .method("POST") + .endpoint("https://sqs.us-east-1.amazonaws.com/") + .addHeader("Host", "sqs.us-east-1.amazonaws.com") + .addFormParam("Action", "GetQueueUrl") + .addFormParam("QueueName", "queueName") + .addFormParam("QueueOwnerAWSAccountId", "120908098979") + .addFormParam("Signature", "O0E%2B3jh2vN6bKqmb4%2FXPTHUmPO1iat9o8YnIFH463g8%3D") + .addFormParam("SignatureMethod", "HmacSHA256") + .addFormParam("SignatureVersion", "2") + .addFormParam("Timestamp", "2009-11-08T15%3A54%3A08.897Z") + .addFormParam("Version", "2011-10-01") + .addFormParam("AWSAccessKeyId", "identity").build(); + + public void testGetQueueUrlByOwnerWhenResponseIs2xx() throws Exception { + + HttpResponse getQueueUrlResponse = HttpResponse.builder() + .statusCode(200) + .payload(payloadFromResourceWithContentType("/get_queue_url.xml", "text/xml")).build(); + + + SQSApi apiWhenExist = requestSendsResponse(getQueueUrlByOwner, getQueueUrlResponse); + + assertEquals(apiWhenExist.getQueueApi().getInAccount("queueName", "120908098979"), URI.create("http://sqs.us-east-1.amazonaws.com/123456789012/testQueue")); + } + + // when the queue doesn't exist, or you don't have access to it + public void testGetQueueUrlByOwnerWhenResponseIs400ReturnsNull() throws Exception { + + HttpResponse getQueueUrlResponse = HttpResponse.builder() + .statusCode(400) + .payload( + payloadFromStringWithContentType( + "SenderAWS.SimpleQueueService.NonExistentQueueThe specified queue does not exist or you do not have access to it.194a169f-4483-5bb1-8cb6-5e4ac865909a", + "text/xml")).build(); + + SQSApi apiWhenExist = requestSendsResponse(getQueueUrlByOwner, getQueueUrlResponse); + + assertNull(apiWhenExist.getQueueApi().getInAccount("queueName", "120908098979")); + } + + public HttpRequest createQueue = HttpRequest.builder() + .method("POST") + .endpoint("https://sqs.us-east-1.amazonaws.com/") + .addHeader("Host", "sqs.us-east-1.amazonaws.com") + .addFormParam("Action", "CreateQueue") + .addFormParam("QueueName", "queueName") + .addFormParam("Signature", "I7tmwiCzJ9cvw79pmlz1rOILh2C2ZV6OpLk23JGx6AU%3D") + .addFormParam("SignatureMethod", "HmacSHA256") + .addFormParam("SignatureVersion", "2") + .addFormParam("Timestamp", "2009-11-08T15%3A54%3A08.897Z") + .addFormParam("Version", "2011-10-01") + .addFormParam("AWSAccessKeyId", "identity").build(); + + public void testCreateQueueWhenResponseIs2xx() throws Exception { + + HttpResponse createQueueResponse = HttpResponse.builder().statusCode(200) + .payload(payloadFromResourceWithContentType("/create_queue.xml", "text/xml")).build(); + + SQSApi apiWhenExist = requestSendsResponse(createQueue, createQueueResponse); + + assertEquals(apiWhenExist.getQueueApi().create("queueName").toString(), new CreateQueueResponseTest().expected() + .toString()); + } + + public HttpRequest getQueueAttribute = HttpRequest.builder() + .method("POST") + .endpoint("https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/") + .addHeader("Host", "sqs.us-east-1.amazonaws.com") + .addFormParam("Action", "GetQueueAttributes") + .addFormParam("AttributeName.1", "VisibilityTimeout") + .addFormParam("Signature", "AfydayBBaIk4UGikHHY1CFNmOOAcTnogpFWydZyNass%3D") + .addFormParam("SignatureMethod", "HmacSHA256") + .addFormParam("SignatureVersion", "2") + .addFormParam("Timestamp", "2009-11-08T15%3A54%3A08.897Z") + .addFormParam("Version", "2011-10-01") + .addFormParam("AWSAccessKeyId", "identity").build(); + + public void testGetQueueAttributeWhenResponseIs2xx() throws Exception { + + HttpResponse getQueueAttributeResponse = HttpResponse.builder() + .statusCode(200) + .payload( + payloadFromStringWithContentType( + "VisibilityTimeout30", + "text/xml")).build(); + + SQSApi apiWhenExist = requestSendsResponse(getQueueAttribute, getQueueAttributeResponse); + + assertEquals(apiWhenExist.getQueueApi().getAttribute(queue, "VisibilityTimeout"), "30"); + } + + public HttpRequest getQueueAttributes = HttpRequest.builder() + .method("POST") + .endpoint("https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/") + .addHeader("Host", "sqs.us-east-1.amazonaws.com") + .addFormParam("Action", "GetQueueAttributes") + .addFormParam("AttributeName.1", "All") + .addFormParam("Signature", "welFLn0TV6JlH6s6s60XZTJeJfFXGiXN4qNPrBx7aHc%3D") + .addFormParam("SignatureMethod", "HmacSHA256") + .addFormParam("SignatureVersion", "2") + .addFormParam("Timestamp", "2009-11-08T15%3A54%3A08.897Z") + .addFormParam("Version", "2011-10-01") + .addFormParam("AWSAccessKeyId", "identity").build(); + + public void testGetQueueAttributesWhenResponseIs2xx() throws Exception { + + HttpResponse getQueueAttributesResponse = HttpResponse.builder().statusCode(200) + .payload(payloadFromResourceWithContentType("/attributes.xml", "text/xml")).build(); + + SQSApi apiWhenExist = requestSendsResponse(getQueueAttributes, getQueueAttributesResponse); + + assertEquals(apiWhenExist.getQueueApi().getAttributes(queue).toString(), new MapToQueueAttributesTest() + .expected().toString()); + } + + public HttpRequest getQueueAttributesSubset = HttpRequest.builder() + .method("POST") + .endpoint("https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/") + .addHeader("Host", "sqs.us-east-1.amazonaws.com") + .addFormParam("Action", "GetQueueAttributes") + .addFormParam("AttributeName.1", "VisibilityTimeout") + .addFormParam("AttributeName.2", "DelaySeconds") + .addFormParam("Signature", "9KaiOOWWyFPTVMOnyHA3ZoXbPBPSD4AZ4q460UNMfDs%3D") + .addFormParam("SignatureMethod", "HmacSHA256") + .addFormParam("SignatureVersion", "2") + .addFormParam("Timestamp", "2009-11-08T15%3A54%3A08.897Z") + .addFormParam("Version", "2011-10-01") + .addFormParam("AWSAccessKeyId", "identity").build(); + + public void testGetQueueAttributesSubsetWhenResponseIs2xx() throws Exception { + + HttpResponse getQueueAttributesSubsetResponse = HttpResponse.builder().statusCode(200) + .payload(payloadFromResourceWithContentType("/attributes.xml", "text/xml")).build(); + + SQSApi apiWhenExist = requestSendsResponse(getQueueAttributesSubset, getQueueAttributesSubsetResponse); + + assertEquals(apiWhenExist.getQueueApi() + .getAttributes(queue, ImmutableSet.of("VisibilityTimeout", "DelaySeconds")).toString(), + new GetQueueAttributesResponseTest().expected().toString()); + } + + public HttpRequest setQueueAttribute = HttpRequest.builder() + .method("POST") + .endpoint("https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/") + .addHeader("Host", "sqs.us-east-1.amazonaws.com") + .addFormParam("Action", "SetQueueAttributes") + .addFormParam("Attribute.Name", "MaximumMessageSize") + .addFormParam("Attribute.Value", "1") + .addFormParam("Signature", "ktBkQ3c%2FrwGcBSec0fkckfo73xmcoTuub5fxudM1qh0%3D") + .addFormParam("SignatureMethod", "HmacSHA256") + .addFormParam("SignatureVersion", "2") + .addFormParam("Timestamp", "2009-11-08T15%3A54%3A08.897Z") + .addFormParam("Version", "2011-10-01") + .addFormParam("AWSAccessKeyId", "identity").build(); + + public void testSetQueueAttributeWhenResponseIs2xx() throws Exception { + + HttpResponse setQueueAttributeResponse = HttpResponse.builder() + .statusCode(200) + .payload( + payloadFromStringWithContentType( + "b5293cb5-d306-4a17-9048-b263635abe42", + "text/xml")).build(); + + SQSApi apiWhenExist = requestSendsResponse(setQueueAttribute, setQueueAttributeResponse); + + apiWhenExist.getQueueApi().setAttribute(queue, "MaximumMessageSize", "1"); + } + +} diff --git a/apis/sqs/src/test/java/org/jclouds/sqs/features/QueueApiLiveTest.java b/apis/sqs/src/test/java/org/jclouds/sqs/features/QueueApiLiveTest.java new file mode 100644 index 0000000000..0d98c06c2a --- /dev/null +++ b/apis/sqs/src/test/java/org/jclouds/sqs/features/QueueApiLiveTest.java @@ -0,0 +1,108 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.sqs.features; + +import static com.google.common.collect.Iterables.getLast; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; + +import java.net.URI; +import java.util.Map; +import java.util.UUID; + +import org.jclouds.sqs.internal.BaseSQSApiLiveTest; +import org.testng.annotations.Test; + +import com.google.common.collect.FluentIterable; +import com.google.common.collect.ImmutableSet; + +/** + * + * @author Adrian Cole + */ +@Test(groups = "live", singleThreaded = true, testName = "QueueApiLiveTest") +public class QueueApiLiveTest extends BaseSQSApiLiveTest { + + public QueueApiLiveTest() { + prefix = prefix + "-queue"; + } + + @Test + public void testListQueues() throws InterruptedException { + listQueuesInRegion(null); + } + + protected void listQueuesInRegion(String region) throws InterruptedException { + FluentIterable allResults = api().getQueueApiForRegion(region).list(); + assertNotNull(allResults); + if (allResults.size() >= 1) { + URI queue = getLast(allResults); + assertQueueInList(region, queue); + } + } + + @Test + public void testGracefulNoQueue() throws InterruptedException { + assertNull(api().getQueueApi().get(UUID.randomUUID().toString())); + } + + @Test + public void testCanRecreateQueueGracefully() throws InterruptedException { + recreateQueueInRegion(prefix, null); + recreateQueueInRegion(prefix, null); + } + + @Test(dependsOnMethods = "testCanRecreateQueueGracefully") + public void testCreateQueueWhenAlreadyExistsReturnsURI() { + for (URI queue : queues) { + assertEquals(api().getQueueApi().create(prefix), queue); + } + } + + @Test(dependsOnMethods = "testCanRecreateQueueGracefully") + public void testGet() { + for (URI queue : queues) { + assertEquals(api().getQueueApi().get(prefix), queue); + } + } + + @Test(dependsOnMethods = "testCanRecreateQueueGracefully") + public void testGetInAccount() { + for (URI queue : queues) { + assertEquals(api().getQueueApi().getInAccount(prefix, getOwner(queue)), queue); + } + } + + @Test(dependsOnMethods = "testCanRecreateQueueGracefully") + public void testGetQueueAttributes() { + for (URI queue : queues) { + Map attributes = api().getQueueApi().getAttributes(queue, ImmutableSet.of("All")); + assertEquals(api().getQueueApi().getAttributes(queue, attributes.keySet()), attributes); + } + } + + @Test(dependsOnMethods = "testGetQueueAttributes") + public void testSetQueueAttribute() { + for (URI queue : queues) { + api().getQueueApi().setAttribute(queue, "MaximumMessageSize", "1024"); + assertEquals(api().getQueueApi().getAttributes(queue).getMaximumMessageSize(), 1024); + } + } +} diff --git a/apis/sqs/src/test/java/org/jclouds/sqs/functions/MapToQueueAttributesTest.java b/apis/sqs/src/test/java/org/jclouds/sqs/functions/MapToQueueAttributesTest.java new file mode 100644 index 0000000000..203a5b78f1 --- /dev/null +++ b/apis/sqs/src/test/java/org/jclouds/sqs/functions/MapToQueueAttributesTest.java @@ -0,0 +1,64 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.sqs.functions; + +import static org.testng.Assert.assertEquals; + +import java.util.Date; + +import org.jclouds.sqs.domain.QueueAttributes; +import org.jclouds.sqs.parse.GetQueueAttributesResponseTest; +import org.testng.annotations.Test; + +/** + * @author Adrian Cole + */ +// NOTE:without testName, this will not call @Before* and fail w/NPE during +// surefire +@Test(groups = "unit", testName = "MapToQueueAttributesTest") +public class MapToQueueAttributesTest { + + public void test() { + + + QueueAttributes expected = expected(); + + MapToQueueAttributes fn = new MapToQueueAttributes(); + + QueueAttributes result = fn.apply(new GetQueueAttributesResponseTest().expected()); + + assertEquals(result.toString(), expected.toString()); + + } + + public QueueAttributes expected() { + return QueueAttributes.builder() + .queueArn("arn:aws:sqs:us-east-1:993194456877:adrian-sqs1") + .approximateNumberOfMessages(0) + .approximateNumberOfMessagesNotVisible(0) + .approximateNumberOfMessagesDelayed(0) + .createdTimestamp(new Date(1347566436l)) + .lastModifiedTimestamp(new Date(1347566436)) + .visibilityTimeout(30) + .maximumMessageSize(65536) + .messageRetentionPeriod(345600) + .delaySeconds(0) + .build(); + } +} diff --git a/apis/sqs/src/test/java/org/jclouds/sqs/handlers/SQSErrorRetryHandlerTest.java b/apis/sqs/src/test/java/org/jclouds/sqs/handlers/SQSErrorRetryHandlerTest.java new file mode 100644 index 0000000000..d9de520019 --- /dev/null +++ b/apis/sqs/src/test/java/org/jclouds/sqs/handlers/SQSErrorRetryHandlerTest.java @@ -0,0 +1,138 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.sqs.handlers; + +import static org.easymock.EasyMock.createMock; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertTrue; + +import java.util.concurrent.TimeUnit; + +import org.jclouds.aws.domain.AWSError; +import org.jclouds.aws.util.AWSUtils; +import org.jclouds.http.HttpCommand; +import org.jclouds.http.HttpRequest; +import org.jclouds.http.HttpResponse; +import org.jclouds.http.handlers.BackoffLimitedRetryHandler; +import org.testng.annotations.Test; + +import com.google.common.base.Stopwatch; +import com.google.common.collect.ImmutableSet; + +/** + * Tests behavior of {@code SQSErrorRetryHandler} + * + * @author Adrian Cole + */ +@Test(groups = "unit", testName = "SQSErrorRetryHandlerTest") +public class SQSErrorRetryHandlerTest { + + String code = "AWS.SimpleQueueService.QueueDeletedRecently"; + AWSError error; + HttpResponse response = HttpResponse.builder().statusCode(400) + .payload(String.format("%s", code)).build(); + + public SQSErrorRetryHandlerTest() { + error = new AWSError(); + error.setCode(code); + } + + public void testQueueDeletedRecentlyRetriesWhen59SleepsAndTries() { + + SQSErrorRetryHandler retry = new SQSErrorRetryHandler(createMock(AWSUtils.class), + createMock(BackoffLimitedRetryHandler.class), ImmutableSet. of(), 60, 100); + + HttpCommand command = createHttpCommandForFailureCount(59); + + Stopwatch watch = new Stopwatch().start(); + assertTrue(retry.shouldRetryRequestOnError(command, response, error)); + assertEquals(command.getFailureCount(), 60); + // allow for slightly inaccurate system timers + assertTrue(watch.stop().elapsedTime(TimeUnit.MILLISECONDS) >= 98); + } + + + + public void testQueueDeletedRecentlyRetriesWhen60DoesntTry() { + + SQSErrorRetryHandler retry = new SQSErrorRetryHandler(createMock(AWSUtils.class), + createMock(BackoffLimitedRetryHandler.class), ImmutableSet. of(), 60, 100); + + HttpCommand command = createHttpCommandForFailureCount(60); + + Stopwatch watch = new Stopwatch().start(); + assertFalse(retry.shouldRetryRequestOnError(command, response, error)); + assertEquals(command.getFailureCount(), 61); + assertTrue(watch.stop().elapsedTime(TimeUnit.MILLISECONDS) < 100); + } + + //TODO: make a builder for this + HttpCommand createHttpCommandForFailureCount(final int failureCount) { + return new HttpCommand() { + int fCount = failureCount; + + @Override + public int incrementRedirectCount() { + return 0; + } + + @Override + public int getRedirectCount() { + return 0; + } + + @Override + public boolean isReplayable() { + return false; + } + + @Override + public int incrementFailureCount() { + return ++fCount; + } + + @Override + public int getFailureCount() { + return fCount; + } + + @Override + public HttpRequest getCurrentRequest() { + return null; + } + + @Override + public void setCurrentRequest(HttpRequest request) { + + } + + @Override + public void setException(Exception exception) { + } + + @Override + public Exception getException() { + return null; + } + }; + } + + +} diff --git a/labs/sqs/src/test/java/org/jclouds/sqs/internal/BaseSQSApiExpectTest.java b/apis/sqs/src/test/java/org/jclouds/sqs/internal/BaseSQSApiExpectTest.java similarity index 100% rename from labs/sqs/src/test/java/org/jclouds/sqs/internal/BaseSQSApiExpectTest.java rename to apis/sqs/src/test/java/org/jclouds/sqs/internal/BaseSQSApiExpectTest.java diff --git a/apis/sqs/src/test/java/org/jclouds/sqs/internal/BaseSQSApiLiveTest.java b/apis/sqs/src/test/java/org/jclouds/sqs/internal/BaseSQSApiLiveTest.java new file mode 100644 index 0000000000..1ebe3b622a --- /dev/null +++ b/apis/sqs/src/test/java/org/jclouds/sqs/internal/BaseSQSApiLiveTest.java @@ -0,0 +1,165 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.sqs.internal; + +import static com.google.common.collect.Iterables.get; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertTrue; + +import java.net.URI; +import java.util.Set; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; + +import org.jclouds.apis.BaseContextLiveTest; +import org.jclouds.rest.RestContext; +import org.jclouds.sqs.SQSApi; +import org.jclouds.sqs.SQSApiMetadata; +import org.jclouds.sqs.SQSAsyncApi; +import org.jclouds.sqs.domain.Message; +import org.jclouds.sqs.features.QueueApi; +import org.testng.annotations.AfterClass; +import org.testng.annotations.Test; + +import com.google.common.base.Splitter; +import com.google.common.collect.FluentIterable; +import com.google.common.collect.Sets; +import com.google.common.reflect.TypeToken; +import com.google.common.util.concurrent.Uninterruptibles; + +/** + * + * @author Adrian Cole + */ +@Test(groups = "live") +public class BaseSQSApiLiveTest extends BaseContextLiveTest> { + + protected String prefix = System.getProperty("user.name") + "-sqs"; + + public BaseSQSApiLiveTest() { + provider = "sqs"; + } + + protected Set queues = Sets.newHashSet(); + + protected String getOwner(URI queue) { + return get(Splitter.on('/').split(queue.getPath()), 1); + } + + protected String recreateQueueInRegion(String queueName, String region) { + QueueApi api = api().getQueueApiForRegion(region); + URI result = api.get(queueName); + if (result != null) { + api.delete(result); + } + URI queue = api.create(queueName); + assertQueueInList(region, queue); + queues.add(queue); + return queueName; + } + + @Override + protected TypeToken> contextType() { + return SQSApiMetadata.CONTEXT_TOKEN; + } + + protected String assertPolicyPresent(final URI queue) { + final AtomicReference policy = new AtomicReference(); + assertEventually(new Runnable() { + public void run() { + String policyForAuthorizationByAccount = api().getQueueApi().getAttribute(queue, "Policy"); + + assertNotNull(policyForAuthorizationByAccount); + policy.set(policyForAuthorizationByAccount); + } + }); + return policy.get(); + } + + protected void assertNoPermissions(final URI queue) { + assertEventually(new Runnable() { + public void run() { + String policy = api().getQueueApi().getAttribute(queue, "Policy"); + assertTrue(policy == null || policy.indexOf("\"Statement\":[]") != -1, policy); + } + }); + } + + protected void assertNoMessages(final URI queue) { + assertEventually(new Runnable() { + public void run() { + Message message = api().getMessageApiForQueue(queue).receive(); + assertNull(message, "message: " + message + " left in queue " + queue); + } + }); + } + + protected void assertQueueInList(final String region, URI queue) { + final URI finalQ = queue; + assertEventually(new Runnable() { + public void run() { + FluentIterable result = api().getQueueApiForRegion(region).list(); + assertNotNull(result); + assert result.size() >= 1 : result; + assertTrue(result.contains(finalQ), finalQ + " not in " + result); + } + }); + } + + private static final int INCONSISTENCY_WINDOW = 10000; + + /** + * Due to eventual consistency, container commands may not return correctly + * immediately. Hence, we will try up to the inconsistency window to see if + * the assertion completes. + */ + protected static void assertEventually(Runnable assertion) { + long start = System.currentTimeMillis(); + AssertionError error = null; + for (int i = 0; i < 30; i++) { + try { + assertion.run(); + if (i > 0) + System.err.printf("%d attempts and %dms asserting %s%n", i + 1, System.currentTimeMillis() - start, + assertion.getClass().getSimpleName()); + return; + } catch (AssertionError e) { + error = e; + } + Uninterruptibles.sleepUninterruptibly(INCONSISTENCY_WINDOW / 30, TimeUnit.MILLISECONDS); + } + if (error != null) + throw error; + } + + @Override + @AfterClass(groups = "live") + protected void tearDownContext() { + for (URI queue : queues) { + api().getQueueApi().delete(queue); + } + super.tearDownContext(); + } + + protected SQSApi api() { + return context.getApi(); + } + +} diff --git a/labs/sqs/src/test/java/org/jclouds/sqs/internal/BaseSQSExpectTest.java b/apis/sqs/src/test/java/org/jclouds/sqs/internal/BaseSQSExpectTest.java similarity index 92% rename from labs/sqs/src/test/java/org/jclouds/sqs/internal/BaseSQSExpectTest.java rename to apis/sqs/src/test/java/org/jclouds/sqs/internal/BaseSQSExpectTest.java index 6896a1ad65..082cb1d2b4 100644 --- a/labs/sqs/src/test/java/org/jclouds/sqs/internal/BaseSQSExpectTest.java +++ b/apis/sqs/src/test/java/org/jclouds/sqs/internal/BaseSQSExpectTest.java @@ -18,6 +18,8 @@ */ package org.jclouds.sqs.internal; +import java.net.URI; + import org.jclouds.date.DateService; import org.jclouds.rest.ConfiguresRestClient; import org.jclouds.rest.internal.BaseRestApiExpectTest; @@ -30,6 +32,7 @@ import com.google.inject.Module; * @author Adrian Cole */ public class BaseSQSExpectTest extends BaseRestApiExpectTest { + protected URI queue = URI.create("https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/"); public BaseSQSExpectTest() { provider = "sqs"; diff --git a/labs/sqs/src/test/java/org/jclouds/sqs/options/CreateQueueOptionsTest.java b/apis/sqs/src/test/java/org/jclouds/sqs/options/CreateQueueOptionsTest.java similarity index 100% rename from labs/sqs/src/test/java/org/jclouds/sqs/options/CreateQueueOptionsTest.java rename to apis/sqs/src/test/java/org/jclouds/sqs/options/CreateQueueOptionsTest.java diff --git a/labs/sqs/src/test/java/org/jclouds/sqs/options/ListQueuesOptionsTest.java b/apis/sqs/src/test/java/org/jclouds/sqs/options/ListQueuesOptionsTest.java similarity index 91% rename from labs/sqs/src/test/java/org/jclouds/sqs/options/ListQueuesOptionsTest.java rename to apis/sqs/src/test/java/org/jclouds/sqs/options/ListQueuesOptionsTest.java index d8c6149059..dfe9cdb791 100644 --- a/labs/sqs/src/test/java/org/jclouds/sqs/options/ListQueuesOptionsTest.java +++ b/apis/sqs/src/test/java/org/jclouds/sqs/options/ListQueuesOptionsTest.java @@ -21,7 +21,7 @@ package org.jclouds.sqs.options; import static org.jclouds.sqs.options.ListQueuesOptions.Builder.queuePrefix; import static org.testng.Assert.assertEquals; -import java.util.Collections; +import com.google.common.collect.ImmutableList; import org.jclouds.http.options.HttpRequestOptions; import org.testng.annotations.Test; @@ -43,21 +43,19 @@ public class ListQueuesOptionsTest { public void testPrefix() { ListQueuesOptions options = new ListQueuesOptions(); options.queuePrefix("test"); - assertEquals(options.buildFormParameters().get("QueueNamePrefix"), Collections - .singletonList("test")); + assertEquals(options.buildFormParameters().get("QueueNamePrefix"), ImmutableList.of("test")); } @Test public void testNullPrefix() { ListQueuesOptions options = new ListQueuesOptions(); - assertEquals(options.buildFormParameters().get("QueueNamePrefix"), Collections.EMPTY_LIST); + assertEquals(options.buildFormParameters().get("QueueNamePrefix"), ImmutableList.of()); } @Test public void testPrefixStatic() { ListQueuesOptions options = queuePrefix("test"); - assertEquals(options.buildFormParameters().get("QueueNamePrefix"), Collections - .singletonList("test")); + assertEquals(options.buildFormParameters().get("QueueNamePrefix"), ImmutableList.of("test")); } public void testNoPrefix() { diff --git a/labs/sqs/src/test/java/org/jclouds/sqs/options/ReceiveMessageOptionsTest.java b/apis/sqs/src/test/java/org/jclouds/sqs/options/ReceiveMessageOptionsTest.java similarity index 100% rename from labs/sqs/src/test/java/org/jclouds/sqs/options/ReceiveMessageOptionsTest.java rename to apis/sqs/src/test/java/org/jclouds/sqs/options/ReceiveMessageOptionsTest.java diff --git a/labs/sqs/src/test/java/org/jclouds/sqs/options/SendMessageOptionsTest.java b/apis/sqs/src/test/java/org/jclouds/sqs/options/SendMessageOptionsTest.java similarity index 100% rename from labs/sqs/src/test/java/org/jclouds/sqs/options/SendMessageOptionsTest.java rename to apis/sqs/src/test/java/org/jclouds/sqs/options/SendMessageOptionsTest.java diff --git a/apis/sqs/src/test/java/org/jclouds/sqs/parse/ChangeMessageVisibilityBatchResponseTest.java b/apis/sqs/src/test/java/org/jclouds/sqs/parse/ChangeMessageVisibilityBatchResponseTest.java new file mode 100644 index 0000000000..4e40613310 --- /dev/null +++ b/apis/sqs/src/test/java/org/jclouds/sqs/parse/ChangeMessageVisibilityBatchResponseTest.java @@ -0,0 +1,56 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.sqs.parse; + +import static org.testng.Assert.assertEquals; + +import java.io.InputStream; + +import org.jclouds.http.functions.BaseHandlerTest; +import org.jclouds.sqs.domain.BatchResult; +import org.jclouds.sqs.xml.ChangeMessageVisibilityBatchResponseHandler; +import org.testng.annotations.Test; + +/** + * @author Adrian Cole + */ +// NOTE:without testName, this will not call @Before* and fail w/NPE during +// surefire +@Test(groups = "unit", testName = "ChangeMessageVisibilityBatchResponseTest") +public class ChangeMessageVisibilityBatchResponseTest extends BaseHandlerTest { + + public void test() { + InputStream is = getClass().getResourceAsStream("/change_message_visibility_batch.xml"); + + BatchResult expected = expected(); + + ChangeMessageVisibilityBatchResponseHandler handler = injector.getInstance(ChangeMessageVisibilityBatchResponseHandler.class); + BatchResult result = factory.create(handler).parse(is); + + assertEquals(result.toString(), expected.toString()); + + } + + public BatchResult expected() { + return BatchResult. builder() + .put("change_visibility_msg_2","change_visibility_msg_2") + .put("change_visibility_msg_3","change_visibility_msg_3") + .build(); + } +} diff --git a/apis/sqs/src/test/java/org/jclouds/sqs/parse/CreateQueueResponseTest.java b/apis/sqs/src/test/java/org/jclouds/sqs/parse/CreateQueueResponseTest.java new file mode 100644 index 0000000000..f3d92264ca --- /dev/null +++ b/apis/sqs/src/test/java/org/jclouds/sqs/parse/CreateQueueResponseTest.java @@ -0,0 +1,54 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.sqs.parse; + +import static org.testng.Assert.assertEquals; + +import java.io.InputStream; +import java.net.URI; + +import org.jclouds.http.HttpResponse; +import org.jclouds.http.functions.ReturnStringIf2xx; +import org.jclouds.sqs.xml.RegexQueueHandler; +import org.testng.annotations.Test; + +/** + * @author Adrian Cole + */ +// NOTE:without testName, this will not call @Before* and fail w/NPE during +// surefire +@Test(groups = "unit", testName = "CreateQueueResponseTest") +public class CreateQueueResponseTest { + + public void test() { + InputStream is = getClass().getResourceAsStream("/create_queue.xml"); + + URI expected = expected(); + + RegexQueueHandler handler = new RegexQueueHandler(new ReturnStringIf2xx()); + URI result = handler.apply(HttpResponse.builder().statusCode(200).payload(is).build()); + + assertEquals(result.toString(), expected.toString()); + + } + + public URI expected() { + return URI.create("https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11"); + } +} diff --git a/apis/sqs/src/test/java/org/jclouds/sqs/parse/DeleteMessageBatchResponseTest.java b/apis/sqs/src/test/java/org/jclouds/sqs/parse/DeleteMessageBatchResponseTest.java new file mode 100644 index 0000000000..c7e4ce47c5 --- /dev/null +++ b/apis/sqs/src/test/java/org/jclouds/sqs/parse/DeleteMessageBatchResponseTest.java @@ -0,0 +1,56 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.sqs.parse; + +import static org.testng.Assert.assertEquals; + +import java.io.InputStream; + +import org.jclouds.http.functions.BaseHandlerTest; +import org.jclouds.sqs.domain.BatchResult; +import org.jclouds.sqs.xml.DeleteMessageBatchResponseHandler; +import org.testng.annotations.Test; + +/** + * @author Adrian Cole + */ +// NOTE:without testName, this will not call @Before* and fail w/NPE during +// surefire +@Test(groups = "unit", testName = "DeleteMessageBatchResponseTest") +public class DeleteMessageBatchResponseTest extends BaseHandlerTest { + + public void test() { + InputStream is = getClass().getResourceAsStream("/delete_message_batch.xml"); + + BatchResult expected = expected(); + + DeleteMessageBatchResponseHandler handler = injector.getInstance(DeleteMessageBatchResponseHandler.class); + BatchResult result = factory.create(handler).parse(is); + + assertEquals(result.toString(), expected.toString()); + + } + + public BatchResult expected() { + return BatchResult. builder() + .put("msg1","msg1") + .put("msg2","msg2") + .build(); + } +} diff --git a/apis/sqs/src/test/java/org/jclouds/sqs/parse/GetQueueAttributesResponseTest.java b/apis/sqs/src/test/java/org/jclouds/sqs/parse/GetQueueAttributesResponseTest.java new file mode 100644 index 0000000000..143d293e6d --- /dev/null +++ b/apis/sqs/src/test/java/org/jclouds/sqs/parse/GetQueueAttributesResponseTest.java @@ -0,0 +1,66 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.sqs.parse; + +import static org.testng.Assert.assertEquals; + +import java.io.InputStream; +import java.util.Map; + +import org.jclouds.http.functions.BaseHandlerTest; +import org.jclouds.sqs.xml.AttributesHandler; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableMap; + +/** + * @author Adrian Cole + */ +// NOTE:without testName, this will not call @Before* and fail w/NPE during +// surefire +@Test(groups = "unit", testName = "GetQueueAttributesResponseTest") +public class GetQueueAttributesResponseTest extends BaseHandlerTest { + + public void test() { + InputStream is = getClass().getResourceAsStream("/attributes.xml"); + + Map expected = expected(); + + AttributesHandler handler = injector.getInstance(AttributesHandler.class); + Map result = factory.create(handler).parse(is); + + assertEquals(result.toString(), expected.toString()); + + } + + public Map expected() { + return ImmutableMap.builder() + .put("QueueArn", "arn:aws:sqs:us-east-1:993194456877:adrian-sqs1") + .put("ApproximateNumberOfMessages", "0") + .put("ApproximateNumberOfMessagesNotVisible", "0") + .put("ApproximateNumberOfMessagesDelayed", "0") + .put("CreatedTimestamp", "1347566436") + .put("LastModifiedTimestamp", "1347566436") + .put("VisibilityTimeout","30") + .put("MaximumMessageSize", "65536") + .put("MessageRetentionPeriod", "345600") + .put("DelaySeconds", "0") + .build(); + } +} diff --git a/labs/sqs/src/test/java/org/jclouds/sqs/parse/ReceiveMessageResponseTest.java b/apis/sqs/src/test/java/org/jclouds/sqs/parse/ReceiveMessageResponseTest.java similarity index 76% rename from labs/sqs/src/test/java/org/jclouds/sqs/parse/ReceiveMessageResponseTest.java rename to apis/sqs/src/test/java/org/jclouds/sqs/parse/ReceiveMessageResponseTest.java index c06baba868..0afa837bf1 100644 --- a/labs/sqs/src/test/java/org/jclouds/sqs/parse/ReceiveMessageResponseTest.java +++ b/apis/sqs/src/test/java/org/jclouds/sqs/parse/ReceiveMessageResponseTest.java @@ -21,7 +21,6 @@ package org.jclouds.sqs.parse; import static org.testng.Assert.assertEquals; import java.io.InputStream; -import java.util.Set; import org.jclouds.crypto.CryptoStreams; import org.jclouds.http.functions.BaseHandlerTest; @@ -29,7 +28,8 @@ import org.jclouds.sqs.domain.Message; import org.jclouds.sqs.xml.ReceiveMessageResponseHandler; import org.testng.annotations.Test; -import com.google.common.collect.ImmutableSet; +import com.google.common.collect.FluentIterable; +import com.google.common.collect.ImmutableList; import com.google.common.hash.HashCodes; /** @@ -43,28 +43,26 @@ public class ReceiveMessageResponseTest extends BaseHandlerTest { public void test() { InputStream is = getClass().getResourceAsStream("/messages.xml"); - Set expected = expected(); + FluentIterable expected = expected(); ReceiveMessageResponseHandler handler = injector.getInstance(ReceiveMessageResponseHandler.class); - Set result = factory.create(handler).parse(is); + FluentIterable result = factory.create(handler).parse(is); assertEquals(result.toString(), expected.toString()); } - public Set expected() { - return ImmutableSet.of(Message + public FluentIterable expected() { + return FluentIterable.from(ImmutableList.of(Message .builder() .id("5fea7756-0ea4-451a-a703-a558b933e274") .receiptHandle( - "MbZj6wDWli+JvwwJaBV+3dcjk2YW2vA3+STFFljTM8tJJg6HRG6PYSasuWXPJB+Cw" + "\n" - + " Lj1FjgXUv1uSj1gUPAWV66FU/WeR4mq2OKpEGYWbnLmpRCJVAyeMjeU5ZBdtcQ+QE" + "\n" - + " auMZc8ZRv37sIW2iJKq3M9MFx1YvV11A2x/KSbkJ0=") + "+eXJYhj5rDr9cAe/9BuheT5fysi9BoqtEZSkO7IazVbNHg60eCCINxLqaSVv2pFHrWeWNpZwbleSkWRbCtZaQGgpOx/3cWJZiNSG1KKlJX4IOwISFvb3FwByMx4w0lnINeXzcw2VcKQXNrCatO9gdIiVPvJC3SCKatYM/7YTidtjqc8igrtYW2E2mHlCy3NXPCeXxP4tSvyEwIxpDAmMT7IF0mWvTHS6+JBUtFUsrmi61oIHlESNrD1OjdB1QQw+kdvJ6VbsntbJNNYKw+YqdqWNpZkiGQ8y1z9OdHsr1+4=") .md5(HashCodes.fromBytes(CryptoStreams.hex("fafb00f5732ab283681e124bf8747ed1"))) .body("This is a test message") .addAttribute("SenderId", "195004372649") .addAttribute("SentTimestamp", "1238099229000") .addAttribute("ApproximateReceiveCount", "5") - .addAttribute("ApproximateFirstReceiveTimestamp", "1250700979248").build()); + .addAttribute("ApproximateFirstReceiveTimestamp", "1250700979248").build())); } } diff --git a/apis/sqs/src/test/java/org/jclouds/sqs/parse/SendMessageBatchResponseTest.java b/apis/sqs/src/test/java/org/jclouds/sqs/parse/SendMessageBatchResponseTest.java new file mode 100644 index 0000000000..fcafc10c10 --- /dev/null +++ b/apis/sqs/src/test/java/org/jclouds/sqs/parse/SendMessageBatchResponseTest.java @@ -0,0 +1,65 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.sqs.parse; + +import static org.testng.Assert.assertEquals; + +import java.io.InputStream; + +import org.jclouds.crypto.CryptoStreams; +import org.jclouds.http.functions.BaseHandlerTest; +import org.jclouds.sqs.domain.BatchResult; +import org.jclouds.sqs.domain.MessageIdAndMD5; +import org.jclouds.sqs.xml.SendMessageBatchResponseHandler; +import org.testng.annotations.Test; + +import com.google.common.hash.HashCodes; + +/** + * @author Adrian Cole + */ +// NOTE:without testName, this will not call @Before* and fail w/NPE during +// surefire +@Test(groups = "unit", testName = "SendMessageBatchResponseTest") +public class SendMessageBatchResponseTest extends BaseHandlerTest { + + public void test() { + InputStream is = getClass().getResourceAsStream("/send_message_batch.xml"); + + BatchResult expected = expected(); + + SendMessageBatchResponseHandler handler = injector.getInstance(SendMessageBatchResponseHandler.class); + BatchResult result = factory.create(handler).parse(is); + + assertEquals(result.toString(), expected.toString()); + + } + + public BatchResult expected() { + return BatchResult + . builder() + .put("test_msg_001", + MessageIdAndMD5.builder().id("0a5231c7-8bff-4955-be2e-8dc7c50a25fa") + .md5(HashCodes.fromBytes(CryptoStreams.hex("0e024d309850c78cba5eabbeff7cae71"))).build()) + .put("test_msg_002", + MessageIdAndMD5.builder().id("15ee1ed3-87e7-40c1-bdaa-2e49968ea7e9") + .md5(HashCodes.fromBytes(CryptoStreams.hex("7fb8146a82f95e0af155278f406862c2"))).build()) + .build(); + } +} diff --git a/labs/sqs/src/test/java/org/jclouds/sqs/parse/SendMessageResponseTest.java b/apis/sqs/src/test/java/org/jclouds/sqs/parse/SendMessageResponseTest.java similarity index 91% rename from labs/sqs/src/test/java/org/jclouds/sqs/parse/SendMessageResponseTest.java rename to apis/sqs/src/test/java/org/jclouds/sqs/parse/SendMessageResponseTest.java index 1ede1dc154..c49c5d294f 100644 --- a/labs/sqs/src/test/java/org/jclouds/sqs/parse/SendMessageResponseTest.java +++ b/apis/sqs/src/test/java/org/jclouds/sqs/parse/SendMessageResponseTest.java @@ -44,17 +44,15 @@ public class SendMessageResponseTest { MessageIdAndMD5 expected = expected(); - RegexMessageIdAndMD5Handler handler = new RegexMessageIdAndMD5Handler( new ReturnStringIf2xx ()); + RegexMessageIdAndMD5Handler handler = new RegexMessageIdAndMD5Handler(new ReturnStringIf2xx()); MessageIdAndMD5 result = handler.apply(HttpResponse.builder().statusCode(200).payload(is).build()); assertEquals(result.toString(), expected.toString()); } - + public MessageIdAndMD5 expected() { - return MessageIdAndMD5.builder() - .id("c332b2b0-b61f-42d3-8832-d03ebd89f68d") - .md5(HashCodes.fromBytes(CryptoStreams.hex("e32aedf2b2b25355d04b1507055532e6"))) - .build(); + return MessageIdAndMD5.builder().id("c332b2b0-b61f-42d3-8832-d03ebd89f68d") + .md5(HashCodes.fromBytes(CryptoStreams.hex("e32aedf2b2b25355d04b1507055532e6"))).build(); } } diff --git a/apis/sqs/src/test/resources/attributes.xml b/apis/sqs/src/test/resources/attributes.xml new file mode 100644 index 0000000000..726c246b7f --- /dev/null +++ b/apis/sqs/src/test/resources/attributes.xml @@ -0,0 +1,48 @@ + + + + + QueueArn + arn:aws:sqs:us-east-1:993194456877:adrian-sqs1 + + + ApproximateNumberOfMessages + 0 + + + ApproximateNumberOfMessagesNotVisible + 0 + + + ApproximateNumberOfMessagesDelayed + 0 + + + CreatedTimestamp + 1347566436 + + + LastModifiedTimestamp + 1347566436 + + + VisibilityTimeout + 30 + + + MaximumMessageSize + 65536 + + + MessageRetentionPeriod + 345600 + + + DelaySeconds + 0 + + + + 35566a87-caa1-5841-b60b-224bf7068bf5 + + \ No newline at end of file diff --git a/apis/sqs/src/test/resources/change_message_visibility_batch.xml b/apis/sqs/src/test/resources/change_message_visibility_batch.xml new file mode 100644 index 0000000000..bfc4707d34 --- /dev/null +++ b/apis/sqs/src/test/resources/change_message_visibility_batch.xml @@ -0,0 +1,13 @@ + + + + change_visibility_msg_2 + + + change_visibility_msg_3 + + + + ca9668f7-ab1b-4f7a-8859-f15747ab17a7 + + \ No newline at end of file diff --git a/labs/sqs/src/test/resources/create_queue.xml b/apis/sqs/src/test/resources/create_queue.xml similarity index 100% rename from labs/sqs/src/test/resources/create_queue.xml rename to apis/sqs/src/test/resources/create_queue.xml diff --git a/apis/sqs/src/test/resources/delete_message_batch.xml b/apis/sqs/src/test/resources/delete_message_batch.xml new file mode 100644 index 0000000000..aeaefa7f5e --- /dev/null +++ b/apis/sqs/src/test/resources/delete_message_batch.xml @@ -0,0 +1,13 @@ + + + + msg1 + + + msg2 + + + + d6f86b7a-74d1-4439-b43f-196a1e29cd85 + + \ No newline at end of file diff --git a/apis/sqs/src/test/resources/get_queue_url.xml b/apis/sqs/src/test/resources/get_queue_url.xml new file mode 100644 index 0000000000..8e26510f57 --- /dev/null +++ b/apis/sqs/src/test/resources/get_queue_url.xml @@ -0,0 +1,8 @@ + + + http://sqs.us-east-1.amazonaws.com/123456789012/testQueue + + + 470a6f13-2ed9-4181-ad8a-2fdea142988e + + \ No newline at end of file diff --git a/labs/sqs/src/test/resources/list_queues.xml b/apis/sqs/src/test/resources/list_queues.xml similarity index 100% rename from labs/sqs/src/test/resources/list_queues.xml rename to apis/sqs/src/test/resources/list_queues.xml diff --git a/labs/sqs/src/test/resources/log4j.xml b/apis/sqs/src/test/resources/log4j.xml similarity index 100% rename from labs/sqs/src/test/resources/log4j.xml rename to apis/sqs/src/test/resources/log4j.xml diff --git a/labs/sqs/src/test/resources/messages.xml b/apis/sqs/src/test/resources/messages.xml similarity index 72% rename from labs/sqs/src/test/resources/messages.xml rename to apis/sqs/src/test/resources/messages.xml index 496b15980b..fd3224156d 100644 --- a/labs/sqs/src/test/resources/messages.xml +++ b/apis/sqs/src/test/resources/messages.xml @@ -4,11 +4,7 @@ 5fea7756-0ea4-451a-a703-a558b933e274 - - MbZj6wDWli+JvwwJaBV+3dcjk2YW2vA3+STFFljTM8tJJg6HRG6PYSasuWXPJB+Cw - Lj1FjgXUv1uSj1gUPAWV66FU/WeR4mq2OKpEGYWbnLmpRCJVAyeMjeU5ZBdtcQ+QE - auMZc8ZRv37sIW2iJKq3M9MFx1YvV11A2x/KSbkJ0= - + +eXJYhj5rDr9cAe/9BuheT5fysi9BoqtEZSkO7IazVbNHg60eCCINxLqaSVv2pFHrWeWNpZwbleSkWRbCtZaQGgpOx/3cWJZiNSG1KKlJX4IOwISFvb3FwByMx4w0lnINeXzcw2VcKQXNrCatO9gdIiVPvJC3SCKatYM/7YTidtjqc8igrtYW2E2mHlCy3NXPCeXxP4tSvyEwIxpDAmMT7IF0mWvTHS6+JBUtFUsrmi61oIHlESNrD1OjdB1QQw+kdvJ6VbsntbJNNYKw+YqdqWNpZkiGQ8y1z9OdHsr1+4= fafb00f5732ab283681e124bf8747ed1 diff --git a/labs/sqs/src/test/resources/send_message.xml b/apis/sqs/src/test/resources/send_message.xml similarity index 100% rename from labs/sqs/src/test/resources/send_message.xml rename to apis/sqs/src/test/resources/send_message.xml diff --git a/apis/sqs/src/test/resources/send_message_batch.xml b/apis/sqs/src/test/resources/send_message_batch.xml new file mode 100644 index 0000000000..5761d08ea9 --- /dev/null +++ b/apis/sqs/src/test/resources/send_message_batch.xml @@ -0,0 +1,17 @@ + + + + test_msg_001 + 0a5231c7-8bff-4955-be2e-8dc7c50a25fa + 0e024d309850c78cba5eabbeff7cae71 + + + test_msg_002 + 15ee1ed3-87e7-40c1-bdaa-2e49968ea7e9 + 7fb8146a82f95e0af155278f406862c2 + + + + ca1ad5d0-8271-408b-8d0f-1351bf547e74 + + \ No newline at end of file diff --git a/apis/swift/pom.xml b/apis/swift/pom.xml index 5b3cd146fc..f9cc4dacab 100644 --- a/apis/swift/pom.xml +++ b/apis/swift/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.api diff --git a/apis/swift/src/main/java/org/jclouds/openstack/swift/CommonSwiftAsyncClient.java b/apis/swift/src/main/java/org/jclouds/openstack/swift/CommonSwiftAsyncClient.java index b7a9b9fa8c..b31a92c1c2 100644 --- a/apis/swift/src/main/java/org/jclouds/openstack/swift/CommonSwiftAsyncClient.java +++ b/apis/swift/src/main/java/org/jclouds/openstack/swift/CommonSwiftAsyncClient.java @@ -248,5 +248,4 @@ public interface CommonSwiftAsyncClient { @Headers(keys = "X-Object-Manifest", values="{container}/{name}") ListenableFuture putObjectManifest(@PathParam("container") String container, @PathParam("name") String name); - } diff --git a/apis/swift/src/main/java/org/jclouds/openstack/swift/SwiftApiMetadata.java b/apis/swift/src/main/java/org/jclouds/openstack/swift/SwiftApiMetadata.java index 34fa5479de..ca59b003d9 100644 --- a/apis/swift/src/main/java/org/jclouds/openstack/swift/SwiftApiMetadata.java +++ b/apis/swift/src/main/java/org/jclouds/openstack/swift/SwiftApiMetadata.java @@ -27,6 +27,7 @@ import java.util.Properties; import org.jclouds.apis.ApiMetadata; import org.jclouds.blobstore.BlobStoreContext; import org.jclouds.openstack.swift.blobstore.config.SwiftBlobStoreContextModule; +import org.jclouds.openstack.swift.blobstore.config.TemporaryUrlExtensionModule.SwiftTemporaryUrlExtensionModule; import org.jclouds.openstack.swift.config.SwiftRestClientModule; import org.jclouds.openstack.swift.config.SwiftRestClientModule.StorageEndpointModule; import org.jclouds.rest.RestContext; @@ -38,13 +39,13 @@ import com.google.inject.Module; /** * Implementation of {@link ApiMetadata} for OpenStack Swift - * + * * @author Adrian Cole */ public class SwiftApiMetadata extends BaseRestApiMetadata { /** The serialVersionUID */ private static final long serialVersionUID = 6725672099385580694L; - + public static final TypeToken> CONTEXT_TOKEN = new TypeToken>() { private static final long serialVersionUID = -5070937833892503232L; }; @@ -81,7 +82,11 @@ public class SwiftApiMetadata extends BaseRestApiMetadata { .defaultProperties(SwiftApiMetadata.defaultProperties()) .view(TypeToken.of(BlobStoreContext.class)) .context(CONTEXT_TOKEN) - .defaultModules(ImmutableSet.>of(StorageEndpointModule.class, SwiftRestClientModule.class, SwiftBlobStoreContextModule.class)); + .defaultModules(ImmutableSet.>builder() + .add(StorageEndpointModule.class) + .add(SwiftRestClientModule.class) + .add(SwiftBlobStoreContextModule.class) + .add(SwiftTemporaryUrlExtensionModule.class).build()); } @Override diff --git a/apis/swift/src/main/java/org/jclouds/openstack/swift/SwiftKeystoneApiMetadata.java b/apis/swift/src/main/java/org/jclouds/openstack/swift/SwiftKeystoneApiMetadata.java index ba6f4c6ffc..f205b02298 100644 --- a/apis/swift/src/main/java/org/jclouds/openstack/swift/SwiftKeystoneApiMetadata.java +++ b/apis/swift/src/main/java/org/jclouds/openstack/swift/SwiftKeystoneApiMetadata.java @@ -29,6 +29,7 @@ import org.jclouds.openstack.keystone.v2_0.config.CredentialTypes; import org.jclouds.openstack.keystone.v2_0.config.KeystoneAuthenticationModule; import org.jclouds.openstack.services.ServiceType; import org.jclouds.openstack.swift.blobstore.config.SwiftBlobStoreContextModule; +import org.jclouds.openstack.swift.blobstore.config.TemporaryUrlExtensionModule.SwiftKeystoneTemporaryUrlExtensionModule; import org.jclouds.openstack.swift.config.SwiftKeystoneRestClientModule; import org.jclouds.openstack.swift.config.SwiftRestClientModule.KeystoneStorageEndpointModule; import org.jclouds.rest.RestContext; @@ -46,7 +47,7 @@ public class SwiftKeystoneApiMetadata extends SwiftApiMetadata { /** The serialVersionUID */ private static final long serialVersionUID = 820062881469203616L; - + public static final TypeToken> CONTEXT_TOKEN = new TypeToken>() { private static final long serialVersionUID = -5070937833892503232L; }; @@ -91,8 +92,12 @@ public class SwiftKeystoneApiMetadata extends SwiftApiMetadata { .defaultEndpoint("http://localhost:5000/v2.0/") .context(CONTEXT_TOKEN) .defaultProperties(SwiftKeystoneApiMetadata.defaultProperties()) - .defaultModules(ImmutableSet.>of(KeystoneStorageEndpointModule.class, KeystoneAuthenticationModule.RegionModule.class, - SwiftKeystoneRestClientModule.class, SwiftBlobStoreContextModule.class)); + .defaultModules(ImmutableSet.>builder() + .add(KeystoneStorageEndpointModule.class) + .add(KeystoneAuthenticationModule.RegionModule.class) + .add(SwiftKeystoneRestClientModule.class) + .add(SwiftBlobStoreContextModule.class) + .add(SwiftKeystoneTemporaryUrlExtensionModule.class).build()); } @Override diff --git a/apis/cloudfiles/src/main/java/org/jclouds/cloudfiles/TemporaryUrlKey.java b/apis/swift/src/main/java/org/jclouds/openstack/swift/TemporaryUrlKey.java similarity index 97% rename from apis/cloudfiles/src/main/java/org/jclouds/cloudfiles/TemporaryUrlKey.java rename to apis/swift/src/main/java/org/jclouds/openstack/swift/TemporaryUrlKey.java index 15b7d43e1c..7cb011bd74 100644 --- a/apis/cloudfiles/src/main/java/org/jclouds/cloudfiles/TemporaryUrlKey.java +++ b/apis/swift/src/main/java/org/jclouds/openstack/swift/TemporaryUrlKey.java @@ -16,7 +16,7 @@ * specific language governing permissions and limitations * under the License. */ -package org.jclouds.cloudfiles; +package org.jclouds.openstack.swift; import javax.inject.Qualifier; import java.lang.annotation.ElementType; diff --git a/apis/swift/src/main/java/org/jclouds/openstack/swift/blobstore/SwiftBlobRequestSigner.java b/apis/swift/src/main/java/org/jclouds/openstack/swift/blobstore/SwiftBlobRequestSigner.java deleted file mode 100644 index d3986f8e7e..0000000000 --- a/apis/swift/src/main/java/org/jclouds/openstack/swift/blobstore/SwiftBlobRequestSigner.java +++ /dev/null @@ -1,98 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.openstack.swift.blobstore; - -import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.blobstore.util.BlobStoreUtils.cleanRequest; - -import java.lang.reflect.Method; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import org.jclouds.blobstore.BlobRequestSigner; -import org.jclouds.blobstore.domain.Blob; -import org.jclouds.blobstore.functions.BlobToHttpGetOptions; -import org.jclouds.http.HttpRequest; -import org.jclouds.http.options.GetOptions; -import org.jclouds.openstack.swift.CommonSwiftAsyncClient; -import org.jclouds.openstack.swift.blobstore.functions.BlobToObject; -import org.jclouds.openstack.swift.domain.SwiftObject; -import org.jclouds.rest.internal.RestAnnotationProcessor; - -/** - * - * @author Adrian Cole - */ -@Singleton -public class SwiftBlobRequestSigner implements BlobRequestSigner { - - private final RestAnnotationProcessor processor; - - private final BlobToObject blobToObject; - private final BlobToHttpGetOptions blob2HttpGetOptions; - - private final Method getMethod; - private final Method deleteMethod; - private final Method createMethod; - - @Inject - public SwiftBlobRequestSigner(RestAnnotationProcessor processor, BlobToObject blobToObject, - BlobToHttpGetOptions blob2HttpGetOptions) throws SecurityException, NoSuchMethodException { - this.processor = checkNotNull(processor, "processor"); - - this.blobToObject = checkNotNull(blobToObject, "blobToObject"); - this.blob2HttpGetOptions = checkNotNull(blob2HttpGetOptions, "blob2HttpGetOptions"); - - this.getMethod = CommonSwiftAsyncClient.class.getMethod("getObject", String.class, String.class, - GetOptions[].class); - this.deleteMethod = CommonSwiftAsyncClient.class.getMethod("removeObject", String.class, String.class); - this.createMethod = CommonSwiftAsyncClient.class.getMethod("putObject", String.class, SwiftObject.class); - } - - @Override - public HttpRequest signGetBlob(String container, String name) { - return cleanRequest(processor.createRequest(getMethod, container, name)); - } - - @Override - public HttpRequest signGetBlob(String container, String name, long timeInSeconds) { - throw new UnsupportedOperationException(); - } - - @Override - public HttpRequest signPutBlob(String container, Blob blob) { - return cleanRequest(processor.createRequest(createMethod, container, blobToObject.apply(blob))); - } - - @Override - public HttpRequest signPutBlob(String container, Blob blob, long timeInSeconds) { - throw new UnsupportedOperationException(); - } - - @Override - public HttpRequest signRemoveBlob(String container, String name) { - return cleanRequest(processor.createRequest(deleteMethod, container, name)); - } - - @Override - public HttpRequest signGetBlob(String container, String name, org.jclouds.blobstore.options.GetOptions options) { - return cleanRequest(processor.createRequest(getMethod, container, name, blob2HttpGetOptions.apply(options))); - } -} diff --git a/apis/cloudfiles/src/main/java/org/jclouds/cloudfiles/blobstore/CloudFilesBlobRequestSigner.java b/apis/swift/src/main/java/org/jclouds/openstack/swift/blobstore/SwiftBlobSigner.java similarity index 57% rename from apis/cloudfiles/src/main/java/org/jclouds/cloudfiles/blobstore/CloudFilesBlobRequestSigner.java rename to apis/swift/src/main/java/org/jclouds/openstack/swift/blobstore/SwiftBlobSigner.java index b6b9d7136a..688527ce8d 100644 --- a/apis/cloudfiles/src/main/java/org/jclouds/cloudfiles/blobstore/CloudFilesBlobRequestSigner.java +++ b/apis/swift/src/main/java/org/jclouds/openstack/swift/blobstore/SwiftBlobSigner.java @@ -1,39 +1,64 @@ -package org.jclouds.cloudfiles.blobstore; +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.swift.blobstore; + +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; +import static org.jclouds.blobstore.util.BlobStoreUtils.cleanRequest; + +import java.lang.reflect.Method; +import java.security.InvalidKeyException; + +import javax.inject.Inject; +import javax.inject.Singleton; -import com.google.common.base.Throwables; -import com.google.inject.Provider; import org.jclouds.blobstore.BlobRequestSigner; import org.jclouds.blobstore.domain.Blob; import org.jclouds.blobstore.functions.BlobToHttpGetOptions; -import org.jclouds.cloudfiles.CloudFilesAsyncClient; -import org.jclouds.cloudfiles.TemporaryUrlKey; import org.jclouds.crypto.Crypto; import org.jclouds.crypto.CryptoStreams; import org.jclouds.date.TimeStamp; import org.jclouds.http.HttpRequest; +import org.jclouds.http.HttpRequestFilter; import org.jclouds.http.options.GetOptions; -import org.jclouds.openstack.keystone.v2_0.filters.AuthenticateRequest; +import org.jclouds.openstack.swift.CommonSwiftAsyncClient; +import org.jclouds.openstack.swift.TemporaryUrlKey; import org.jclouds.openstack.swift.blobstore.functions.BlobToObject; import org.jclouds.openstack.swift.domain.SwiftObject; import org.jclouds.rest.internal.RestAnnotationProcessor; -import javax.inject.Inject; -import java.lang.reflect.Method; -import java.security.InvalidKeyException; +import com.google.common.base.Supplier; +import com.google.common.base.Throwables; +import com.google.common.collect.ImmutableSet; +import com.google.inject.Provider; -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Predicates.instanceOf; -import static com.google.common.collect.Iterables.filter; -import static org.jclouds.blobstore.util.BlobStoreUtils.cleanRequest; +/** + * @author Adrian Cole + */ +@Singleton +public class SwiftBlobSigner implements BlobRequestSigner { -public class CloudFilesBlobRequestSigner implements BlobRequestSigner { - - private final RestAnnotationProcessor processor; + private final RestAnnotationProcessor processor; private final Crypto crypto; private final Provider unixEpochTimestampProvider; - private final Provider temporaryUrlKeyProvider; + private final Supplier temporaryUrlKeySupplier; private final BlobToObject blobToObject; private final BlobToHttpGetOptions blob2HttpGetOptions; @@ -42,23 +67,30 @@ public class CloudFilesBlobRequestSigner implements BlobRequestSigner { private final Method deleteMethod; private final Method createMethod; + /** + * create a signer for this subtype of swift + * + * @param processor + * bound to the current subclass of {@link CommonSwiftAsyncClient} + */ @Inject - public CloudFilesBlobRequestSigner(RestAnnotationProcessor processor, BlobToObject blobToObject, - BlobToHttpGetOptions blob2HttpGetOptions, Crypto crypto, - @TimeStamp Provider unixEpochTimestampProvider, - @TemporaryUrlKey Provider temporaryUrlKeyProvider) throws SecurityException, NoSuchMethodException { + protected SwiftBlobSigner(BlobToObject blobToObject, BlobToHttpGetOptions blob2HttpGetOptions, Crypto crypto, + @TimeStamp Provider unixEpochTimestampProvider, + @TemporaryUrlKey Supplier temporaryUrlKeySupplier, + RestAnnotationProcessor processor) + throws SecurityException, NoSuchMethodException { this.processor = checkNotNull(processor, "processor"); this.crypto = checkNotNull(crypto, "crypto"); this.unixEpochTimestampProvider = checkNotNull(unixEpochTimestampProvider, "unixEpochTimestampProvider"); - this.temporaryUrlKeyProvider = checkNotNull(temporaryUrlKeyProvider, "temporaryUrlKeyProvider"); + this.temporaryUrlKeySupplier = checkNotNull(temporaryUrlKeySupplier, "temporaryUrlKeyProvider"); this.blobToObject = checkNotNull(blobToObject, "blobToObject"); this.blob2HttpGetOptions = checkNotNull(blob2HttpGetOptions, "blob2HttpGetOptions"); - this.getMethod = CloudFilesAsyncClient.class.getMethod("getObject", String.class, String.class, GetOptions[].class); - this.deleteMethod = CloudFilesAsyncClient.class.getMethod("removeObject", String.class, String.class); - this.createMethod = CloudFilesAsyncClient.class.getMethod("putObject", String.class, SwiftObject.class); + this.getMethod = processor.getDeclaring().getMethod("getObject", String.class, String.class, GetOptions[].class); + this.deleteMethod = processor.getDeclaring().getMethod("removeObject", String.class, String.class); + this.createMethod = processor.getDeclaring().getMethod("putObject", String.class, SwiftObject.class); } @Override @@ -66,17 +98,17 @@ public class CloudFilesBlobRequestSigner implements BlobRequestSigner { return cleanRequest(processor.createRequest(getMethod, container, name)); } - @Override - public HttpRequest signGetBlob(String container, String name, org.jclouds.blobstore.options.GetOptions options) { - return cleanRequest(processor.createRequest(getMethod, container, name, blob2HttpGetOptions.apply(options))); - } - @Override public HttpRequest signGetBlob(String container, String name, long timeInSeconds) { HttpRequest request = processor.createRequest(getMethod, container, name); return cleanRequest(signForTemporaryAccess(request, timeInSeconds)); } + @Override + public HttpRequest signGetBlob(String container, String name, org.jclouds.blobstore.options.GetOptions options) { + return cleanRequest(processor.createRequest(getMethod, container, name, blob2HttpGetOptions.apply(options))); + } + @Override public HttpRequest signPutBlob(String container, Blob blob) { return cleanRequest(processor.createRequest(createMethod, container, blobToObject.apply(blob))); @@ -94,14 +126,16 @@ public class CloudFilesBlobRequestSigner implements BlobRequestSigner { } private HttpRequest signForTemporaryAccess(HttpRequest request, long timeInSeconds) { - HttpRequest.Builder builder = request.toBuilder(); - builder.filters(filter(request.getFilters(), instanceOf(AuthenticateRequest.class))); + HttpRequest.Builder builder = request.toBuilder().filters(ImmutableSet.of()); - String key = temporaryUrlKeyProvider.get(); + String key = temporaryUrlKeySupplier.get(); + if (key == null) { + throw new UnsupportedOperationException(); + } long expiresInSeconds = unixEpochTimestampProvider.get() + timeInSeconds; - builder.addQueryParam("temp_url_sig", createSignature(key, createStringToSign( - request.getMethod().toUpperCase(), request, expiresInSeconds))); + builder.addQueryParam("temp_url_sig", + createSignature(key, createStringToSign(request.getMethod().toUpperCase(), request, expiresInSeconds))); builder.addQueryParam("temp_url_expires", "" + expiresInSeconds); return builder.build(); @@ -109,14 +143,12 @@ public class CloudFilesBlobRequestSigner implements BlobRequestSigner { private String createStringToSign(String method, HttpRequest request, long expiresInSeconds) { checkArgument(method.equalsIgnoreCase("GET") || method.equalsIgnoreCase("PUT")); - return String.format("%s\n%d\n%s", method.toUpperCase(), expiresInSeconds, - request.getEndpoint().getPath()); + return String.format("%s\n%d\n%s", method.toUpperCase(), expiresInSeconds, request.getEndpoint().getPath()); } private String createSignature(String key, String stringToSign) { try { return CryptoStreams.hex(crypto.hmacSHA1(key.getBytes()).doFinal(stringToSign.getBytes())); - } catch (InvalidKeyException e) { throw Throwables.propagate(e); } diff --git a/apis/swift/src/main/java/org/jclouds/openstack/swift/blobstore/config/SwiftBlobStoreContextModule.java b/apis/swift/src/main/java/org/jclouds/openstack/swift/blobstore/config/SwiftBlobStoreContextModule.java index 6b60d81071..051cc8c882 100644 --- a/apis/swift/src/main/java/org/jclouds/openstack/swift/blobstore/config/SwiftBlobStoreContextModule.java +++ b/apis/swift/src/main/java/org/jclouds/openstack/swift/blobstore/config/SwiftBlobStoreContextModule.java @@ -18,21 +18,20 @@ */ package org.jclouds.openstack.swift.blobstore.config; + import org.jclouds.blobstore.AsyncBlobStore; -import org.jclouds.blobstore.BlobRequestSigner; import org.jclouds.blobstore.BlobStore; import org.jclouds.blobstore.attr.ConsistencyModel; import org.jclouds.blobstore.config.BlobStoreMapModule; import org.jclouds.openstack.swift.blobstore.SwiftAsyncBlobStore; -import org.jclouds.openstack.swift.blobstore.SwiftBlobRequestSigner; import org.jclouds.openstack.swift.blobstore.SwiftBlobStore; import com.google.inject.AbstractModule; import com.google.inject.Scopes; /** - * Configures the {@link CloudFilesBlobStoreContext}; requires {@link SwiftAsyncBlobStore} - * bound. + * Configures the {@link CloudFilesBlobStoreContext}; requires + * {@link SwiftAsyncBlobStore} bound. * * @author Adrian Cole */ @@ -44,10 +43,5 @@ public class SwiftBlobStoreContextModule extends AbstractModule { bind(ConsistencyModel.class).toInstance(ConsistencyModel.STRICT); bind(AsyncBlobStore.class).to(SwiftAsyncBlobStore.class).in(Scopes.SINGLETON); bind(BlobStore.class).to(SwiftBlobStore.class).in(Scopes.SINGLETON); - configureRequestSigner(); - } - - protected void configureRequestSigner() { - bind(BlobRequestSigner.class).to(SwiftBlobRequestSigner.class); } } diff --git a/apis/swift/src/main/java/org/jclouds/openstack/swift/blobstore/config/TemporaryUrlExtensionModule.java b/apis/swift/src/main/java/org/jclouds/openstack/swift/blobstore/config/TemporaryUrlExtensionModule.java new file mode 100644 index 0000000000..71bcd40c20 --- /dev/null +++ b/apis/swift/src/main/java/org/jclouds/openstack/swift/blobstore/config/TemporaryUrlExtensionModule.java @@ -0,0 +1,97 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.swift.blobstore.config; + +import static org.jclouds.rest.config.BinderUtils.bindClientAndAsyncClient; + +import org.jclouds.blobstore.BlobRequestSigner; +import org.jclouds.date.TimeStamp; +import org.jclouds.openstack.swift.CommonSwiftAsyncClient; +import org.jclouds.openstack.swift.SwiftAsyncClient; +import org.jclouds.openstack.swift.SwiftKeystoneAsyncClient; +import org.jclouds.openstack.swift.TemporaryUrlKey; +import org.jclouds.openstack.swift.blobstore.SwiftBlobSigner; +import org.jclouds.openstack.swift.extensions.KeystoneTemporaryUrlKeyAsyncApi; +import org.jclouds.openstack.swift.extensions.TemporaryUrlKeyApi; +import org.jclouds.openstack.swift.extensions.TemporaryUrlKeyAsyncApi; +import org.jclouds.openstack.swift.suppliers.ReturnOrFetchTemporaryUrlKey; + +import com.google.common.base.Supplier; +import com.google.inject.AbstractModule; +import com.google.inject.Provides; +import com.google.inject.TypeLiteral; + +/** + * Isolates dependencies needed for {@link SwiftBlobSigner} + * + * @author Adrian Cole + * + */ +public abstract class TemporaryUrlExtensionModule extends AbstractModule { + + public static class SwiftTemporaryUrlExtensionModule extends TemporaryUrlExtensionModule { + + @Override + protected void bindRequestSigner() { + bind(BlobRequestSigner.class).to(new TypeLiteral>() { + }); + } + + } + + /** + * Ensures keystone auth is used instead of swift auth + * + */ + public static class SwiftKeystoneTemporaryUrlExtensionModule extends + TemporaryUrlExtensionModule { + + protected void bindTemporaryUrlKeyApi() { + bindClientAndAsyncClient(binder(), TemporaryUrlKeyApi.class, KeystoneTemporaryUrlKeyAsyncApi.class); + } + + @Override + protected void bindRequestSigner() { + bind(BlobRequestSigner.class).to(new TypeLiteral>() { + }); + } + + } + + @Provides + @TimeStamp + protected Long unixEpochTimestampProvider() { + return System.currentTimeMillis() / 1000; /* convert to seconds */ + } + + @Override + protected void configure() { + bindRequestSigner(); + bindTemporaryUrlKeyApi(); + bind(new TypeLiteral>() { + }).annotatedWith(TemporaryUrlKey.class).to(ReturnOrFetchTemporaryUrlKey.class); + } + + protected abstract void bindRequestSigner(); + + protected void bindTemporaryUrlKeyApi() { + bindClientAndAsyncClient(binder(), TemporaryUrlKeyApi.class, TemporaryUrlKeyAsyncApi.class); + } + +} \ No newline at end of file diff --git a/apis/swift/src/main/java/org/jclouds/openstack/swift/config/SwiftKeystoneRestClientModule.java b/apis/swift/src/main/java/org/jclouds/openstack/swift/config/SwiftKeystoneRestClientModule.java index e5b355762b..deff5d995d 100644 --- a/apis/swift/src/main/java/org/jclouds/openstack/swift/config/SwiftKeystoneRestClientModule.java +++ b/apis/swift/src/main/java/org/jclouds/openstack/swift/config/SwiftKeystoneRestClientModule.java @@ -11,7 +11,7 @@ import com.google.common.reflect.TypeToken; import com.google.inject.Scopes; /** - * + * * @author Adrian Cole */ @ConfiguresRestClient @@ -21,9 +21,9 @@ public class SwiftKeystoneRestClientModule extends SwiftRestClientModule, Class> of()); } - + protected void bindResolvedClientsToCommonSwift() { bind(CommonSwiftClient.class).to(SwiftKeystoneClient.class).in(Scopes.SINGLETON); bind(CommonSwiftAsyncClient.class).to(SwiftKeystoneAsyncClient.class).in(Scopes.SINGLETON); - } + } } diff --git a/apis/swift/src/main/java/org/jclouds/openstack/swift/config/SwiftRestClientModule.java b/apis/swift/src/main/java/org/jclouds/openstack/swift/config/SwiftRestClientModule.java index 830aafb650..5cc3fa31a3 100644 --- a/apis/swift/src/main/java/org/jclouds/openstack/swift/config/SwiftRestClientModule.java +++ b/apis/swift/src/main/java/org/jclouds/openstack/swift/config/SwiftRestClientModule.java @@ -54,23 +54,24 @@ import com.google.inject.Provides; import com.google.inject.Scopes; /** - * + * * @author Adrian Cole */ @ConfiguresRestClient -public class SwiftRestClientModule extends RestClientModule { +public class SwiftRestClientModule extends + RestClientModule { @SuppressWarnings("unchecked") public SwiftRestClientModule() { this(TypeToken.class.cast(TypeToken.of(SwiftClient.class)), TypeToken.class.cast(TypeToken - .of(SwiftAsyncClient.class)), ImmutableMap., Class> of()); + .of(SwiftAsyncClient.class)), ImmutableMap., Class> of()); } protected SwiftRestClientModule(TypeToken syncClientType, TypeToken asyncClientType, - Map, Class> sync2Async) { + Map, Class> sync2Async) { super(syncClientType, asyncClientType, sync2Async); } - + public static class StorageEndpointModule extends OpenStackAuthenticationModule { @Provides @Singleton diff --git a/apis/swift/src/main/java/org/jclouds/openstack/swift/domain/internal/ObjectInfoImpl.java b/apis/swift/src/main/java/org/jclouds/openstack/swift/domain/internal/ObjectInfoImpl.java index 3d88cace84..e4022ce3e9 100644 --- a/apis/swift/src/main/java/org/jclouds/openstack/swift/domain/internal/ObjectInfoImpl.java +++ b/apis/swift/src/main/java/org/jclouds/openstack/swift/domain/internal/ObjectInfoImpl.java @@ -33,6 +33,7 @@ import org.jclouds.openstack.swift.domain.ObjectInfo; import com.google.common.base.Objects; import com.google.common.base.Objects.ToStringHelper; import com.google.common.collect.ComparisonChain; +import com.google.common.collect.Ordering; /** * Class ObjectInfoImpl @@ -243,6 +244,6 @@ public class ObjectInfoImpl implements ObjectInfo { @Override public int compareTo(ObjectInfo other) { - return ComparisonChain.start().compare(name, other.getName()).compare(container, other.getContainer()).result(); + return ComparisonChain.start().compare(name, other.getName()).compare(container, other.getContainer(), Ordering.natural().nullsLast()).result(); } } diff --git a/demos/tweetstore/gae-tweetstore/src/main/java/org/jclouds/demo/tweetstore/reference/TweetStoreConstants.java b/apis/swift/src/main/java/org/jclouds/openstack/swift/extensions/KeystoneTemporaryUrlKeyAsyncApi.java similarity index 58% rename from demos/tweetstore/gae-tweetstore/src/main/java/org/jclouds/demo/tweetstore/reference/TweetStoreConstants.java rename to apis/swift/src/main/java/org/jclouds/openstack/swift/extensions/KeystoneTemporaryUrlKeyAsyncApi.java index 562044e2cd..7fb51d8dc2 100644 --- a/demos/tweetstore/gae-tweetstore/src/main/java/org/jclouds/demo/tweetstore/reference/TweetStoreConstants.java +++ b/apis/swift/src/main/java/org/jclouds/openstack/swift/extensions/KeystoneTemporaryUrlKeyAsyncApi.java @@ -16,19 +16,23 @@ * specific language governing permissions and limitations * under the License. */ -package org.jclouds.demo.tweetstore.reference; +package org.jclouds.openstack.swift.extensions; + +import org.jclouds.openstack.keystone.v2_0.filters.AuthenticateRequest; +import org.jclouds.openstack.swift.Storage; +import org.jclouds.rest.annotations.Endpoint; +import org.jclouds.rest.annotations.RequestFilters; +import org.jclouds.rest.annotations.SkipEncoding; /** - * Configuration properties and constants used in TweetStore connections. - * + * Only purpose is to override the auth filter with one that works in keystone + * * @author Adrian Cole + * @see TemporaryUrlKeyApi */ -public interface TweetStoreConstants { - static final String PROPERTY_TWEETSTORE_BLOBSTORES = "jclouds.tweetstore.blobstores"; - static final String PROPERTY_TWEETSTORE_CONTAINER = "jclouds.tweetstore.container"; - /** - * Note that this has to conform to restrictions of all blobstores. for example, azure doesn't - * support periods. - */ - static final String SENDER_NAME = "sendername"; +@SkipEncoding('/') +@RequestFilters(AuthenticateRequest.class) +@Endpoint(Storage.class) +public interface KeystoneTemporaryUrlKeyAsyncApi extends TemporaryUrlKeyAsyncApi { + } diff --git a/apis/swift/src/main/java/org/jclouds/openstack/swift/extensions/TemporaryUrlKeyApi.java b/apis/swift/src/main/java/org/jclouds/openstack/swift/extensions/TemporaryUrlKeyApi.java new file mode 100644 index 0000000000..b8a9f48b65 --- /dev/null +++ b/apis/swift/src/main/java/org/jclouds/openstack/swift/extensions/TemporaryUrlKeyApi.java @@ -0,0 +1,51 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.swift.extensions; + +import org.jclouds.concurrent.Timeout; + +import java.util.concurrent.TimeUnit; + +/** + * @author Andrei Savu + * @see + */ +@Timeout(duration = 120, timeUnit = TimeUnit.SECONDS) +public interface TemporaryUrlKeyApi { + /** + * Retrieve the key used to generate Temporary object access URLs + * + * @return shared secret key or null + * @see + */ + String getTemporaryUrlKey(); + + /** + * To create a Temporary URL you must first set a key as account metadata. + *

+ * Once the key is set, you should not change it while you still want others to be + * able to access your temporary URL. If you change it, the TempURL becomes invalid + * (within 60 seconds, which is the cache time for a key) and others will not be allowed + * to access it. + * + * @param temporaryUrlKey + * @see + */ + void setTemporaryUrlKey(String temporaryUrlKey); +} diff --git a/apis/swift/src/main/java/org/jclouds/openstack/swift/extensions/TemporaryUrlKeyAsyncApi.java b/apis/swift/src/main/java/org/jclouds/openstack/swift/extensions/TemporaryUrlKeyAsyncApi.java new file mode 100644 index 0000000000..352c7197ce --- /dev/null +++ b/apis/swift/src/main/java/org/jclouds/openstack/swift/extensions/TemporaryUrlKeyAsyncApi.java @@ -0,0 +1,60 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.swift.extensions; + +import com.google.common.util.concurrent.ListenableFuture; +import org.jclouds.openstack.filters.AuthenticateRequest; +import org.jclouds.openstack.swift.Storage; +import org.jclouds.openstack.swift.functions.ParseTemporaryUrlKeyFromHeaders; +import org.jclouds.openstack.swift.reference.SwiftHeaders; +import org.jclouds.rest.annotations.Endpoint; +import org.jclouds.rest.annotations.RequestFilters; +import org.jclouds.rest.annotations.ResponseParser; +import org.jclouds.rest.annotations.SkipEncoding; + +import javax.ws.rs.HEAD; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.POST; +import javax.ws.rs.Path; + +/** + * @author Andrei Savu + * @see TemporaryUrlKeyApi + */ +@SkipEncoding('/') +@RequestFilters(AuthenticateRequest.class) +@Endpoint(Storage.class) +public interface TemporaryUrlKeyAsyncApi { + + /** + * @see TemporaryUrlKeyApi#getTemporaryUrlKey + */ + @HEAD + @Path("/") + @ResponseParser(ParseTemporaryUrlKeyFromHeaders.class) + ListenableFuture getTemporaryUrlKey(); + + /** + * @see TemporaryUrlKeyApi#setTemporaryUrlKey + */ + @POST + @Path("/") + ListenableFuture setTemporaryUrlKey(@HeaderParam(SwiftHeaders.ACCOUNT_TEMPORARY_URL_KEY) String key); + +} diff --git a/apis/cloudfiles/src/main/java/org/jclouds/cloudfiles/functions/ParseTemporaryUrlKeyFromHeaders.java b/apis/swift/src/main/java/org/jclouds/openstack/swift/functions/ParseTemporaryUrlKeyFromHeaders.java similarity index 80% rename from apis/cloudfiles/src/main/java/org/jclouds/cloudfiles/functions/ParseTemporaryUrlKeyFromHeaders.java rename to apis/swift/src/main/java/org/jclouds/openstack/swift/functions/ParseTemporaryUrlKeyFromHeaders.java index fc360aaccf..349dab3334 100644 --- a/apis/cloudfiles/src/main/java/org/jclouds/cloudfiles/functions/ParseTemporaryUrlKeyFromHeaders.java +++ b/apis/swift/src/main/java/org/jclouds/openstack/swift/functions/ParseTemporaryUrlKeyFromHeaders.java @@ -16,13 +16,13 @@ * specific language governing permissions and limitations * under the License. */ -package org.jclouds.cloudfiles.functions; +package org.jclouds.openstack.swift.functions; + +import static org.jclouds.openstack.swift.reference.SwiftHeaders.ACCOUNT_TEMPORARY_URL_KEY; -import com.google.common.base.Function; import org.jclouds.http.HttpResponse; -import static com.google.common.collect.Iterables.getOnlyElement; -import static org.jclouds.cloudfiles.reference.CloudFilesHeaders.ACCOUNT_TEMPORARY_URL_KEY; +import com.google.common.base.Function; /** * @author Andrei Savu @@ -31,6 +31,6 @@ public class ParseTemporaryUrlKeyFromHeaders implements Function { + + private TemporaryUrlKeyApi client; + + @Inject + public ReturnOrFetchTemporaryUrlKey(TemporaryUrlKeyApi client) { + this.client = checkNotNull(client, "client"); + } + + @Override + public String get() { + String key = client.getTemporaryUrlKey(); + if (key == null) { + client.setTemporaryUrlKey(UUID.randomUUID().toString()); + return client.getTemporaryUrlKey(); + } + return key; + } +} diff --git a/apis/swift/src/test/java/org/jclouds/openstack/swift/CommonSwiftClientLiveTest.java b/apis/swift/src/test/java/org/jclouds/openstack/swift/CommonSwiftClientLiveTest.java index 23fbe2d8ec..51a9fdb807 100644 --- a/apis/swift/src/test/java/org/jclouds/openstack/swift/CommonSwiftClientLiveTest.java +++ b/apis/swift/src/test/java/org/jclouds/openstack/swift/CommonSwiftClientLiveTest.java @@ -49,6 +49,7 @@ import org.jclouds.openstack.swift.options.ListContainerOptions; import org.jclouds.util.Strings2; import org.testng.annotations.Test; +import com.google.common.base.Charsets; import com.google.common.collect.Iterables; import com.google.common.collect.Maps; @@ -247,7 +248,7 @@ public abstract class CommonSwiftClientLiveTest ext } // Test PUT chunked/streamed upload with data of "unknown" length - ByteArrayInputStream bais = new ByteArrayInputStream(data.getBytes("UTF-8")); + ByteArrayInputStream bais = new ByteArrayInputStream(data.getBytes(Charsets.UTF_8)); SwiftObject blob = getApi().newSwiftObject(); blob.getInfo().setName("chunked-object"); blob.setPayload(bais); diff --git a/apis/swift/src/test/java/org/jclouds/openstack/swift/CommonSwiftClientTest.java b/apis/swift/src/test/java/org/jclouds/openstack/swift/CommonSwiftClientTest.java index a8d3815445..3023e5e551 100644 --- a/apis/swift/src/test/java/org/jclouds/openstack/swift/CommonSwiftClientTest.java +++ b/apis/swift/src/test/java/org/jclouds/openstack/swift/CommonSwiftClientTest.java @@ -28,17 +28,21 @@ import java.util.Properties; import javax.inject.Singleton; import org.jclouds.apis.ApiMetadata; +import org.jclouds.blobstore.BlobRequestSigner; import org.jclouds.http.HttpRequest; import org.jclouds.openstack.functions.URIFromAuthenticationResponseForService; import org.jclouds.openstack.internal.TestOpenStackAuthenticationModule; import org.jclouds.openstack.reference.AuthHeaders; +import org.jclouds.openstack.swift.blobstore.SwiftBlobSigner; import org.jclouds.openstack.swift.blobstore.config.SwiftBlobStoreContextModule; +import org.jclouds.openstack.swift.blobstore.config.TemporaryUrlExtensionModule; import org.jclouds.openstack.swift.config.SwiftRestClientModule; import org.jclouds.rest.internal.BaseAsyncClientTest; import org.jclouds.rest.internal.RestAnnotationProcessor; import org.testng.annotations.Test; import com.google.common.base.Supplier; +import com.google.common.base.Suppliers; import com.google.common.collect.ImmutableSet; import com.google.inject.Module; import com.google.inject.Provides; @@ -46,13 +50,17 @@ import com.google.inject.TypeLiteral; /** * Tests behavior of {@code BindSwiftObjectMetadataToRequest} - * + * * @author Adrian Cole */ // NOTE:without testName, this will not call @Before* and fail w/NPE during surefire -@Test(groups = "unit", testName = "SwiftClientTest") +@Test(groups = "unit", testName = "CommonSwiftClientTest") public abstract class CommonSwiftClientTest extends BaseAsyncClientTest { + public static final long UNIX_EPOCH_TIMESTAMP = 123456789L; + + public static final String TEMPORARY_URL_KEY = "get-or-set-X-Account-Meta-Temp-Url-Key"; + @Override protected TypeLiteral> createTypeLiteral() { return new TypeLiteral>() { @@ -74,11 +82,34 @@ public abstract class CommonSwiftClientTest extends BaseAsyncClientTest { + @Override + protected Long unixEpochTimestampProvider() { + return UNIX_EPOCH_TIMESTAMP; + } + + @Override + protected void configure() { + bindTemporaryUrlKeyApi(); + bind(new TypeLiteral>() { + }).annotatedWith(TemporaryUrlKey.class).toInstance(Suppliers.ofInstance(TEMPORARY_URL_KEY)); + } + + @Override + protected void bindRequestSigner() { + bind(BlobRequestSigner.class).to(new TypeLiteral>() { + }); + } + } + @Override protected ApiMetadata createApiMetadata() { - return new SwiftApiMetadata().toBuilder().defaultModules( - ImmutableSet.> of(StorageEndpointModule.class, SwiftRestClientModule.class, - SwiftBlobStoreContextModule.class)).build(); + return new SwiftApiMetadata().toBuilder() + .defaultModules(ImmutableSet.>builder() + .add(StorageEndpointModule.class) + .add(SwiftRestClientModule.class) + .add(SwiftBlobStoreContextModule.class) + .add(StaticTimeAndTemporaryUrlKeyModule.class).build()).build(); } @Override diff --git a/apis/swift/src/test/java/org/jclouds/openstack/swift/blobstore/SwiftBlobRequestSignerTest.java b/apis/swift/src/test/java/org/jclouds/openstack/swift/blobstore/SwiftBlobRequestSignerTest.java deleted file mode 100644 index 7c3c82ce4a..0000000000 --- a/apis/swift/src/test/java/org/jclouds/openstack/swift/blobstore/SwiftBlobRequestSignerTest.java +++ /dev/null @@ -1,94 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.openstack.swift.blobstore; - -import static org.testng.Assert.assertEquals; - -import java.io.IOException; -import java.util.Date; - -import org.jclouds.blobstore.BlobRequestSigner; -import org.jclouds.blobstore.domain.Blob; -import org.jclouds.blobstore.domain.Blob.Factory; -import org.jclouds.http.HttpRequest; -import org.jclouds.openstack.swift.CommonSwiftClientTest; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -/** - * Tests behavior of {@code CommonSwiftBlobRequestSigner} - * - * @author Adrian Cole - */ -// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire -@Test(groups = "unit", testName = "SwiftBlobRequestSignerTest") -public class SwiftBlobRequestSignerTest extends CommonSwiftClientTest { - - private BlobRequestSigner signer; - private Factory blobFactory; - - public void testSignGetBlob() throws ArrayIndexOutOfBoundsException, SecurityException, IllegalArgumentException, - NoSuchMethodException, IOException { - HttpRequest request = signer.signGetBlob("container", "name"); - - assertRequestLineEquals(request, "GET http://storage/container/name HTTP/1.1"); - assertNonPayloadHeadersEqual(request, "X-Auth-Token: testtoken\n"); - assertPayloadEquals(request, null, null, false); - - assertEquals(request.getFilters().size(), 0); - } - - public void testSignRemoveBlob() throws ArrayIndexOutOfBoundsException, SecurityException, IllegalArgumentException, - NoSuchMethodException, IOException { - HttpRequest request = signer.signRemoveBlob("container", "name"); - - assertRequestLineEquals(request, "DELETE http://storage/container/name HTTP/1.1"); - assertNonPayloadHeadersEqual(request, "X-Auth-Token: testtoken\n"); - assertPayloadEquals(request, null, null, false); - - assertEquals(request.getFilters().size(), 0); - } - - public void testSignPutBlob() throws ArrayIndexOutOfBoundsException, SecurityException, IllegalArgumentException, - NoSuchMethodException, IOException { - Blob blob = blobFactory.create(null); - blob.getMetadata().setName("name"); - blob.setPayload(""); - blob.getPayload().getContentMetadata().setContentLength(2l); - blob.getPayload().getContentMetadata().setContentMD5(new byte[] { 0, 2, 4, 8 }); - blob.getPayload().getContentMetadata().setContentType("text/plain"); - blob.getPayload().getContentMetadata().setExpires(new Date(1000)); - - HttpRequest request = signer.signPutBlob("container", blob); - - assertRequestLineEquals(request, "PUT http://storage/container/name HTTP/1.1"); - assertNonPayloadHeadersEqual(request, "X-Auth-Token: testtoken\n"); - assertContentHeadersEqual(request, "text/plain", null, null, null, (long) 2l, new byte[] { 0, 2, 4, 8 }, new Date(1000)); - - assertEquals(request.getFilters().size(), 0); - } - - @BeforeClass - protected void setupFactory() throws IOException { - super.setupFactory(); - this.blobFactory = injector.getInstance(Blob.Factory.class); - this.signer = injector.getInstance(BlobRequestSigner.class); - } - -} diff --git a/apis/swift/src/test/java/org/jclouds/openstack/swift/blobstore/SwiftBlobSignerExpectTest.java b/apis/swift/src/test/java/org/jclouds/openstack/swift/blobstore/SwiftBlobSignerExpectTest.java new file mode 100644 index 0000000000..d67448cbda --- /dev/null +++ b/apis/swift/src/test/java/org/jclouds/openstack/swift/blobstore/SwiftBlobSignerExpectTest.java @@ -0,0 +1,140 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.swift.blobstore; + +import static org.jclouds.openstack.swift.reference.SwiftHeaders.ACCOUNT_TEMPORARY_URL_KEY; + +import java.util.Map; + +import org.jclouds.apis.ApiMetadata; +import org.jclouds.blobstore.internal.BaseBlobSignerExpectTest; +import org.jclouds.http.HttpRequest; +import org.jclouds.http.HttpResponse; +import org.jclouds.openstack.swift.CommonSwiftClientTest.StorageEndpointModule; +import org.jclouds.openstack.swift.SwiftApiMetadata; +import org.jclouds.openstack.swift.blobstore.config.SwiftBlobStoreContextModule; +import org.jclouds.openstack.swift.blobstore.config.TemporaryUrlExtensionModule.SwiftTemporaryUrlExtensionModule; +import org.jclouds.openstack.swift.config.SwiftRestClientModule; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; +import com.google.inject.Module; + +/** + * Tests behavior of {@code SwiftBlobRequestSigner} + * + * @author Adrian Cole + */ +@Test(groups = "unit", testName = "SwiftBlobSignerExpectTest") +public class SwiftBlobSignerExpectTest extends BaseBlobSignerExpectTest { + + public SwiftBlobSignerExpectTest() { + identity = "test:tester"; + credential = "testing"; + } + + @Override + protected HttpRequest getBlob() { + return HttpRequest.builder().method("GET") + .endpoint("http://storage/container/name") + .addHeader("X-Auth-Token", "testtoken").build(); + } + + @Override + protected HttpRequest getBlobWithTime() { + return HttpRequest.builder().method("GET") + .endpoint("http://storage/container/name?temp_url_sig=2abd47f6b1c159fe9a45c873aaade8eeeb36a2e1&temp_url_expires=123456792").build(); + } + + @Override + protected HttpRequest getBlobWithOptions() { + return HttpRequest.builder().method("GET") + .endpoint("http://storage/container/name") + .addHeader("X-Auth-Token", "testtoken") + .addHeader("Range", "bytes=0-1").build(); + } + + @Override + protected HttpRequest putBlob() { + return HttpRequest.builder().method("PUT") + .endpoint("http://storage/container/name") + .addHeader("X-Auth-Token", "testtoken").build(); + } + + @Override + protected HttpRequest putBlobWithTime() { + return HttpRequest.builder().method("PUT") + .endpoint("http://storage/container/name?temp_url_sig=e894c60fa1284cc575cf22d7786bab07b8c33610&temp_url_expires=123456792").build(); + } + + @Override + protected HttpRequest removeBlob() { + return HttpRequest.builder().method("DELETE") + .endpoint("http://storage/container/name") + .addHeader("X-Auth-Token", "testtoken").build(); + } + + @Override + protected Map init() { + HttpRequest authRequest = HttpRequest.builder().method("GET") + .endpoint("http://auth/v1.0") + .addHeader("X-Auth-User", identity) + .addHeader("X-Auth-Key", credential) + .addHeader("Accept", "*/*") + .addHeader("Host", "myhost:8080").build(); + + HttpResponse authResponse = HttpResponse.builder().statusCode(200) + .message("HTTP/1.1 200 OK") + .addHeader("X-Storage-Url", "http://storage") + .addHeader("X-Auth-Token", "testtoken").build(); + + HttpRequest temporaryKeyRequest = HttpRequest.builder().method("HEAD") + .endpoint("http://storage/") + .addHeader("X-Auth-Token", "testtoken").build(); + + HttpResponse temporaryKeyResponse = HttpResponse.builder().statusCode(200) + .addHeader(ACCOUNT_TEMPORARY_URL_KEY, "TEMPORARY_KEY").build(); + + return ImmutableMap. builder() + .put(authRequest, authResponse) + .put(temporaryKeyRequest, temporaryKeyResponse).build(); + } + + public static class StaticTimeAndTemporaryUrlKeyModule extends SwiftTemporaryUrlExtensionModule { + + @Override + protected Long unixEpochTimestampProvider() { + return 123456789L; + } + } + + @Override + protected ApiMetadata createApiMetadata() { + return new SwiftApiMetadata() + .toBuilder() + .defaultEndpoint("http://auth") + .defaultModules( + ImmutableSet.> builder() + .add(StorageEndpointModule.class) + .add(SwiftRestClientModule.class) + .add(SwiftBlobStoreContextModule.class) + .add(StaticTimeAndTemporaryUrlKeyModule.class).build()).build(); + } +} diff --git a/apis/swift/src/test/java/org/jclouds/openstack/swift/blobstore/SwiftKeystoneBlobSignerExpectTest.java b/apis/swift/src/test/java/org/jclouds/openstack/swift/blobstore/SwiftKeystoneBlobSignerExpectTest.java new file mode 100644 index 0000000000..130ea8b017 --- /dev/null +++ b/apis/swift/src/test/java/org/jclouds/openstack/swift/blobstore/SwiftKeystoneBlobSignerExpectTest.java @@ -0,0 +1,142 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.swift.blobstore; + +import static org.jclouds.openstack.swift.reference.SwiftHeaders.ACCOUNT_TEMPORARY_URL_KEY; + +import java.util.Map; + +import org.jclouds.apis.ApiMetadata; +import org.jclouds.blobstore.internal.BaseBlobSignerExpectTest; +import org.jclouds.http.HttpRequest; +import org.jclouds.http.HttpResponse; +import org.jclouds.openstack.keystone.v2_0.config.KeystoneAuthenticationModule; +import org.jclouds.openstack.swift.SwiftKeystoneApiMetadata; +import org.jclouds.openstack.swift.blobstore.config.SwiftBlobStoreContextModule; +import org.jclouds.openstack.swift.blobstore.config.TemporaryUrlExtensionModule.SwiftKeystoneTemporaryUrlExtensionModule; +import org.jclouds.openstack.swift.config.SwiftKeystoneRestClientModule; +import org.jclouds.openstack.swift.config.SwiftRestClientModule.KeystoneStorageEndpointModule; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; +import com.google.inject.Module; + +/** + * Tests behavior of {@code SwiftBlobRequestSigner} + * + * @author Adrian Cole + */ +@Test(groups = "unit", testName = "SwiftKeystoneBlobSignerExpectTest") +public class SwiftKeystoneBlobSignerExpectTest extends BaseBlobSignerExpectTest { + + @Override + protected HttpRequest getBlob() { + return HttpRequest.builder().method("GET") + .endpoint("https://objects.jclouds.org/v1.0/40806637803162/container/name") + .addHeader("X-Auth-Token", "Auth_4f173437e4b013bee56d1007").build(); + } + + @Override + protected HttpRequest getBlobWithTime() { + return HttpRequest.builder().method("GET") + .endpoint("https://objects.jclouds.org/v1.0/40806637803162/container/name?temp_url_sig=fd9b09acbc3ce71182240503c803dda4902098a9&temp_url_expires=123456792").build(); + } + + @Override + protected HttpRequest getBlobWithOptions() { + return HttpRequest.builder().method("GET") + .endpoint("https://objects.jclouds.org/v1.0/40806637803162/container/name") + .addHeader("X-Auth-Token", "Auth_4f173437e4b013bee56d1007").addHeader("Range", "bytes=0-1").build(); + } + + @Override + protected HttpRequest putBlob() { + return HttpRequest.builder().method("PUT") + .endpoint("https://objects.jclouds.org/v1.0/40806637803162/container/name") + .addHeader("X-Auth-Token", "Auth_4f173437e4b013bee56d1007").build(); + } + + @Override + protected HttpRequest putBlobWithTime() { + return HttpRequest.builder().method("PUT") + .endpoint("https://objects.jclouds.org/v1.0/40806637803162/container/name?temp_url_sig=72e5f6ebafab2b3da0586198797e58fb7478211e&temp_url_expires=123456792").build(); + } + + @Override + protected HttpRequest removeBlob() { + return HttpRequest.builder().method("DELETE") + .endpoint("https://objects.jclouds.org/v1.0/40806637803162/container/name") + .addHeader("X-Auth-Token", "Auth_4f173437e4b013bee56d1007").build(); + } + + /** + * add the keystone commands + */ + @Override + protected Map init() { + + HttpRequest authenticate = HttpRequest + .builder() + .method("POST") + .endpoint("http://localhost:5000/v2.0/tokens") + .addHeader("Accept", "application/json") + .payload( + payloadFromStringWithContentType( + "{\"auth\":{\"passwordCredentials\":{\"username\":\"identity\",\"password\":\"credential\"}}}", + "application/json")).build(); + + HttpResponse authenticationResponse = HttpResponse.builder().statusCode(200) + .payload(payloadFromResourceWithContentType("/keystoneAuthResponse.json", "application/json")) + .build(); + + HttpRequest temporaryKeyRequest = HttpRequest + .builder() + .method("HEAD") + .endpoint("https://objects.jclouds.org/v1.0/40806637803162/") + .addHeader("X-Auth-Token", "Auth_4f173437e4b013bee56d1007").build(); + + HttpResponse temporaryKeyResponse = HttpResponse.builder().statusCode(200) + .addHeader(ACCOUNT_TEMPORARY_URL_KEY, "TEMPORARY_KEY").build(); + + return ImmutableMap. builder() + .put(authenticate, authenticationResponse) + .put(temporaryKeyRequest, temporaryKeyResponse).build(); + } + + public static class StaticTimeAndTemporaryUrlKeyModule extends SwiftKeystoneTemporaryUrlExtensionModule { + public static final long UNIX_EPOCH_TIMESTAMP = 123456789L; + + @Override + protected Long unixEpochTimestampProvider() { + return UNIX_EPOCH_TIMESTAMP; + } + } + + @Override + protected ApiMetadata createApiMetadata() { + return new SwiftKeystoneApiMetadata().toBuilder() + .defaultModules(ImmutableSet.>builder() + .add(KeystoneStorageEndpointModule.class) + .add(KeystoneAuthenticationModule.RegionModule.class) + .add(SwiftKeystoneRestClientModule.class) + .add(SwiftBlobStoreContextModule.class) + .add(StaticTimeAndTemporaryUrlKeyModule.class).build()).build(); + } +} diff --git a/apis/swift/src/test/java/org/jclouds/openstack/swift/blobstore/integration/SwiftBlobIntegrationLiveTest.java b/apis/swift/src/test/java/org/jclouds/openstack/swift/blobstore/integration/SwiftBlobIntegrationLiveTest.java index a2b4a08392..6966e041ec 100644 --- a/apis/swift/src/test/java/org/jclouds/openstack/swift/blobstore/integration/SwiftBlobIntegrationLiveTest.java +++ b/apis/swift/src/test/java/org/jclouds/openstack/swift/blobstore/integration/SwiftBlobIntegrationLiveTest.java @@ -93,7 +93,7 @@ public class SwiftBlobIntegrationLiveTest extends BaseBlobIntegrationTest { public void testMultipartChunkedFileStream() throws IOException, InterruptedException { FileOutputStream fous = new FileOutputStream(new File("target/const.txt")); - ByteStreams.copy(oneHundredOneConstitutions.getInput(), fous); + ByteStreams.copy(oneHundredOneConstitutions, fous); fous.flush(); fous.close(); String containerName = getContainerName(); diff --git a/apis/swift/src/test/java/org/jclouds/openstack/swift/blobstore/integration/SwiftBlobLiveTest.java b/apis/swift/src/test/java/org/jclouds/openstack/swift/blobstore/integration/SwiftBlobLiveTest.java index 5aa1b4931c..e18e85fd34 100644 --- a/apis/swift/src/test/java/org/jclouds/openstack/swift/blobstore/integration/SwiftBlobLiveTest.java +++ b/apis/swift/src/test/java/org/jclouds/openstack/swift/blobstore/integration/SwiftBlobLiveTest.java @@ -25,7 +25,7 @@ import org.jclouds.openstack.keystone.v2_0.config.KeystoneProperties; import org.testng.annotations.Test; /** - * + * * @author James Murty * @author Adrian Cole */ @@ -37,7 +37,7 @@ public class SwiftBlobLiveTest extends BaseBlobLiveTest { setIfTestSystemPropertyPresent(props, KeystoneProperties.CREDENTIAL_TYPE); return props; } - + public SwiftBlobLiveTest() { provider = System.getProperty("test.swift.provider", "swift"); } diff --git a/apis/swift/src/test/java/org/jclouds/openstack/swift/blobstore/integration/SwiftBlobSignerLiveTest.java b/apis/swift/src/test/java/org/jclouds/openstack/swift/blobstore/integration/SwiftBlobSignerLiveTest.java index 392a38024e..9c6ed48d16 100644 --- a/apis/swift/src/test/java/org/jclouds/openstack/swift/blobstore/integration/SwiftBlobSignerLiveTest.java +++ b/apis/swift/src/test/java/org/jclouds/openstack/swift/blobstore/integration/SwiftBlobSignerLiveTest.java @@ -18,17 +18,16 @@ */ package org.jclouds.openstack.swift.blobstore.integration; -import java.util.Properties; - import org.jclouds.blobstore.integration.internal.BaseBlobSignerLiveTest; import org.jclouds.openstack.keystone.v2_0.config.KeystoneProperties; import org.testng.annotations.Test; +import java.util.Properties; + /** - * * @author Adrian Cole */ -@Test(groups = { "live" }) +@Test(groups = {"live"}) public class SwiftBlobSignerLiveTest extends BaseBlobSignerLiveTest { @Override diff --git a/apis/swift/src/test/java/org/jclouds/openstack/swift/internal/StubSwiftAsyncClient.java b/apis/swift/src/test/java/org/jclouds/openstack/swift/internal/StubSwiftAsyncClient.java index 1341de2b0c..477c53628c 100644 --- a/apis/swift/src/test/java/org/jclouds/openstack/swift/internal/StubSwiftAsyncClient.java +++ b/apis/swift/src/test/java/org/jclouds/openstack/swift/internal/StubSwiftAsyncClient.java @@ -63,7 +63,7 @@ import com.google.common.util.concurrent.ListenableFuture; /** * Implementation of {@link SwiftAsyncClient} which keeps all data in a local Map object. - * + * * @author Adrian Cole */ @Singleton @@ -201,7 +201,7 @@ public class StubSwiftAsyncClient implements CommonSwiftAsyncClient { return null; } - public ListenableFuture setObjectInfo(String container, String key, Map userMetadata) { + public ListenableFuture setObjectInfo(String container, String key, Map userMetadata) { throw new UnsupportedOperationException(); } diff --git a/apis/swift/src/test/java/org/jclouds/openstack/swift/options/ListContainerOptionsTest.java b/apis/swift/src/test/java/org/jclouds/openstack/swift/options/ListContainerOptionsTest.java index ab5d5762d1..c27d8afb5b 100644 --- a/apis/swift/src/test/java/org/jclouds/openstack/swift/options/ListContainerOptionsTest.java +++ b/apis/swift/src/test/java/org/jclouds/openstack/swift/options/ListContainerOptionsTest.java @@ -24,12 +24,11 @@ import static org.jclouds.openstack.swift.options.ListContainerOptions.Builder.u import static org.jclouds.openstack.swift.options.ListContainerOptions.Builder.withPrefix; import static org.testng.Assert.assertEquals; -import java.util.Collections; - import org.jclouds.http.options.HttpRequestOptions; import org.jclouds.openstack.swift.reference.SwiftConstants; import org.testng.annotations.Test; +import com.google.common.collect.ImmutableList; import com.google.common.collect.Multimap; /** @@ -49,7 +48,7 @@ public class ListContainerOptionsTest { public void testPrefix() { ListContainerOptions options = new ListContainerOptions(); options.withPrefix("test"); - assertEquals(options.buildQueryParameters().get(SwiftConstants.PREFIX), Collections.singletonList("test")); + assertEquals(options.buildQueryParameters().get(SwiftConstants.PREFIX), ImmutableList.of("test")); } @Test @@ -64,7 +63,7 @@ public class ListContainerOptionsTest { options.withPrefix("test"); Multimap map = options.buildQueryParameters(); assertEquals(map.size(), 1); - assertEquals(map.get("prefix"), Collections.singletonList("test")); + assertEquals(map.get("prefix"), ImmutableList.of("test")); } @Test @@ -73,8 +72,8 @@ public class ListContainerOptionsTest { options.withPrefix("test").maxResults(1); Multimap map = options.buildQueryParameters(); assertEquals(map.size(), 2); - assertEquals(map.get("prefix"), Collections.singletonList("test")); - assertEquals(map.get("limit"), Collections.singletonList("1")); + assertEquals(map.get("prefix"), ImmutableList.of("test")); + assertEquals(map.get("limit"), ImmutableList.of("1")); } @Test @@ -83,21 +82,21 @@ public class ListContainerOptionsTest { options.withPrefix("/cloudfiles/test").underPath("/"); Multimap map = options.buildQueryParameters(); assertEquals(map.size(), 2); - assertEquals(map.get("prefix"), Collections.singletonList("/cloudfiles/test")); - assertEquals(map.get("path"), Collections.singletonList("/")); + assertEquals(map.get("prefix"), ImmutableList.of("/cloudfiles/test")); + assertEquals(map.get("path"), ImmutableList.of("/")); } @Test public void testNullPrefix() { ListContainerOptions options = new ListContainerOptions(); - assertEquals(options.buildQueryParameters().get(SwiftConstants.PREFIX), Collections.EMPTY_LIST); + assertEquals(options.buildQueryParameters().get(SwiftConstants.PREFIX), ImmutableList.of()); } @Test public void testPrefixStatic() { ListContainerOptions options = withPrefix("test"); - assertEquals(options.buildQueryParameters().get(SwiftConstants.PREFIX), Collections.singletonList("test")); + assertEquals(options.buildQueryParameters().get(SwiftConstants.PREFIX), ImmutableList.of("test")); } @Test(expectedExceptions = NullPointerException.class) @@ -109,19 +108,19 @@ public class ListContainerOptionsTest { public void testMarker() { ListContainerOptions options = new ListContainerOptions(); options.afterMarker("test"); - assertEquals(options.buildQueryParameters().get(SwiftConstants.MARKER), Collections.singletonList("test")); + assertEquals(options.buildQueryParameters().get(SwiftConstants.MARKER), ImmutableList.of("test")); } @Test public void testNullMarker() { ListContainerOptions options = new ListContainerOptions(); - assertEquals(options.buildQueryParameters().get(SwiftConstants.MARKER), Collections.EMPTY_LIST); + assertEquals(options.buildQueryParameters().get(SwiftConstants.MARKER), ImmutableList.of()); } @Test public void testMarkerStatic() { ListContainerOptions options = afterMarker("test"); - assertEquals(options.buildQueryParameters().get(SwiftConstants.MARKER), Collections.singletonList("test")); + assertEquals(options.buildQueryParameters().get(SwiftConstants.MARKER), ImmutableList.of("test")); } @Test(expectedExceptions = NullPointerException.class) @@ -133,19 +132,19 @@ public class ListContainerOptionsTest { public void testMaxKeys() { ListContainerOptions options = new ListContainerOptions(); options.maxResults(1000); - assertEquals(options.buildQueryParameters().get(SwiftConstants.LIMIT), Collections.singletonList("1000")); + assertEquals(options.buildQueryParameters().get(SwiftConstants.LIMIT), ImmutableList.of("1000")); } @Test public void testNullMaxKeys() { ListContainerOptions options = new ListContainerOptions(); - assertEquals(options.buildQueryParameters().get(SwiftConstants.LIMIT), Collections.EMPTY_LIST); + assertEquals(options.buildQueryParameters().get(SwiftConstants.LIMIT), ImmutableList.of()); } @Test public void testMaxKeysStatic() { ListContainerOptions options = maxResults(1000); - assertEquals(options.buildQueryParameters().get(SwiftConstants.LIMIT), Collections.singletonList("1000")); + assertEquals(options.buildQueryParameters().get(SwiftConstants.LIMIT), ImmutableList.of("1000")); } @Test(expectedExceptions = IllegalStateException.class) @@ -157,19 +156,19 @@ public class ListContainerOptionsTest { public void testPath() { ListContainerOptions options = new ListContainerOptions(); options.underPath("test"); - assertEquals(options.buildQueryParameters().get(SwiftConstants.PATH), Collections.singletonList("test")); + assertEquals(options.buildQueryParameters().get(SwiftConstants.PATH), ImmutableList.of("test")); } @Test public void testNullPath() { ListContainerOptions options = new ListContainerOptions(); - assertEquals(options.buildQueryParameters().get(SwiftConstants.PATH), Collections.EMPTY_LIST); + assertEquals(options.buildQueryParameters().get(SwiftConstants.PATH), ImmutableList.of()); } @Test public void testPathStatic() { ListContainerOptions options = underPath("test"); - assertEquals(options.buildQueryParameters().get(SwiftConstants.PATH), Collections.singletonList("test")); + assertEquals(options.buildQueryParameters().get(SwiftConstants.PATH), ImmutableList.of("test")); } @Test(expectedExceptions = NullPointerException.class) diff --git a/apis/swift/src/test/resources/log4j.xml b/apis/swift/src/test/resources/log4j.xml index 12f6512542..fbbca6e6d5 100644 --- a/apis/swift/src/test/resources/log4j.xml +++ b/apis/swift/src/test/resources/log4j.xml @@ -89,9 +89,11 @@ diff --git a/apis/vcloud/pom.xml b/apis/vcloud/pom.xml index 4f23e0f9a3..efe3182210 100644 --- a/apis/vcloud/pom.xml +++ b/apis/vcloud/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.api diff --git a/apis/vcloud/src/test/java/org/jclouds/vcloud/compute/strategy/VCloudComputeServiceAdapterTest.java b/apis/vcloud/src/test/java/org/jclouds/vcloud/compute/strategy/VCloudComputeServiceAdapterTest.java index 8bf2bc9fdb..ae931b8124 100644 --- a/apis/vcloud/src/test/java/org/jclouds/vcloud/compute/strategy/VCloudComputeServiceAdapterTest.java +++ b/apis/vcloud/src/test/java/org/jclouds/vcloud/compute/strategy/VCloudComputeServiceAdapterTest.java @@ -3,7 +3,6 @@ package org.jclouds.vcloud.compute.strategy; import static org.testng.Assert.assertEquals; import java.net.URI; -import java.util.Collections; import org.jclouds.compute.ComputeService; import org.jclouds.http.HttpRequest; @@ -69,6 +68,6 @@ public class VCloudComputeServiceAdapterTest extends BaseVCloudComputeServiceExp Iterable hardwareProfiles = adapter.listHardwareProfiles(); - assertEquals(ImmutableSet.copyOf(hardwareProfiles), Collections.emptySet()); + assertEquals(ImmutableSet.copyOf(hardwareProfiles), ImmutableSet.of()); } } diff --git a/apis/walrus/pom.xml b/apis/walrus/pom.xml index 42b7201f27..c7ec26acd7 100644 --- a/apis/walrus/pom.xml +++ b/apis/walrus/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.api diff --git a/archetypes/compute-service-archetype/pom.xml b/archetypes/compute-service-archetype/pom.xml index 112c7cf14a..c9ac7c10b4 100644 --- a/archetypes/compute-service-archetype/pom.xml +++ b/archetypes/compute-service-archetype/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml jclouds-compute-service-archetype diff --git a/archetypes/pom.xml b/archetypes/pom.xml index ca597868ee..69fe1ff3bb 100644 --- a/archetypes/pom.xml +++ b/archetypes/pom.xml @@ -24,7 +24,7 @@ jclouds-project org.jclouds - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../project/pom.xml jclouds-archetypes diff --git a/archetypes/rest-client-archetype/pom.xml b/archetypes/rest-client-archetype/pom.xml index 24ec77d3ea..cdf7fe2014 100644 --- a/archetypes/rest-client-archetype/pom.xml +++ b/archetypes/rest-client-archetype/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml jclouds-rest-client-archetype diff --git a/archetypes/rest-client-archetype/src/main/resources/archetype-resources/pom.xml b/archetypes/rest-client-archetype/src/main/resources/archetype-resources/pom.xml index 79db3b4e24..cfa9a5ae91 100644 --- a/archetypes/rest-client-archetype/src/main/resources/archetype-resources/pom.xml +++ b/archetypes/rest-client-archetype/src/main/resources/archetype-resources/pom.xml @@ -27,7 +27,7 @@ $symbol_dollar = '$' ) org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml ${groupId} @@ -56,7 +56,7 @@ $symbol_dollar = '$' ) - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ${providerIdentity} ${providerCredential} ${providerApiVersion} diff --git a/assemblies/pom.xml b/assemblies/pom.xml index c575dfb77b..be66a43900 100644 --- a/assemblies/pom.xml +++ b/assemblies/pom.xml @@ -24,7 +24,7 @@ jclouds-project org.jclouds - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../project/pom.xml jclouds-assemblies diff --git a/blobstore/pom.xml b/blobstore/pom.xml index 0575ee6f00..5b088e81b1 100644 --- a/blobstore/pom.xml +++ b/blobstore/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../project/pom.xml jclouds-blobstore diff --git a/blobstore/src/main/java/org/jclouds/blobstore/TransientBlobRequestSigner.java b/blobstore/src/main/java/org/jclouds/blobstore/LocalBlobRequestSigner.java similarity index 94% rename from blobstore/src/main/java/org/jclouds/blobstore/TransientBlobRequestSigner.java rename to blobstore/src/main/java/org/jclouds/blobstore/LocalBlobRequestSigner.java index 9cd59a79be..87f03ab457 100644 --- a/blobstore/src/main/java/org/jclouds/blobstore/TransientBlobRequestSigner.java +++ b/blobstore/src/main/java/org/jclouds/blobstore/LocalBlobRequestSigner.java @@ -36,19 +36,18 @@ import org.jclouds.location.Provider; import com.google.common.base.Supplier; /** - * * @author Adrian Cole */ @Singleton -public class TransientBlobRequestSigner implements BlobRequestSigner { +public class LocalBlobRequestSigner implements BlobRequestSigner { private final BasicAuthentication basicAuth; private final BlobToHttpGetOptions blob2HttpGetOptions; private final Supplier endpoint; private final ContentMetadataCodec contentMetadataCodec; - + @Inject - public TransientBlobRequestSigner(BasicAuthentication basicAuth, BlobToHttpGetOptions blob2HttpGetOptions, @Provider Supplier endpoint, + public LocalBlobRequestSigner(BasicAuthentication basicAuth, BlobToHttpGetOptions blob2HttpGetOptions, @Provider Supplier endpoint, ContentMetadataCodec contentMetadataCodec) { this.basicAuth = checkNotNull(basicAuth, "basicAuth"); this.blob2HttpGetOptions = checkNotNull(blob2HttpGetOptions, "blob2HttpGetOptions"); @@ -96,4 +95,4 @@ public class TransientBlobRequestSigner implements BlobRequestSigner { return basicAuth.filter(request); } -} \ No newline at end of file +} diff --git a/blobstore/src/main/java/org/jclouds/blobstore/TransientStorageStrategy.java b/blobstore/src/main/java/org/jclouds/blobstore/TransientStorageStrategy.java index a4506fc217..1947ad9ca1 100644 --- a/blobstore/src/main/java/org/jclouds/blobstore/TransientStorageStrategy.java +++ b/blobstore/src/main/java/org/jclouds/blobstore/TransientStorageStrategy.java @@ -22,7 +22,6 @@ import static com.google.common.base.Preconditions.checkNotNull; import java.io.ByteArrayOutputStream; import java.io.IOException; -import java.util.Collections; import java.util.Date; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -35,6 +34,7 @@ import javax.ws.rs.core.UriBuilder; import com.google.common.base.Preconditions; import com.google.common.base.Supplier; import com.google.common.base.Throwables; +import com.google.common.collect.ImmutableList; import com.google.common.collect.Multimaps; import org.jclouds.blobstore.domain.Blob; @@ -191,8 +191,8 @@ public class TransientStorageStrategy implements LocalStorageStrategy { blob.getMetadata().setETag(eTag); // Set HTTP headers to match metadata blob.getAllHeaders().replaceValues(HttpHeaders.LAST_MODIFIED, - Collections.singleton(dateService.rfc822DateFormat(blob.getMetadata().getLastModified()))); - blob.getAllHeaders().replaceValues(HttpHeaders.ETAG, Collections.singleton(eTag)); + ImmutableList.of(dateService.rfc822DateFormat(blob.getMetadata().getLastModified()))); + blob.getAllHeaders().replaceValues(HttpHeaders.ETAG, ImmutableList.of(eTag)); copyPayloadHeadersToBlob(payload, blob); blob.getAllHeaders().putAll(Multimaps.forMap(blob.getMetadata().getUserMetadata())); return blob; diff --git a/blobstore/src/main/java/org/jclouds/blobstore/config/TransientBlobStoreContextModule.java b/blobstore/src/main/java/org/jclouds/blobstore/config/TransientBlobStoreContextModule.java index e5bdb32cd6..975c3266eb 100644 --- a/blobstore/src/main/java/org/jclouds/blobstore/config/TransientBlobStoreContextModule.java +++ b/blobstore/src/main/java/org/jclouds/blobstore/config/TransientBlobStoreContextModule.java @@ -22,8 +22,8 @@ import org.jclouds.blobstore.AsyncBlobStore; import org.jclouds.blobstore.BlobRequestSigner; import org.jclouds.blobstore.BlobStore; import org.jclouds.blobstore.LocalAsyncBlobStore; +import org.jclouds.blobstore.LocalBlobRequestSigner; import org.jclouds.blobstore.LocalStorageStrategy; -import org.jclouds.blobstore.TransientBlobRequestSigner; import org.jclouds.blobstore.TransientStorageStrategy; import org.jclouds.blobstore.attr.ConsistencyModel; import org.jclouds.rest.config.BinderUtils; @@ -47,7 +47,7 @@ public class TransientBlobStoreContextModule extends AbstractModule { bind(BlobStore.class).to(LocalBlobStore.class); bind(ConsistencyModel.class).toInstance(ConsistencyModel.STRICT); bind(LocalStorageStrategy.class).to(TransientStorageStrategy.class); - bind(BlobRequestSigner.class).to(TransientBlobRequestSigner.class); + bind(BlobRequestSigner.class).to(LocalBlobRequestSigner.class); } } diff --git a/blobstore/src/main/java/org/jclouds/blobstore/strategy/internal/DeleteAllKeysInList.java b/blobstore/src/main/java/org/jclouds/blobstore/strategy/internal/DeleteAllKeysInList.java index 87d58ae43d..71a94fb559 100644 --- a/blobstore/src/main/java/org/jclouds/blobstore/strategy/internal/DeleteAllKeysInList.java +++ b/blobstore/src/main/java/org/jclouds/blobstore/strategy/internal/DeleteAllKeysInList.java @@ -22,6 +22,7 @@ import static org.jclouds.blobstore.options.ListContainerOptions.Builder.recursi import static org.jclouds.concurrent.FutureIterables.awaitCompletion; import java.util.Map; +import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; @@ -92,16 +93,19 @@ public class DeleteAllKeysInList implements ClearListStrategy, ClearContainerStr Map exceptions = Maps.newHashMap(); PageSet listing; int maxErrors = 3; // TODO parameterize - for (int i = 0; i < maxErrors; ) { + for (int numErrors = 0; numErrors < maxErrors; ) { // fetch partial directory listing try { - listing = Futures.getUnchecked(connection.list(containerName, options)); - } catch (RuntimeException ee) { - ++i; - if (i == maxErrors) { + listing = connection.list(containerName, options).get(); + } catch (InterruptedException ie) { + Thread.currentThread().interrupt(); + break; + } catch (ExecutionException ee) { + ++numErrors; + if (numErrors == maxErrors) { throw Throwables.propagate(ee.getCause()); } - retryHandler.imposeBackoffExponentialDelay(i, message); + retryHandler.imposeBackoffExponentialDelay(numErrors, message); continue; } @@ -151,8 +155,8 @@ public class DeleteAllKeysInList implements ClearListStrategy, ClearContainerStr exceptions = awaitCompletion(responses, userExecutor, maxTime, logger, message); if (!exceptions.isEmpty()) { - ++i; - retryHandler.imposeBackoffExponentialDelay(i, message); + ++numErrors; + retryHandler.imposeBackoffExponentialDelay(numErrors, message); continue; } @@ -161,6 +165,12 @@ public class DeleteAllKeysInList implements ClearListStrategy, ClearContainerStr break; } options = options.afterMarker(marker); + + // Reset numErrors if we execute a successful iteration. This ensures + // that we only try an unsuccessful operation maxErrors times but + // allow progress with directories containing many blobs in the face + // of some failures. + numErrors = 0; } if (!exceptions.isEmpty()) throw new BlobRuntimeException(String.format("error %s: %s", message, exceptions)); diff --git a/blobstore/src/test/java/org/jclouds/blobstore/BlobStoresTest.java b/blobstore/src/test/java/org/jclouds/blobstore/BlobStoresTest.java index 41cf4c711d..29ea2b554c 100644 --- a/blobstore/src/test/java/org/jclouds/blobstore/BlobStoresTest.java +++ b/blobstore/src/test/java/org/jclouds/blobstore/BlobStoresTest.java @@ -21,7 +21,6 @@ package org.jclouds.blobstore; import static org.easymock.EasyMock.createMock; import static org.testng.Assert.assertEquals; -import java.util.Collections; import java.util.HashSet; import java.util.Set; @@ -132,7 +131,7 @@ public class BlobStoresTest { BlobStore blobStore = createMock(BlobStore.class); ListContainerOptions options = ListContainerOptions.NONE; StorageMetadata v1 = createMock(StorageMetadata.class); - PageSet pageSet = new PageSetImpl(Collections.singletonList(v1), null); + PageSet pageSet = new PageSetImpl(ImmutableList.of(v1), null); EasyMock.> expect(blobStore.list(containerName, options)).andReturn(pageSet) .once(); @@ -149,8 +148,8 @@ public class BlobStoresTest { ListContainerOptions options2 = ListContainerOptions.Builder.afterMarker("marker1"); StorageMetadata v1 = createMock(StorageMetadata.class); StorageMetadata v2 = createMock(StorageMetadata.class); - PageSet pageSet = new PageSetImpl(Collections.singletonList(v1), "marker1"); - PageSet pageSet2 = new PageSetImpl(Collections.singletonList(v2), null); + PageSet pageSet = new PageSetImpl(ImmutableList.of(v1), "marker1"); + PageSet pageSet2 = new PageSetImpl(ImmutableList.of(v2), null); EasyMock.> expect(blobStore.list(containerName, options)).andReturn(pageSet) .once(); diff --git a/blobstore/src/test/java/org/jclouds/blobstore/TransientBlobRequestSignerTest.java b/blobstore/src/test/java/org/jclouds/blobstore/TransientBlobRequestSignerTest.java index 445accb319..4089855abc 100644 --- a/blobstore/src/test/java/org/jclouds/blobstore/TransientBlobRequestSignerTest.java +++ b/blobstore/src/test/java/org/jclouds/blobstore/TransientBlobRequestSignerTest.java @@ -36,7 +36,7 @@ import org.testng.annotations.Test; import com.google.inject.TypeLiteral; /** - * Tests behavior of {@code TransientBlobRequestSigner} + * Tests behavior of {@code LocalBlobRequestSigner} * * @author Adrian Cole */ diff --git a/blobstore/src/test/java/org/jclouds/blobstore/functions/ParseBlobFromHeadersAndHttpContentTest.java b/blobstore/src/test/java/org/jclouds/blobstore/functions/ParseBlobFromHeadersAndHttpContentTest.java index 693087bc76..58ddd4d8b8 100644 --- a/blobstore/src/test/java/org/jclouds/blobstore/functions/ParseBlobFromHeadersAndHttpContentTest.java +++ b/blobstore/src/test/java/org/jclouds/blobstore/functions/ParseBlobFromHeadersAndHttpContentTest.java @@ -23,8 +23,6 @@ import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.testng.Assert.assertEquals; -import java.util.Collections; - import javax.inject.Provider; import javax.ws.rs.core.MediaType; @@ -37,6 +35,7 @@ import org.jclouds.http.HttpResponse; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; +import com.google.common.collect.ImmutableList; import com.google.inject.Guice; /** @@ -86,7 +85,7 @@ public class ParseBlobFromHeadersAndHttpContentTest { Blob object = callable.apply(response); assertEquals(object.getPayload().getContentMetadata().getContentLength(), Long.valueOf(10485760)); - assertEquals(object.getAllHeaders().get("Content-Range"), Collections.singletonList("0-10485759/20232760")); + assertEquals(object.getAllHeaders().get("Content-Range"), ImmutableList.of("0-10485759/20232760")); } diff --git a/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseBlobIntegrationTest.java b/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseBlobIntegrationTest.java index 68e7cc41a2..d194001c7f 100644 --- a/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseBlobIntegrationTest.java +++ b/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseBlobIntegrationTest.java @@ -31,7 +31,6 @@ import static org.testng.Assert.assertNull; import java.io.ByteArrayInputStream; import java.io.File; -import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -68,12 +67,12 @@ import org.jclouds.io.Payloads; import org.jclouds.io.WriteTo; import org.jclouds.io.payloads.StreamingPayload; import org.jclouds.logging.Logger; -import org.jclouds.util.Strings2; import org.testng.ITestContext; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; +import com.google.common.base.Charsets; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.base.Throwables; @@ -482,10 +481,10 @@ public class BaseBlobIntegrationTest extends BaseBlobStoreIntegrationTest { @DataProvider(name = "putTests") public Object[][] createData1() throws IOException { + File file = new File("pom.xml"); + String realObject = Files.toString(file, Charsets.UTF_8); - String realObject = Strings2.toStringAndClose(new FileInputStream("pom.xml")); - - return new Object[][] { { "file", "text/xml", new File("pom.xml"), realObject }, + return new Object[][] { { "file", "text/xml", file, realObject }, { "string", "text/xml", realObject, realObject }, { "bytes", "application/octet-stream", realObject.getBytes(), realObject } }; } diff --git a/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseBlobSignerLiveTest.java b/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseBlobSignerLiveTest.java index 200f4399b6..bee7e726f1 100644 --- a/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseBlobSignerLiveTest.java +++ b/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseBlobSignerLiveTest.java @@ -20,41 +20,28 @@ package org.jclouds.blobstore.integration.internal; import static org.jclouds.blobstore.options.GetOptions.Builder.range; import static org.testng.Assert.assertEquals; +import static org.testng.Assert.fail; import org.jclouds.blobstore.domain.Blob; import org.jclouds.http.HttpRequest; +import org.jclouds.rest.AuthorizationException; import org.jclouds.util.Strings2; +import org.testng.SkipException; import org.testng.annotations.Test; +import java.io.IOException; +import java.util.concurrent.TimeUnit; + /** * Tests integrated functionality of all signature commands. *

* Each test uses a different container name, so it should be perfectly fine to run in parallel. - * + * * @author Adrian Cole */ -@Test(groups = { "live" }) +@Test(groups = {"live"}) public class BaseBlobSignerLiveTest extends BaseBlobStoreIntegrationTest { - @Test - public void testSignRemoveUrl() throws Exception { - String name = "hello"; - String text = "fooooooooooooooooooooooo"; - - Blob blob = view.getBlobStore().blobBuilder(name).payload(text).contentType("text/plain").build(); - String container = getContainerName(); - try { - view.getBlobStore().putBlob(container, blob); - assertConsistencyAwareContainerSize(container, 1); - HttpRequest request = view.getSigner().signRemoveBlob(container, name); - assertEquals(request.getFilters().size(), 0); - view.utils().http().invoke(request); - assert !view.getBlobStore().blobExists(container, name); - } finally { - returnContainer(container); - } - } - @Test public void testSignGetUrl() throws Exception { String name = "hello"; @@ -91,6 +78,34 @@ public class BaseBlobSignerLiveTest extends BaseBlobStoreIntegrationTest { } } + @Test + public void testSignGetUrlWithTime() throws InterruptedException, IOException { + String name = "hello"; + String text = "fooooooooooooooooooooooo"; + + Blob blob = view.getBlobStore().blobBuilder(name).payload(text).contentType("text/plain").build(); + String container = getContainerName(); + try { + view.getBlobStore().putBlob(container, blob); + assertConsistencyAwareContainerSize(container, 1); + HttpRequest request = view.getSigner().signGetBlob(container, name, 3 /* seconds */); + + assertEquals(request.getFilters().size(), 0); + assertEquals(Strings2.toString(view.utils().http().invoke(request).getPayload()), text); + + TimeUnit.SECONDS.sleep(4); + try { + Strings2.toString(view.utils().http().invoke(request).getPayload()); + fail("Temporary URL did not expire as expected"); + } catch (AuthorizationException expected) { + } + } catch (UnsupportedOperationException ignore) { + throw new SkipException("signGetUrl with a time limit is not supported on " + provider); + } finally { + returnContainer(container); + } + } + @Test public void testSignPutUrl() throws Exception { String name = "hello"; @@ -108,4 +123,52 @@ public class BaseBlobSignerLiveTest extends BaseBlobStoreIntegrationTest { } } + @Test + public void testSignPutUrlWithTime() throws Exception { + String name = "hello"; + String text = "fooooooooooooooooooooooo"; + + Blob blob = view.getBlobStore().blobBuilder(name).payload(text).contentType("text/plain").build(); + String container = getContainerName(); + try { + HttpRequest request = view.getSigner().signPutBlob(container, blob, 3 /* seconds */); + assertEquals(request.getFilters().size(), 0); + + Strings2.toString(view.utils().http().invoke(request).getPayload()); + assertConsistencyAwareContainerSize(container, 1); + + view.getBlobStore().removeBlob(container, name); + assertConsistencyAwareContainerSize(container, 0); + + TimeUnit.SECONDS.sleep(4); + try { + Strings2.toString(view.utils().http().invoke(request).getPayload()); + fail("Temporary URL did not expire as expected"); + } catch (AuthorizationException expected) { + } + } catch (UnsupportedOperationException ignore) { + throw new SkipException("signPutUrl with a time limit is not supported on " + provider); + } finally { + returnContainer(container); + } + } + + @Test + public void testSignRemoveUrl() throws Exception { + String name = "hello"; + String text = "fooooooooooooooooooooooo"; + + Blob blob = view.getBlobStore().blobBuilder(name).payload(text).contentType("text/plain").build(); + String container = getContainerName(); + try { + view.getBlobStore().putBlob(container, blob); + assertConsistencyAwareContainerSize(container, 1); + HttpRequest request = view.getSigner().signRemoveBlob(container, name); + assertEquals(request.getFilters().size(), 0); + view.utils().http().invoke(request); + assert !view.getBlobStore().blobExists(container, name); + } finally { + returnContainer(container); + } + } } \ No newline at end of file diff --git a/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseServiceIntegrationTest.java b/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseServiceIntegrationTest.java index 3e61b5f821..9fbfc2f7f0 100644 --- a/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseServiceIntegrationTest.java +++ b/blobstore/src/test/java/org/jclouds/blobstore/integration/internal/BaseServiceIntegrationTest.java @@ -19,6 +19,7 @@ package org.jclouds.blobstore.integration.internal; import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertTrue; import java.util.Set; @@ -34,7 +35,7 @@ import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; /** - * + * * @author Adrian Cole */ public class BaseServiceIntegrationTest extends BaseBlobStoreIntegrationTest { @@ -64,6 +65,7 @@ public class BaseServiceIntegrationTest extends BaseBlobStoreIntegrationTest { return containerName.equals(md.getName()) && location.equals(md.getLocation()); } }) : String.format("container %s/%s not found in list %s", location, containerName, list); + assertTrue(view.getBlobStore().containerExists(containerName), containerName); } }); diff --git a/blobstore/src/test/java/org/jclouds/blobstore/internal/BaseBlobSignerExpectTest.java b/blobstore/src/test/java/org/jclouds/blobstore/internal/BaseBlobSignerExpectTest.java new file mode 100644 index 0000000000..c28fc3168d --- /dev/null +++ b/blobstore/src/test/java/org/jclouds/blobstore/internal/BaseBlobSignerExpectTest.java @@ -0,0 +1,121 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.blobstore.internal; + +import static org.jclouds.blobstore.options.GetOptions.Builder.range; +import static org.testng.Assert.assertEquals; + +import java.util.Date; +import java.util.Map; +import java.util.Properties; + +import org.jclouds.blobstore.BlobStore; +import org.jclouds.blobstore.domain.Blob; +import org.jclouds.blobstore.options.GetOptions; +import org.jclouds.http.HttpRequest; +import org.jclouds.http.HttpResponse; +import org.jclouds.rest.internal.BaseRestClientExpectTest; +import org.testng.annotations.Test; + +import com.google.common.base.Function; +import com.google.common.collect.ImmutableMap; +import com.google.inject.Module; + +/** + * @author Adrian Cole + */ +public abstract class BaseBlobSignerExpectTest extends BaseRestClientExpectTest { + + /** + * define the requests and responses needed to initialize the blobstore. For + * example, you may need to add in discovery requests needed (ex. KeyStone in + */ + protected Map init() { + return ImmutableMap. of(); + } + + protected String container = "container"; + protected String name = "name"; + protected String text = "fooooooooooooooooooooooo"; + protected GetOptions options = range(0, 1); + + @Test + public void testSignGetBlob() { + BlobStore getBlob = requestsSendResponses(init()); + assertEquals(getBlob.getContext().getSigner().signGetBlob(container, name), getBlob()); + } + + protected abstract HttpRequest getBlob(); + + @Test + public void testSignGetBlobWithTime() { + BlobStore getBlobWithTime = requestsSendResponses(init()); + HttpRequest compare = getBlobWithTime(); + assertEquals(getBlobWithTime.getContext().getSigner().signGetBlob(container, name, 3l /* seconds */), + compare); + } + + protected abstract HttpRequest getBlobWithTime(); + + @Test + public void testSignGetBlobWithOptions() { + BlobStore getBlobWithOptions = requestsSendResponses(init()); + assertEquals(getBlobWithOptions.getContext().getSigner().signGetBlob(container, name, options), + getBlobWithOptions()); + } + + protected abstract HttpRequest getBlobWithOptions(); + + @Test + public void testSignRemoveBlob() { + BlobStore removeBlob = requestsSendResponses(init()); + assertEquals(removeBlob.getContext().getSigner().signRemoveBlob(container, name), removeBlob()); + } + + @Test + public void testSignPutBlob() throws Exception { + BlobStore signPutBlob = requestsSendResponses(init()); + Blob blob = signPutBlob.blobBuilder("name").forSigning().contentLength(2l).contentMD5(new byte[] { 0, 2, 4, 8 }) + .contentType("text/plain").expires(new Date(1000)).build(); + HttpRequest compare = putBlob(); + compare.setPayload(blob.getPayload()); + assertEquals(signPutBlob.getContext().getSigner().signPutBlob(container, blob), compare); + } + + protected abstract HttpRequest putBlob(); + + @Test + public void testSignPutBlobWithTime() throws Exception { + BlobStore signPutBloblWithTime = requestsSendResponses(init()); + Blob blob = signPutBloblWithTime.blobBuilder(name).payload(text).contentType("text/plain").build(); + HttpRequest compare = putBlobWithTime(); + compare.setPayload(blob.getPayload()); + assertEquals(signPutBloblWithTime.getContext().getSigner().signPutBlob(container, blob, 3l /* seconds */), + compare); + } + + protected abstract HttpRequest putBlobWithTime(); + + protected abstract HttpRequest removeBlob(); + + @Override + public BlobStore createClient(Function fn, Module module, Properties props) { + return createInjector(fn, module, props).getInstance(BlobStore.class); + } +} \ No newline at end of file diff --git a/common/aws/pom.xml b/common/aws/pom.xml index a17ed98e81..7c3dbea7fd 100644 --- a/common/aws/pom.xml +++ b/common/aws/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.common diff --git a/common/aws/src/main/java/org/jclouds/aws/binders/BindMapToIndexedFormParams.java b/common/aws/src/main/java/org/jclouds/aws/binders/BindMapToIndexedFormParams.java new file mode 100644 index 0000000000..4d390797fc --- /dev/null +++ b/common/aws/src/main/java/org/jclouds/aws/binders/BindMapToIndexedFormParams.java @@ -0,0 +1,78 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.aws.binders; + +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; +import static java.lang.String.format; + +import java.util.Map; +import java.util.Map.Entry; + +import org.jclouds.http.HttpRequest; +import org.jclouds.rest.Binder; + +import com.google.common.base.Function; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Maps; +import com.google.common.collect.Multimap; +import com.google.common.collect.Multimaps; + +/** + * @author Adrian Cole + */ +public class BindMapToIndexedFormParams implements Binder { + + private final String keyPattern; + private final String valuePattern; + + protected BindMapToIndexedFormParams(String keyPattern, String valuePattern) { + this.keyPattern = keyPattern; + this.valuePattern = valuePattern; + } + + @SuppressWarnings("unchecked") + @Override + public R bindToRequest(R request, Object input) { + if (checkNotNull(input, "input") instanceof Iterable) + input = Maps.uniqueIndex((Iterable) input, new Function() { + int index = 1; + + @Override + public String apply(String input) { + return index++ + ""; + } + }); + checkArgument(checkNotNull(input, "input") instanceof Map, "this binder is only valid for Map"); + Map mapping = (Map) input; + + ImmutableMap.Builder builder = ImmutableMap.builder(); + int amazonOneBasedIndex = 1; // according to docs, counters must start + // with 1 + for (Entry entry : mapping.entrySet()) { + // not null by contract + builder.put(format(keyPattern, amazonOneBasedIndex), entry.getKey()); + builder.put(format(valuePattern, amazonOneBasedIndex), entry.getValue()); + amazonOneBasedIndex++; + } + Multimap forms = Multimaps.forMap(builder.build()); + return forms.size() == 0 ? request : (R) request.toBuilder().replaceFormParams(forms).build(); + } + +} diff --git a/common/aws/src/main/java/org/jclouds/aws/binders/BindTableToIndexedFormParams.java b/common/aws/src/main/java/org/jclouds/aws/binders/BindTableToIndexedFormParams.java new file mode 100644 index 0000000000..3d0d91d6d7 --- /dev/null +++ b/common/aws/src/main/java/org/jclouds/aws/binders/BindTableToIndexedFormParams.java @@ -0,0 +1,81 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.aws.binders; + +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; +import static java.lang.String.format; + +import java.util.Map; + +import org.jclouds.http.HttpRequest; +import org.jclouds.rest.Binder; + +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableTable; +import com.google.common.collect.ImmutableTable.Builder; +import com.google.common.collect.Multimap; +import com.google.common.collect.Multimaps; +import com.google.common.collect.Table; +import com.google.common.collect.Table.Cell; + +/** + * @author Adrian Cole + */ +public class BindTableToIndexedFormParams implements Binder { + + private final String rowPattern; + private final String columnPattern; + private final String valuePattern; + + protected BindTableToIndexedFormParams(String rowPattern, String columnPattern, String valuePattern) { + this.rowPattern = rowPattern; + this.columnPattern = columnPattern; + this.valuePattern = valuePattern; + } + + @SuppressWarnings("unchecked") + @Override + public R bindToRequest(R request, Object input) { + if (checkNotNull(input, "input") instanceof Map) { + Builder builder = ImmutableTable.builder(); + int index = 1; + for (Map.Entry entry : ((Map) input).entrySet()) + builder.put(index++, entry.getKey(), entry.getValue()); + input = builder.build(); + } + checkArgument(checkNotNull(input, "input") instanceof Table, "this binder is only valid for Table"); + Table table = Table.class.cast(input); + + ImmutableMap.Builder builder = ImmutableMap.builder(); + int amazonOneBasedIndex = 1; // according to docs, counters must start + // with 1 + for (Cell cell : table.cellSet()) { + // not null by contract + builder.put(format(rowPattern, amazonOneBasedIndex), cell.getRowKey().toString()); + builder.put(format(columnPattern, amazonOneBasedIndex), cell.getColumnKey().toString()); + builder.put(format(valuePattern, amazonOneBasedIndex), cell.getValue().toString()); + + amazonOneBasedIndex++; + } + Multimap forms = Multimaps.forMap(builder.build()); + return forms.size() == 0 ? request : (R) request.toBuilder().replaceFormParams(forms).build(); + } + +} diff --git a/common/aws/src/main/java/org/jclouds/aws/config/AWSRestClientModule.java b/common/aws/src/main/java/org/jclouds/aws/config/AWSRestClientModule.java index 7915b4f088..75b4cb5c73 100644 --- a/common/aws/src/main/java/org/jclouds/aws/config/AWSRestClientModule.java +++ b/common/aws/src/main/java/org/jclouds/aws/config/AWSRestClientModule.java @@ -20,6 +20,9 @@ package org.jclouds.aws.config; import java.util.Map; +import java.util.Set; + +import javax.inject.Singleton; import org.jclouds.aws.handlers.AWSClientErrorRetryHandler; import org.jclouds.aws.handlers.ParseAWSErrorFromXmlContent; @@ -31,7 +34,9 @@ import org.jclouds.http.annotation.ServerError; import org.jclouds.rest.ConfiguresRestClient; import org.jclouds.rest.config.RestClientModule; +import com.google.common.collect.ImmutableSet; import com.google.common.reflect.TypeToken; +import com.google.inject.Provides; /** @@ -57,6 +62,13 @@ public abstract class AWSRestClientModule extends RestClientModule { super(syncClientType, asyncClientType, sync2Async); } + @Provides + @ClientError + @Singleton + protected Set provideRetryableCodes(){ + return ImmutableSet.of("RequestTimeout", "OperationAborted", "SignatureDoesNotMatch"); + } + @Override protected void bindErrorHandlers() { bind(HttpErrorHandler.class).annotatedWith(Redirection.class).to(ParseAWSErrorFromXmlContent.class); diff --git a/common/aws/src/main/java/org/jclouds/aws/domain/AWSError.java b/common/aws/src/main/java/org/jclouds/aws/domain/AWSError.java index 05e802def5..8d55506545 100644 --- a/common/aws/src/main/java/org/jclouds/aws/domain/AWSError.java +++ b/common/aws/src/main/java/org/jclouds/aws/domain/AWSError.java @@ -54,7 +54,8 @@ public class AWSError { if (getSignature() != null) sb.append(", signature='").append(getSignature()).append('\''); if (details.size() != 0) - sb.append(", context='").append(details.toString()).append('\'').append('}'); + sb.append(", context='").append(details.toString()).append('\''); + sb.append('}'); return sb.toString(); } diff --git a/common/aws/src/main/java/org/jclouds/aws/handlers/AWSClientErrorRetryHandler.java b/common/aws/src/main/java/org/jclouds/aws/handlers/AWSClientErrorRetryHandler.java index f074f99a0f..b99f8b0ec0 100644 --- a/common/aws/src/main/java/org/jclouds/aws/handlers/AWSClientErrorRetryHandler.java +++ b/common/aws/src/main/java/org/jclouds/aws/handlers/AWSClientErrorRetryHandler.java @@ -20,14 +20,16 @@ package org.jclouds.aws.handlers; import static org.jclouds.http.HttpUtils.closeClientButKeepContentStream; +import java.util.Set; + import org.jclouds.aws.domain.AWSError; import org.jclouds.aws.util.AWSUtils; import org.jclouds.http.HttpCommand; import org.jclouds.http.HttpResponse; import org.jclouds.http.HttpRetryHandler; +import org.jclouds.http.annotation.ClientError; import org.jclouds.http.handlers.BackoffLimitedRetryHandler; -import com.google.common.collect.ImmutableSet; import com.google.inject.Inject; /** @@ -39,27 +41,35 @@ public class AWSClientErrorRetryHandler implements HttpRetryHandler { private final AWSUtils utils; private final BackoffLimitedRetryHandler backoffLimitedRetryHandler; + private final Set retryableCodes; @Inject - public AWSClientErrorRetryHandler(AWSUtils utils, BackoffLimitedRetryHandler backoffLimitedRetryHandler) { + public AWSClientErrorRetryHandler(AWSUtils utils, BackoffLimitedRetryHandler backoffLimitedRetryHandler, + @ClientError Set retryableCodes) { this.utils = utils; this.backoffLimitedRetryHandler = backoffLimitedRetryHandler; + this.retryableCodes = retryableCodes; } + @Override public boolean shouldRetryRequest(HttpCommand command, HttpResponse response) { if (response.getStatusCode() == 400 || response.getStatusCode() == 403 || response.getStatusCode() == 409) { // Content can be null in the case of HEAD requests if (response.getPayload() != null) { closeClientButKeepContentStream(response); AWSError error = utils.parseAWSErrorFromContent(command.getCurrentRequest(), response); - if (error != null - && ImmutableSet.of("RequestTimeout", "OperationAborted", "SignatureDoesNotMatch").contains( - error.getCode())) { - return backoffLimitedRetryHandler.shouldRetryRequest(command, response); + if (error != null) { + return shouldRetryRequestOnError(command, response, error); } } } return false; } + protected boolean shouldRetryRequestOnError(HttpCommand command, HttpResponse response, AWSError error) { + if (retryableCodes.contains(error.getCode())) + return backoffLimitedRetryHandler.shouldRetryRequest(command, response); + return false; + } + } diff --git a/common/aws/src/test/java/org/jclouds/aws/handlers/AWSClientErrorRetryHandlerTest.java b/common/aws/src/test/java/org/jclouds/aws/handlers/AWSClientErrorRetryHandlerTest.java index 03d978f59b..2d2ab66673 100644 --- a/common/aws/src/test/java/org/jclouds/aws/handlers/AWSClientErrorRetryHandlerTest.java +++ b/common/aws/src/test/java/org/jclouds/aws/handlers/AWSClientErrorRetryHandlerTest.java @@ -33,6 +33,8 @@ import org.jclouds.io.Payloads; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; +import com.google.common.collect.ImmutableSet; + /** * Tests behavior of {@code AWSClientErrorRetryHandler} * @@ -49,7 +51,8 @@ public class AWSClientErrorRetryHandlerTest { replay(utils, backoffLimitedRetryHandler, command); - AWSClientErrorRetryHandler retry = new AWSClientErrorRetryHandler(utils, backoffLimitedRetryHandler); + AWSClientErrorRetryHandler retry = new AWSClientErrorRetryHandler(utils, backoffLimitedRetryHandler, + ImmutableSet. of()); assert !retry.shouldRetryRequest(command, HttpResponse.builder().statusCode(401).build()); @@ -70,10 +73,10 @@ public class AWSClientErrorRetryHandlerTest { HttpCommand command = createMock(HttpCommand.class); HttpRequest putBucket = HttpRequest.builder().method("PUT") - .endpoint("https://adriancole-blobstore113.s3.amazonaws.com/").build(); + .endpoint("https://adriancole-blobstore113.s3.amazonaws.com/").build(); HttpResponse operationAborted = HttpResponse.builder().statusCode(409) - .payload(Payloads.newStringPayload(String.format("%s", code))).build(); + .payload(Payloads.newStringPayload(String.format("%s", code))).build(); expect(command.getCurrentRequest()).andReturn(putBucket); @@ -86,7 +89,8 @@ public class AWSClientErrorRetryHandlerTest { replay(utils, backoffLimitedRetryHandler, command); - AWSClientErrorRetryHandler retry = new AWSClientErrorRetryHandler(utils, backoffLimitedRetryHandler); + AWSClientErrorRetryHandler retry = new AWSClientErrorRetryHandler(utils, backoffLimitedRetryHandler, + ImmutableSet. of("RequestTimeout", "OperationAborted", "SignatureDoesNotMatch")); assert retry.shouldRetryRequest(command, operationAborted); diff --git a/common/azure/pom.xml b/common/azure/pom.xml index de82407402..a962989bf0 100644 --- a/common/azure/pom.xml +++ b/common/azure/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.common diff --git a/common/openstack/pom.xml b/common/openstack/pom.xml index af8aa2a6c0..0edacdf557 100644 --- a/common/openstack/pom.xml +++ b/common/openstack/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml diff --git a/common/pom.xml b/common/pom.xml index 9d13aa5e09..1772dba2ea 100644 --- a/common/pom.xml +++ b/common/pom.xml @@ -24,7 +24,7 @@ jclouds-project org.jclouds - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../project/pom.xml org.jclouds.common diff --git a/common/trmk/pom.xml b/common/trmk/pom.xml index cd96a8d4a5..b5884b6fc0 100644 --- a/common/trmk/pom.xml +++ b/common/trmk/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml diff --git a/compute/pom.xml b/compute/pom.xml index 0a3b34c670..32518799f1 100644 --- a/compute/pom.xml +++ b/compute/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../project/pom.xml diff --git a/compute/src/main/clojure/org/jclouds/compute2.clj b/compute/src/main/clojure/org/jclouds/compute2.clj index fc75cd7205..76f3ac8752 100644 --- a/compute/src/main/clojure/org/jclouds/compute2.clj +++ b/compute/src/main/clojure/org/jclouds/compute2.clj @@ -349,7 +349,7 @@ Here's an example of creating and running a small linux node in the group webser [;; RunScriptOptions :override-login-credentials :override-login-user - :override-login-password :override-login-privateKey + :override-login-password :override-login-private-key :override-authenticate-sudo :name-task :run-as-root :wrap-in-init-script :block-on-complete diff --git a/compute/src/main/java/org/jclouds/compute/config/ComputeServiceProperties.java b/compute/src/main/java/org/jclouds/compute/config/ComputeServiceProperties.java index b071aacb04..640515f537 100644 --- a/compute/src/main/java/org/jclouds/compute/config/ComputeServiceProperties.java +++ b/compute/src/main/java/org/jclouds/compute/config/ComputeServiceProperties.java @@ -40,6 +40,12 @@ public interface ComputeServiceProperties { public static final String INIT_STATUS_INITIAL_PERIOD = "jclouds.compute.init-status.initial-period"; public static final String INIT_STATUS_MAX_PERIOD = "jclouds.compute.init-status.max-period"; + // The period in milliseconds between node updates when using the ComputeService + public static final String POLL_INITIAL_PERIOD = "jclouds.compute.poll-status.initial-period"; + + // The max period in milliseconds between node updates when using the ComputeService + public static final String POLL_MAX_PERIOD = "jclouds.compute.poll-status.max-period"; + /** * time in milliseconds to wait for an image to finish creating. * diff --git a/compute/src/main/java/org/jclouds/compute/config/ComputeServiceTimeoutsModule.java b/compute/src/main/java/org/jclouds/compute/config/ComputeServiceTimeoutsModule.java index adb01e7ad8..8997fef90f 100644 --- a/compute/src/main/java/org/jclouds/compute/config/ComputeServiceTimeoutsModule.java +++ b/compute/src/main/java/org/jclouds/compute/config/ComputeServiceTimeoutsModule.java @@ -32,6 +32,7 @@ import javax.inject.Singleton; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.NodeMetadata; +import org.jclouds.compute.functions.PollNodeRunning; import org.jclouds.compute.predicates.AtomicImageAvailable; import org.jclouds.compute.predicates.AtomicImageDeleted; import org.jclouds.compute.predicates.AtomicNodeRunning; @@ -39,12 +40,16 @@ import org.jclouds.compute.predicates.AtomicNodeSuspended; import org.jclouds.compute.predicates.AtomicNodeTerminated; import org.jclouds.compute.predicates.ScriptStatusReturnsZero; import org.jclouds.compute.predicates.ScriptStatusReturnsZero.CommandUsingClient; +import org.jclouds.compute.reference.ComputeServiceConstants.PollPeriod; import org.jclouds.compute.reference.ComputeServiceConstants.Timeouts; import org.jclouds.predicates.RetryablePredicate; +import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.inject.AbstractModule; import com.google.inject.Provides; +import com.google.inject.TypeLiteral; +import com.google.inject.name.Names; /** * @@ -56,26 +61,35 @@ public class ComputeServiceTimeoutsModule extends AbstractModule { @Provides @Singleton @Named(TIMEOUT_NODE_RUNNING) - protected Predicate> nodeRunning(AtomicNodeRunning statusRunning, Timeouts timeouts) { - return timeouts.nodeRunning == 0 ? statusRunning : new RetryablePredicateGuardingNull(statusRunning, - timeouts.nodeRunning); + protected Predicate> nodeRunning( + AtomicNodeRunning statusRunning, Timeouts timeouts, PollPeriod period) { + return timeouts.nodeRunning == 0 ? + statusRunning : + new RetryablePredicateGuardingNull( + statusRunning, timeouts.nodeRunning, period.pollInitialPeriod, period.pollMaxPeriod); } @Provides @Singleton @Named(TIMEOUT_NODE_TERMINATED) - protected Predicate> serverTerminated(AtomicNodeTerminated statusTerminated, Timeouts timeouts) { - return timeouts.nodeTerminated == 0 ? statusTerminated : new RetryablePredicate>(statusTerminated, - timeouts.nodeTerminated); + protected Predicate> serverTerminated( + AtomicNodeTerminated statusTerminated, Timeouts timeouts, PollPeriod period) { + return timeouts.nodeTerminated == 0 ? + statusTerminated : + new RetryablePredicate>( + statusTerminated, timeouts.nodeTerminated, period.pollInitialPeriod, period.pollMaxPeriod); } @Provides @Singleton @Named(TIMEOUT_NODE_SUSPENDED) - protected Predicate> serverSuspended(AtomicNodeSuspended statusSuspended, Timeouts timeouts) { - return timeouts.nodeSuspended == 0 ? statusSuspended : new RetryablePredicateGuardingNull(statusSuspended, - timeouts.nodeSuspended); + protected Predicate> serverSuspended( + AtomicNodeSuspended statusSuspended, Timeouts timeouts, PollPeriod period) { + return timeouts.nodeSuspended == 0 ? + statusSuspended : + new RetryablePredicateGuardingNull( + statusSuspended, timeouts.nodeSuspended, period.pollInitialPeriod, period.pollMaxPeriod); } @Provides @@ -89,22 +103,29 @@ public class ComputeServiceTimeoutsModule extends AbstractModule { @Provides @Singleton @Named(TIMEOUT_IMAGE_AVAILABLE) - protected Predicate> imageAvailable(AtomicImageAvailable statusAvailable, Timeouts timeouts) { - return timeouts.imageAvailable == 0 ? statusAvailable : new RetryablePredicateGuardingNull(statusAvailable, - timeouts.imageAvailable); + protected Predicate> imageAvailable( + AtomicImageAvailable statusAvailable, Timeouts timeouts, PollPeriod period) { + return timeouts.imageAvailable == 0 ? + statusAvailable : + new RetryablePredicateGuardingNull( + statusAvailable, timeouts.imageAvailable, period.pollInitialPeriod, period.pollMaxPeriod); } @Provides @Singleton @Named(TIMEOUT_IMAGE_DELETED) - protected Predicate> serverDeleted(AtomicImageDeleted statusDeleted, Timeouts timeouts) { - return timeouts.imageDeleted == 0 ? statusDeleted : new RetryablePredicate>(statusDeleted, - timeouts.imageDeleted); + protected Predicate> serverDeleted( + AtomicImageDeleted statusDeleted, Timeouts timeouts, PollPeriod period) { + return timeouts.imageDeleted == 0 ? + statusDeleted : + new RetryablePredicate>( + statusDeleted, timeouts.imageDeleted, period.pollInitialPeriod, period.pollMaxPeriod); } @Override protected void configure() { - + bind(new TypeLiteral, AtomicReference>>() { + }).annotatedWith(Names.named(TIMEOUT_NODE_RUNNING)).to(PollNodeRunning.class); } /** @@ -127,7 +148,7 @@ public class ComputeServiceTimeoutsModule extends AbstractModule { private final RetryablePredicate retryablePredicate; - public RetryablePredicateGuardingNull(final Predicate> predicate, long maxWait) { + public RetryablePredicateGuardingNull(final Predicate> predicate, long maxWait, long period, long maxPeriod) { Predicate nonNullThingPredicate = new Predicate() { @Override public boolean apply(AtomicRefAndOrig input) { @@ -139,7 +160,7 @@ public class ComputeServiceTimeoutsModule extends AbstractModule { } } }; - retryablePredicate = new RetryablePredicate(nonNullThingPredicate, maxWait); + retryablePredicate = new RetryablePredicate(nonNullThingPredicate, maxWait, period, maxPeriod); } @Override diff --git a/compute/src/main/java/org/jclouds/compute/functions/PollNodeRunning.java b/compute/src/main/java/org/jclouds/compute/functions/PollNodeRunning.java new file mode 100644 index 0000000000..ee6a744bd6 --- /dev/null +++ b/compute/src/main/java/org/jclouds/compute/functions/PollNodeRunning.java @@ -0,0 +1,87 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.compute.functions; + +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Throwables.propagate; +import static java.lang.String.format; +import static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_RUNNING; +import static org.jclouds.compute.util.ComputeServiceUtils.formatStatus; + +import java.util.concurrent.atomic.AtomicReference; + +import javax.inject.Inject; +import javax.inject.Named; + +import org.jclouds.compute.domain.NodeMetadata; +import org.jclouds.compute.domain.NodeMetadata.Status; + +import com.google.common.base.Function; +import com.google.common.base.Predicate; +import com.google.common.base.Stopwatch; + +/** + * Polls until the node is running or throws {@link IllegalStateException} if + * this cannot be achieved within the timeout. + * + * @author Adrian Cole + * + */ +@Named(TIMEOUT_NODE_RUNNING) +public class PollNodeRunning implements Function, AtomicReference> { + private final Predicate> nodeRunning; + + @Inject + public PollNodeRunning(@Named(TIMEOUT_NODE_RUNNING) Predicate> nodeRunning) { + this.nodeRunning = checkNotNull(nodeRunning, "nodeRunning"); + } + + /** + * @param node + * will be updated with the node which is running + * @throws {@link IllegalStateException} if this cannot be achieved within + * the timeout. + */ + @Override + public AtomicReference apply(AtomicReference node) throws IllegalStateException { + String originalId = node.get().getId(); + NodeMetadata originalNode = node.get(); + try { + Stopwatch stopwatch = new Stopwatch().start(); + if (!nodeRunning.apply(node)) { + long timeWaited = stopwatch.elapsedMillis(); + if (node.get() == null) { + node.set(originalNode); + throw new IllegalStateException(format("api response for node(%s) was null", originalId)); + } else { + throw new IllegalStateException(format( + "node(%s) didn't achieve the status running; aborting after %d seconds with final status: %s", + originalId, timeWaited / 1000, formatStatus(node.get()))); + } + } + } catch (IllegalStateException e) { + if (node.get().getStatus() == Status.TERMINATED) { + throw new IllegalStateException(format("node(%s) terminated", originalId)); + } else { + throw propagate(e); + } + } + return node; + } +} diff --git a/compute/src/main/java/org/jclouds/compute/reference/ComputeServiceConstants.java b/compute/src/main/java/org/jclouds/compute/reference/ComputeServiceConstants.java index ba39b1f700..6cefff9a91 100644 --- a/compute/src/main/java/org/jclouds/compute/reference/ComputeServiceConstants.java +++ b/compute/src/main/java/org/jclouds/compute/reference/ComputeServiceConstants.java @@ -24,6 +24,8 @@ import static org.jclouds.compute.config.ComputeServiceProperties.IMAGE_ID; import static org.jclouds.compute.config.ComputeServiceProperties.IMAGE_LOGIN_USER; import static org.jclouds.compute.config.ComputeServiceProperties.INIT_STATUS_INITIAL_PERIOD; import static org.jclouds.compute.config.ComputeServiceProperties.INIT_STATUS_MAX_PERIOD; +import static org.jclouds.compute.config.ComputeServiceProperties.POLL_INITIAL_PERIOD; +import static org.jclouds.compute.config.ComputeServiceProperties.POLL_MAX_PERIOD; import static org.jclouds.compute.config.ComputeServiceProperties.OS_VERSION_MAP_JSON; import static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_IMAGE_AVAILABLE; import static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_IMAGE_DELETED; @@ -40,6 +42,7 @@ import javax.inject.Named; import javax.inject.Singleton; import org.jclouds.compute.config.ComputeServiceProperties; +import org.jclouds.predicates.RetryablePredicate; import com.google.common.base.Supplier; import com.google.inject.Inject; @@ -52,7 +55,7 @@ public interface ComputeServiceConstants { public static final String COMPUTE_LOGGER = "jclouds.compute"; public static final String LOCAL_PARTITION_GB_PATTERN = "disk_drive/%s/gb"; - + /** * @see ComputeServiceProperties#TIMEOUT_NODE_TERMINATED */ @@ -139,6 +142,17 @@ public interface ComputeServiceConstants { public long initStatusMaxPeriod = 5000; } + @Singleton + public static class PollPeriod { + @Inject(optional = true) + @Named(POLL_INITIAL_PERIOD) + public long pollInitialPeriod = RetryablePredicate.DEFAULT_PERIOD; + + @Inject(optional = true) + @Named(POLL_MAX_PERIOD) + public long pollMaxPeriod = RetryablePredicate.DEFAULT_MAX_PERIOD; + } + @Singleton public static class ReferenceData { @Inject(optional = true) diff --git a/compute/src/main/java/org/jclouds/compute/strategy/CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap.java b/compute/src/main/java/org/jclouds/compute/strategy/CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap.java index 616f39eb33..62486959a2 100644 --- a/compute/src/main/java/org/jclouds/compute/strategy/CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap.java +++ b/compute/src/main/java/org/jclouds/compute/strategy/CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap.java @@ -17,12 +17,11 @@ * under the License. */ package org.jclouds.compute.strategy; + import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Throwables.getRootCause; -import static java.lang.String.format; import static org.jclouds.compute.config.ComputeServiceProperties.TIMEOUT_NODE_RUNNING; -import static org.jclouds.compute.util.ComputeServiceUtils.formatStatus; import java.util.Map; import java.util.Set; @@ -37,18 +36,14 @@ import org.jclouds.compute.callables.RunScriptOnNode; import org.jclouds.compute.config.CustomizationResponse; import org.jclouds.compute.domain.ExecResponse; import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.domain.NodeMetadata.Status; import org.jclouds.compute.options.TemplateOptions; import org.jclouds.compute.reference.ComputeServiceConstants; -import org.jclouds.compute.reference.ComputeServiceConstants.Timeouts; import org.jclouds.compute.util.OpenSocketFinder; import org.jclouds.javax.annotation.Nullable; import org.jclouds.logging.Logger; import org.jclouds.scriptbuilder.domain.Statement; import com.google.common.base.Function; -import com.google.common.base.Predicate; -import com.google.common.base.Stopwatch; import com.google.common.collect.Multimap; import com.google.inject.assistedinject.Assisted; import com.google.inject.assistedinject.AssistedInject; @@ -59,6 +54,7 @@ import com.google.inject.assistedinject.AssistedInject; */ public class CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap implements Callable, Function, Void> { + public static interface Factory { Callable create(TemplateOptions options, AtomicReference node, Set goodNodes, Map badNodes, Multimap customizationResponses); @@ -71,9 +67,8 @@ public class CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap implements Cal @Named(ComputeServiceConstants.COMPUTE_LOGGER) protected Logger logger = Logger.NULL; - private final Predicate> nodeRunning; + private final Function, AtomicReference> pollNodeRunning; private final InitializeRunScriptOnNodeOrPlaceInBadMap.Factory initScriptRunnerFactory; - private final Timeouts timeouts; private final OpenSocketFinder openSocketFinder; @Nullable @@ -88,19 +83,17 @@ public class CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap implements Cal @AssistedInject public CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap( - @Named(TIMEOUT_NODE_RUNNING) Predicate> nodeRunning, - OpenSocketFinder openSocketFinder, Timeouts timeouts, - Function templateOptionsToStatement, + @Named(TIMEOUT_NODE_RUNNING) Function, AtomicReference> pollNodeRunning, + OpenSocketFinder openSocketFinder, Function templateOptionsToStatement, InitializeRunScriptOnNodeOrPlaceInBadMap.Factory initScriptRunnerFactory, @Assisted TemplateOptions options, @Assisted AtomicReference node, @Assisted Set goodNodes, @Assisted Map badNodes, @Assisted Multimap customizationResponses) { this.statement = checkNotNull(templateOptionsToStatement, "templateOptionsToStatement").apply( checkNotNull(options, "options")); - this.nodeRunning = checkNotNull(nodeRunning, "nodeRunning"); + this.pollNodeRunning = checkNotNull(pollNodeRunning, "pollNodeRunning"); this.initScriptRunnerFactory = checkNotNull(initScriptRunnerFactory, "initScriptRunnerFactory"); this.openSocketFinder = checkNotNull(openSocketFinder, "openSocketFinder"); - this.timeouts = checkNotNull(timeouts, "timeouts"); this.node = node; this.options = checkNotNull(options, "options"); this.goodNodes = checkNotNull(goodNodes, "goodNodes"); @@ -110,13 +103,13 @@ public class CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap implements Cal @AssistedInject public CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap( - @Named(TIMEOUT_NODE_RUNNING) Predicate> nodeRunning, GetNodeMetadataStrategy getNode, - OpenSocketFinder openSocketFinder, Timeouts timeouts, + @Named(TIMEOUT_NODE_RUNNING) Function, AtomicReference> pollNodeRunning, + GetNodeMetadataStrategy getNode, OpenSocketFinder openSocketFinder, Function templateOptionsToStatement, InitializeRunScriptOnNodeOrPlaceInBadMap.Factory initScriptRunnerFactory, @Assisted TemplateOptions options, @Assisted Set goodNodes, @Assisted Map badNodes, @Assisted Multimap customizationResponses) { - this(nodeRunning, openSocketFinder, timeouts, templateOptionsToStatement, initScriptRunnerFactory, options, + this(pollNodeRunning, openSocketFinder, templateOptionsToStatement, initScriptRunnerFactory, options, new AtomicReference(null), goodNodes, badNodes, customizationResponses); } @@ -125,38 +118,9 @@ public class CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap implements Cal checkState(!tainted, "this object is not designed to be reused: %s", toString()); tainted = true; String originalId = node.get().getId(); - NodeMetadata originalNode = node.get(); try { if (options.shouldBlockUntilRunning()) { - try { - Stopwatch stopwatch = new Stopwatch().start(); - if (!nodeRunning.apply(node)) { - long timeWaited = stopwatch.elapsedMillis(); - long earlyReturnGrace = 10; // sleeps can sometimes return milliseconds early - - if (node.get() == null) { - node.set(originalNode); - throw new IllegalStateException(format("api response for node(%s) was null, so we can't customize", - originalId)); - } else if (timeWaited < (timeouts.nodeRunning - earlyReturnGrace)) { - throw new IllegalStateException( - format( - "node(%s) didn't achieve the status running, so we couldn't customize; aborting prematurely after %d seconds with final status: %s", - originalId, timeWaited / 1000, formatStatus(node.get()))); - } else { - throw new IllegalStateException( - format( - "node(%s) didn't achieve the status running within %d seconds, so we couldn't customize; final status: %s", - originalId, timeouts.nodeRunning / 1000, formatStatus(node.get()))); - } - } - } catch (IllegalStateException e) { - if (node.get().getStatus() == Status.TERMINATED) { - throw new IllegalStateException(format("node(%s) terminated before we could customize", originalId)); - } else { - throw e; - } - } + pollNodeRunning.apply(node); if (statement != null) { RunScriptOnNode runner = initScriptRunnerFactory.create(node.get(), statement, options, badNodes).call(); if (runner != null) { @@ -165,8 +129,8 @@ public class CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap implements Cal } } if (options.getPort() > 0) { - openSocketFinder.findOpenSocketOnNode(node.get(), options.getPort(), - options.getSeconds(), TimeUnit.SECONDS); + openSocketFinder.findOpenSocketOnNode(node.get(), options.getPort(), options.getSeconds(), + TimeUnit.SECONDS); } } logger.debug("<< customized node(%s)", originalId); diff --git a/compute/src/test/java/org/jclouds/compute/config/ComputeServicePropertiesTest.java b/compute/src/test/java/org/jclouds/compute/config/ComputeServicePropertiesTest.java index 573d333351..4e28610033 100644 --- a/compute/src/test/java/org/jclouds/compute/config/ComputeServicePropertiesTest.java +++ b/compute/src/test/java/org/jclouds/compute/config/ComputeServicePropertiesTest.java @@ -24,6 +24,7 @@ import java.util.Properties; import org.jclouds.ContextBuilder; import org.jclouds.compute.reference.ComputeServiceConstants.InitStatusProperties; +import org.jclouds.compute.reference.ComputeServiceConstants.PollPeriod; import org.testng.annotations.Test; /** @@ -51,4 +52,22 @@ public class ComputeServicePropertiesTest { assertEquals(props.initStatusMaxPeriod, 5001); } + public void testDefaultPollPeriod() { + PollPeriod props = ContextBuilder.newBuilder("stub").buildInjector() + .getInstance(PollPeriod.class); + assertEquals(props.pollInitialPeriod, 50); + assertEquals(props.pollMaxPeriod, 1000); + } + + public void testOverridePollPeriod() { + Properties overrides = new Properties(); + overrides.setProperty(ComputeServiceProperties.POLL_INITIAL_PERIOD, "501"); + overrides.setProperty(ComputeServiceProperties.POLL_MAX_PERIOD, "5001"); + + PollPeriod props = ContextBuilder.newBuilder("stub").overrides(overrides).buildInjector() + .getInstance(PollPeriod.class); + + assertEquals(props.pollInitialPeriod, 501); + assertEquals(props.pollMaxPeriod, 5001); + } } diff --git a/compute/src/test/java/org/jclouds/compute/functions/PollNodeRunningTest.java b/compute/src/test/java/org/jclouds/compute/functions/PollNodeRunningTest.java new file mode 100644 index 0000000000..d6664d8154 --- /dev/null +++ b/compute/src/test/java/org/jclouds/compute/functions/PollNodeRunningTest.java @@ -0,0 +1,163 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.compute.functions; + +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; +import static org.testng.Assert.assertEquals; + +import java.util.concurrent.atomic.AtomicReference; + +import org.easymock.EasyMock; +import org.easymock.IAnswer; +import org.jclouds.compute.config.ComputeServiceTimeoutsModule; +import org.jclouds.compute.domain.NodeMetadata; +import org.jclouds.compute.domain.NodeMetadata.Status; +import org.jclouds.compute.domain.NodeMetadataBuilder; +import org.jclouds.compute.predicates.AtomicNodeRunning; +import org.jclouds.compute.reference.ComputeServiceConstants.PollPeriod; +import org.jclouds.compute.reference.ComputeServiceConstants.Timeouts; +import org.jclouds.compute.strategy.GetNodeMetadataStrategy; +import org.testng.annotations.Test; + +import com.google.common.base.Predicate; + +/** + * @author Adrian Cole + */ +@Test +public class PollNodeRunningTest { + + @Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = "node\\(id\\) didn't achieve the status running; aborting after 0 seconds with final status: PENDING") + public void testIllegalStateExceptionWhenNodeStillPending() { + final NodeMetadata pendingNode = new NodeMetadataBuilder().ids("id").status(Status.PENDING).build(); + + // node always stays pending + Predicate> nodeRunning = new Predicate>() { + + @Override + public boolean apply(AtomicReference input) { + assertEquals(input.get(), pendingNode); + return false; + } + + }; + + AtomicReference atomicNode = new AtomicReference(pendingNode); + try { + new PollNodeRunning(nodeRunning).apply(atomicNode); + } finally { + assertEquals(atomicNode.get(), pendingNode); + } + } + + @Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = "node\\(id\\) terminated") + public void testIllegalStateExceptionWhenNodeDied() { + final NodeMetadata pendingNode = new NodeMetadataBuilder().ids("id").status(Status.PENDING).build(); + final NodeMetadata deadNode = new NodeMetadataBuilder().ids("id").status(Status.TERMINATED).build(); + + Predicate> nodeRunning = new Predicate>() { + + @Override + public boolean apply(AtomicReference input) { + assertEquals(input.get(), pendingNode); + input.set(deadNode); + return false; + } + + }; + + AtomicReference atomicNode = new AtomicReference(pendingNode); + try { + new PollNodeRunning(nodeRunning).apply(atomicNode); + } finally { + assertEquals(atomicNode.get(), deadNode); + } + } + + @Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = "api response for node\\(id\\) was null") + public void testIllegalStateExceptionAndNodeResetWhenRefSetToNull() { + final NodeMetadata pendingNode = new NodeMetadataBuilder().ids("id").status(Status.PENDING).build(); + + Predicate> nodeRunning = new Predicate>() { + + @Override + public boolean apply(AtomicReference input) { + assertEquals(input.get(), pendingNode); + input.set(null); + return false; + } + + }; + + AtomicReference atomicNode = new AtomicReference(pendingNode); + try { + new PollNodeRunning(nodeRunning).apply(atomicNode); + } finally { + assertEquals(atomicNode.get(), pendingNode); + } + } + + public void testRecoversWhenTemporarilyNodeNotFound() { + String nodeId = "myid"; + Timeouts timeouts = new Timeouts(); + + PollPeriod period = new PollPeriod(); + + final NodeMetadata pendingNode = new NodeMetadataBuilder().ids(nodeId).status(Status.PENDING).build(); + final NodeMetadata runningNode = new NodeMetadataBuilder().ids(nodeId).status(Status.RUNNING).build(); + GetNodeMetadataStrategy nodeClient = createMock(GetNodeMetadataStrategy.class); + AtomicNodeRunning nodeRunning = new AtomicNodeRunning(nodeClient); + Predicate> retryableNodeRunning = new ComputeServiceTimeoutsModule() { + public Predicate> nodeRunning(AtomicNodeRunning statusRunning, + Timeouts timeouts, PollPeriod period) { + return super.nodeRunning(statusRunning, timeouts, period); + } + }.nodeRunning(nodeRunning, timeouts, period); + AtomicReference atomicNode = new AtomicReference(pendingNode); + + // Simulate transient error: first call returns null; subsequent calls + // return the running node + EasyMock.expect(nodeClient.getNode(nodeId)).andAnswer(new IAnswer() { + private int count = 0; + + @Override + public NodeMetadata answer() throws Throwable { + count++; + if (count <= 1) { + return null; + } else { + return runningNode; + } + } + }).anyTimes(); + + // replay mocks + replay(nodeClient); + + // run + new PollNodeRunning(retryableNodeRunning).apply(atomicNode); + + assertEquals(atomicNode.get().getStatus(), Status.RUNNING); + + // verify mocks + verify(nodeClient); + } +} diff --git a/compute/src/test/java/org/jclouds/compute/internal/BaseComputeServiceLiveTest.java b/compute/src/test/java/org/jclouds/compute/internal/BaseComputeServiceLiveTest.java index 7c6624a551..0f26611a3f 100644 --- a/compute/src/test/java/org/jclouds/compute/internal/BaseComputeServiceLiveTest.java +++ b/compute/src/test/java/org/jclouds/compute/internal/BaseComputeServiceLiveTest.java @@ -348,8 +348,8 @@ public abstract class BaseComputeServiceLiveTest extends BaseComputeServiceConte // credentials aren't always the same // assertEquals(node1.getCredentials(), node2.getCredentials()); - assertLocationSameOrChild(node1.getLocation(), template.getLocation()); - assertLocationSameOrChild(node2.getLocation(), template.getLocation()); + assertLocationSameOrChild(checkNotNull(node1.getLocation(), "location of %s", node1), template.getLocation()); + assertLocationSameOrChild(checkNotNull(node2.getLocation(), "location of %s", node2), template.getLocation()); checkImageIdMatchesTemplate(node1); checkImageIdMatchesTemplate(node2); checkOsMatchesTemplate(node1); @@ -411,7 +411,7 @@ public abstract class BaseComputeServiceLiveTest extends BaseComputeServiceConte if (existingLocationIsAssignable) assertEquals(node.getLocation(), existingLocation); else - this.assertLocationSameOrChild(node.getLocation(), template.getLocation()); + this.assertLocationSameOrChild(checkNotNull(node.getLocation(), "location of %s", node), template.getLocation()); checkOsMatchesTemplate(node); this.nodes.add(node); } @@ -502,7 +502,7 @@ public abstract class BaseComputeServiceLiveTest extends BaseComputeServiceConte NodeMetadata metadata = client.getNodeMetadata(node.getId()); assertEquals(metadata.getProviderId(), node.getProviderId()); assertEquals(metadata.getGroup(), node.getGroup()); - assertLocationSameOrChild(metadata.getLocation(), template.getLocation()); + assertLocationSameOrChild(checkNotNull(metadata.getLocation(), "location of %s", metadata), template.getLocation()); checkImageIdMatchesTemplate(metadata); checkOsMatchesTemplate(metadata); assert (metadata.getStatus() == Status.RUNNING) : metadata; @@ -645,7 +645,9 @@ public abstract class BaseComputeServiceLiveTest extends BaseComputeServiceConte } protected void createAndRunAServiceInGroup(String group) throws RunNodesException { - ImmutableMap userMetadata = ImmutableMap. of("Name", group); + // note that some cloud providers do not support mixed case tag names + ImmutableMap userMetadata = ImmutableMap. of("name", group); + ImmutableSet tags = ImmutableSet. of(group); Stopwatch watch = new Stopwatch().start(); NodeMetadata node = getOnlyElement(client.createNodesInGroup(group, 1, diff --git a/compute/src/test/java/org/jclouds/compute/strategy/CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMapTest.java b/compute/src/test/java/org/jclouds/compute/strategy/CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMapTest.java index 0634637263..12d914ef9f 100644 --- a/compute/src/test/java/org/jclouds/compute/strategy/CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMapTest.java +++ b/compute/src/test/java/org/jclouds/compute/strategy/CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMapTest.java @@ -23,7 +23,6 @@ import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; import java.util.Map; import java.util.NoSuchElementException; @@ -31,26 +30,19 @@ import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; -import org.easymock.EasyMock; -import org.easymock.IAnswer; -import org.jclouds.compute.config.ComputeServiceTimeoutsModule; import org.jclouds.compute.config.CustomizationResponse; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadata.Status; import org.jclouds.compute.domain.NodeMetadataBuilder; import org.jclouds.compute.functions.TemplateOptionsToStatement; import org.jclouds.compute.options.TemplateOptions; -import org.jclouds.compute.predicates.AtomicNodeRunning; -import org.jclouds.compute.reference.ComputeServiceConstants.Timeouts; import org.jclouds.compute.util.OpenSocketFinder; import org.jclouds.scriptbuilder.domain.Statement; import org.testng.Assert; import org.testng.annotations.Test; import com.google.common.base.Function; -import com.google.common.base.Predicate; import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Iterables; import com.google.common.collect.LinkedHashMultimap; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; @@ -62,10 +54,9 @@ import com.google.common.collect.Sets; @Test(groups = "unit", testName = "CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMapTest") public class CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMapTest { - public void testBreakWhenNodeStillPending() { + public void testBreakOnIllegalStateExceptionDuringPollNode() { InitializeRunScriptOnNodeOrPlaceInBadMap.Factory initScriptRunnerFactory = createMock(InitializeRunScriptOnNodeOrPlaceInBadMap.Factory.class); OpenSocketFinder openSocketFinder = createMock(OpenSocketFinder.class); - Timeouts timeouts = new Timeouts(); Function templateOptionsToStatement = new TemplateOptionsToStatement(); @SuppressWarnings("unused") Statement statement = null; @@ -74,87 +65,40 @@ public class CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMapTest { Map badNodes = Maps.newLinkedHashMap(); Multimap customizationResponses = LinkedHashMultimap.create(); - final NodeMetadata node = new NodeMetadataBuilder().ids("id").status(Status.PENDING).build(); + final NodeMetadata pendingNode = new NodeMetadataBuilder().ids("id").status(Status.PENDING).build(); // node always stays pending - GetNodeMetadataStrategy nodeRunning = new GetNodeMetadataStrategy(){ + Function, AtomicReference> pollNodeRunning = new Function, AtomicReference>() { @Override - public NodeMetadata getNode(String input) { - Assert.assertEquals(input, node.getId()); - return node; + public AtomicReference apply(AtomicReference node) { + Assert.assertEquals(node.get(), pendingNode); + throw new IllegalStateException("bad state!"); } - + }; // replay mocks replay(initScriptRunnerFactory, openSocketFinder); // run - AtomicReference atomicNode = new AtomicReference(node); - new CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap( new AtomicNodeRunning(nodeRunning), openSocketFinder, timeouts, - templateOptionsToStatement, initScriptRunnerFactory, options, atomicNode, goodNodes, badNodes, - customizationResponses).apply(atomicNode); - + AtomicReference atomicNode = new AtomicReference(pendingNode); + new CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap(pollNodeRunning, openSocketFinder, + templateOptionsToStatement, initScriptRunnerFactory, options, atomicNode, goodNodes, badNodes, + customizationResponses).apply(atomicNode); + assertEquals(goodNodes.size(), 0); - assertEquals(badNodes.keySet(), ImmutableSet.of(node)); - assertTrue(badNodes.get(node).getMessage() != null && badNodes.get(node).getMessage().matches( - "node\\(id\\) didn't achieve the status running, so we couldn't customize; aborting prematurely after .* seconds with final status: PENDING"), - badNodes.get(node).getMessage()); + assertEquals(badNodes.keySet(), ImmutableSet.of(pendingNode)); + assertEquals(badNodes.get(pendingNode).getMessage(), "bad state!"); assertEquals(customizationResponses.size(), 0); // verify mocks verify(initScriptRunnerFactory, openSocketFinder); } - public void testBreakGraceFullyWhenNodeDied() { - InitializeRunScriptOnNodeOrPlaceInBadMap.Factory initScriptRunnerFactory = createMock(InitializeRunScriptOnNodeOrPlaceInBadMap.Factory.class); - OpenSocketFinder openSocketFinder = createMock(OpenSocketFinder.class); - Timeouts timeouts = new Timeouts(); - Function templateOptionsToStatement = new TemplateOptionsToStatement(); - @SuppressWarnings("unused") - Statement statement = null; - TemplateOptions options = new TemplateOptions(); - Set goodNodes = Sets.newLinkedHashSet(); - Map badNodes = Maps.newLinkedHashMap(); - Multimap customizationResponses = LinkedHashMultimap.create(); - - final NodeMetadata node = new NodeMetadataBuilder().ids("id").status(Status.PENDING).build(); - final NodeMetadata deadNnode = new NodeMetadataBuilder().ids("id").status(Status.TERMINATED).build(); - - // node dies - GetNodeMetadataStrategy nodeRunning = new GetNodeMetadataStrategy(){ - - @Override - public NodeMetadata getNode(String input) { - Assert.assertEquals(input, node.getId()); - return deadNnode; - } - - }; - - // replay mocks - replay(initScriptRunnerFactory, openSocketFinder); - // run - AtomicReference atomicNode = new AtomicReference(node); - new CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap( new AtomicNodeRunning(nodeRunning), openSocketFinder, timeouts, - templateOptionsToStatement, initScriptRunnerFactory, options, atomicNode, goodNodes, badNodes, - customizationResponses).apply(atomicNode); - - assertEquals(goodNodes.size(), 0); - assertEquals(badNodes.keySet(), ImmutableSet.of(node)); - badNodes.get(node).printStackTrace(); - assertEquals(badNodes.get(node).getMessage(), "node(id) terminated before we could customize"); - assertEquals(customizationResponses.size(), 0); - - // verify mocks - verify(initScriptRunnerFactory, openSocketFinder); - } - public void testBreakGraceWhenNodeSocketFailsToOpen() { int portTimeoutSecs = 2; InitializeRunScriptOnNodeOrPlaceInBadMap.Factory initScriptRunnerFactory = createMock(InitializeRunScriptOnNodeOrPlaceInBadMap.Factory.class); OpenSocketFinder openSocketFinder = createMock(OpenSocketFinder.class); - Timeouts timeouts = new Timeouts(); Function templateOptionsToStatement = new TemplateOptionsToStatement(); TemplateOptions options = new TemplateOptions().blockOnPort(22, portTimeoutSecs); Set goodNodes = Sets.newLinkedHashSet(); @@ -164,27 +108,28 @@ public class CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMapTest { final NodeMetadata pendingNode = new NodeMetadataBuilder().ids("id").status(Status.PENDING).build(); final NodeMetadata runningNode = new NodeMetadataBuilder().ids("id").status(Status.RUNNING).build(); - expect(openSocketFinder.findOpenSocketOnNode(runningNode, 22, portTimeoutSecs, TimeUnit.SECONDS)) - .andThrow(new NoSuchElementException("could not connect to any ip address port")).once(); + expect(openSocketFinder.findOpenSocketOnNode(runningNode, 22, portTimeoutSecs, TimeUnit.SECONDS)).andThrow( + new NoSuchElementException("could not connect to any ip address port")).once(); - GetNodeMetadataStrategy nodeRunning = new GetNodeMetadataStrategy(){ + Function, AtomicReference> pollNodeRunning = new Function, AtomicReference>() { @Override - public NodeMetadata getNode(String input) { - Assert.assertEquals(input, pendingNode.getId()); - return runningNode; + public AtomicReference apply(AtomicReference node) { + Assert.assertEquals(node.get(), pendingNode); + node.set(runningNode); + return node; } - + }; // replay mocks replay(initScriptRunnerFactory, openSocketFinder); - + // run AtomicReference atomicNode = new AtomicReference(pendingNode); - new CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap( new AtomicNodeRunning(nodeRunning), openSocketFinder, timeouts, - templateOptionsToStatement, initScriptRunnerFactory, options, atomicNode, goodNodes, badNodes, - customizationResponses).apply(atomicNode); + new CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap(pollNodeRunning, openSocketFinder, + templateOptionsToStatement, initScriptRunnerFactory, options, atomicNode, goodNodes, badNodes, + customizationResponses).apply(atomicNode); assertEquals(goodNodes.size(), 0); assertEquals(badNodes.keySet(), ImmutableSet.of(pendingNode)); @@ -195,58 +140,4 @@ public class CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMapTest { // verify mocks verify(initScriptRunnerFactory, openSocketFinder); } - - public void testRecoversWhenTemporarilyNodeNotFound() { - String nodeId = "myid"; - - InitializeRunScriptOnNodeOrPlaceInBadMap.Factory initScriptRunnerFactory = createMock(InitializeRunScriptOnNodeOrPlaceInBadMap.Factory.class); - OpenSocketFinder openSocketFinder = createMock(OpenSocketFinder.class); - Timeouts timeouts = new Timeouts(); - Function templateOptionsToStatement = new TemplateOptionsToStatement(); - Set goodNodes = Sets.newLinkedHashSet(); - Map badNodes = Maps.newLinkedHashMap(); - Multimap customizationResponses = LinkedHashMultimap.create(); - TemplateOptions options = new TemplateOptions(); - - final NodeMetadata pendingNode = new NodeMetadataBuilder().ids(nodeId).status(Status.PENDING).build(); - final NodeMetadata runningNode = new NodeMetadataBuilder().ids(nodeId).status(Status.RUNNING).build(); - GetNodeMetadataStrategy nodeClient = createMock(GetNodeMetadataStrategy.class); - AtomicNodeRunning nodeRunning = new AtomicNodeRunning(nodeClient); - Predicate> retryableNodeRunning = new ComputeServiceTimeoutsModule() { - public Predicate> nodeRunning(AtomicNodeRunning statusRunning, Timeouts timeouts) { - return super.nodeRunning(statusRunning, timeouts); - } - }.nodeRunning(nodeRunning, timeouts); - AtomicReference atomicNode = new AtomicReference(pendingNode); - - // Simulate transient error: first call returns null; subsequent calls return the running node - EasyMock.expect(nodeClient.getNode(nodeId)).andAnswer(new IAnswer() { - private int count = 0; - @Override - public NodeMetadata answer() throws Throwable { - count++; - if (count <= 1) { - return null; - } else { - return runningNode; - } - } - }).anyTimes(); - - // replay mocks - replay(initScriptRunnerFactory, openSocketFinder, nodeClient); - - // run - new CustomizeNodeAndAddToGoodMapOrPutExceptionIntoBadMap(retryableNodeRunning, openSocketFinder, timeouts, - templateOptionsToStatement, initScriptRunnerFactory, options, atomicNode, goodNodes, badNodes, - customizationResponses).apply(atomicNode); - - if (badNodes.size() > 0) Iterables.get(badNodes.values(), 0).printStackTrace(); - assertEquals(badNodes.size(), 0); - assertEquals(goodNodes, ImmutableSet.of(runningNode)); - assertEquals(customizationResponses.size(), 0); - - // verify mocks - verify(initScriptRunnerFactory, openSocketFinder, nodeClient); - } } diff --git a/core/pom.xml b/core/pom.xml index 6a8b97bf9a..b8d2c7688d 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -24,7 +24,7 @@ jclouds-project org.jclouds - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../project/pom.xml jclouds-core diff --git a/core/src/main/java/org/jclouds/Context.java b/core/src/main/java/org/jclouds/Context.java index 2e70b8732d..81b577e2ef 100644 --- a/core/src/main/java/org/jclouds/Context.java +++ b/core/src/main/java/org/jclouds/Context.java @@ -46,6 +46,14 @@ import com.google.inject.ImplementedBy; @ImplementedBy(ContextImpl.class) public interface Context extends Location, Closeable { + /** + * Identifies the Context. This is a unique name optionally specified by the user and safe to index on. + * The purpose of this property is to provide means to distinct between multiple contexts, without having to check + * multiple properties or have explicit knowledge of how the context was created. + * @return + */ + String getName(); + /** * will be removed in jclouds 1.6 * diff --git a/core/src/main/java/org/jclouds/ContextBuilder.java b/core/src/main/java/org/jclouds/ContextBuilder.java index 9d8074955d..fa2a0d0d0b 100644 --- a/core/src/main/java/org/jclouds/ContextBuilder.java +++ b/core/src/main/java/org/jclouds/ContextBuilder.java @@ -30,14 +30,7 @@ import static com.google.common.collect.Iterables.filter; import static com.google.common.collect.Iterables.find; import static com.google.common.collect.Iterables.transform; import static com.google.common.collect.Lists.newArrayList; -import static org.jclouds.Constants.PROPERTY_API; -import static org.jclouds.Constants.PROPERTY_API_VERSION; -import static org.jclouds.Constants.PROPERTY_BUILD_VERSION; -import static org.jclouds.Constants.PROPERTY_CREDENTIAL; -import static org.jclouds.Constants.PROPERTY_ENDPOINT; -import static org.jclouds.Constants.PROPERTY_IDENTITY; -import static org.jclouds.Constants.PROPERTY_ISO3166_CODES; -import static org.jclouds.Constants.PROPERTY_PROVIDER; +import static org.jclouds.Constants.*; import static org.jclouds.util.Throwables2.propagateAuthorizationOrOriginalException; import java.util.ArrayList; @@ -53,6 +46,7 @@ import org.jclouds.concurrent.MoreExecutors; import org.jclouds.concurrent.SingleThreaded; import org.jclouds.concurrent.config.ConfiguresExecutorService; import org.jclouds.concurrent.config.ExecutorServiceModule; +import org.jclouds.config.BindNameToContext; import org.jclouds.config.BindPropertiesToExpandedValues; import org.jclouds.config.BindRestContextWithWildcardExtendsExplicitAndRawType; import org.jclouds.domain.Credentials; @@ -154,6 +148,7 @@ public class ContextBuilder { } } + protected Optional name = Optional.absent(); protected Optional providerMetadata = Optional.absent(); protected final String providerId; protected Optional endpoint = Optional.absent(); @@ -196,6 +191,11 @@ public class ContextBuilder { this(null, apiMetadata); } + public ContextBuilder name(String name) { + this.name = Optional.of(checkNotNull(name, "name")); + return this; + } + public ContextBuilder credentials(String identity, @Nullable String credential) { this.identity = Optional.of(checkNotNull(identity, "identity")); this.credential = credential; @@ -258,7 +258,9 @@ public class ContextBuilder { ProviderMetadata providerMetadata = new UpdateProviderMetadataFromProperties(apiMetadata, this.providerMetadata).apply(expanded); - return buildInjector(providerMetadata, creds, modules); + //We use either the specified name (optional) or a hash of provider/api, endpoint, api version & identity. Hash is used to be something readable. + return buildInjector(name.or(String.valueOf(Objects.hashCode(providerMetadata.getId(), + providerMetadata.getEndpoint(), providerMetadata.getApiMetadata().getVersion(), creds.identity))), providerMetadata, creds, modules); } private static String getAndRemove(Properties expanded, String key) { @@ -302,7 +304,7 @@ public class ContextBuilder { return Guice.createInjector(new BindPropertiesToExpandedValues(resolved)).getInstance(Properties.class); } - public static Injector buildInjector(ProviderMetadata providerMetadata, Credentials creds, List inputModules) { + public static Injector buildInjector(String name, ProviderMetadata providerMetadata, Credentials creds, List inputModules) { List modules = newArrayList(); modules.addAll(inputModules); boolean restModuleSpecifiedByUser = restClientModulePresent(inputModules); @@ -318,6 +320,7 @@ public class ContextBuilder { addCredentialStoreIfNotPresent(modules); modules.add(new LifeCycleModule()); modules.add(new BindProviderMetadataContextAndCredentials(providerMetadata, creds)); + modules.add(new BindNameToContext(name)); Injector returnVal = Guice.createInjector(Stage.PRODUCTION, modules); returnVal.getInstance(ExecutionList.class).execute(); return returnVal; @@ -372,7 +375,7 @@ public class ContextBuilder { @SuppressWarnings( { "unchecked" }) static Map propertiesPrefixedWithJcloudsApiOrProviderId(Properties properties, String apiId, String providerId) { - return Maps.filterKeys((Map) properties, containsPattern("^(jclouds|" + providerId + "|" + apiId + return Maps.filterKeys(Map.class.cast(properties), containsPattern("^(jclouds|" + providerId + "|" + apiId + ").*")); } diff --git a/core/src/main/java/org/jclouds/annotations/Name.java b/core/src/main/java/org/jclouds/annotations/Name.java new file mode 100644 index 0000000000..a622ad20a7 --- /dev/null +++ b/core/src/main/java/org/jclouds/annotations/Name.java @@ -0,0 +1,36 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.annotations; + +import javax.inject.Qualifier; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.*; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +/** + * Designates that this Resource qualifies an object to a context name. + */ +@Target( { ANNOTATION_TYPE, FIELD, METHOD, PARAMETER }) +@Retention(RUNTIME) +@Qualifier +public @interface Name { + +} diff --git a/core/src/main/java/org/jclouds/cache/internal/BackoffExponentiallyAndRetryOnThrowableCacheLoader.java b/core/src/main/java/org/jclouds/cache/internal/BackoffExponentiallyAndRetryOnThrowableCacheLoader.java index 967a046143..abdecf8c94 100644 --- a/core/src/main/java/org/jclouds/cache/internal/BackoffExponentiallyAndRetryOnThrowableCacheLoader.java +++ b/core/src/main/java/org/jclouds/cache/internal/BackoffExponentiallyAndRetryOnThrowableCacheLoader.java @@ -23,8 +23,10 @@ import static com.google.common.base.Preconditions.checkNotNull; import java.util.Map; import java.util.concurrent.Callable; +import java.util.concurrent.TimeoutException; import org.jclouds.cache.ForwardingCacheLoader; +import org.jclouds.util.Throwables2; import com.google.common.annotations.Beta; import com.google.common.cache.CacheLoader; @@ -93,7 +95,16 @@ public class BackoffExponentiallyAndRetryOnThrowableCacheLoader extends Fo @Override public V call() throws Exception { - return BackoffExponentiallyAndRetryOnThrowableCacheLoader.super.load(key); + try { + return BackoffExponentiallyAndRetryOnThrowableCacheLoader.super.load(key); + } catch (Exception e) { + TimeoutException te = Throwables2.getFirstThrowableOfType(e, + TimeoutException.class); + if (te != null) { + throw te; + } + throw e; + } } }); } diff --git a/core/src/main/java/org/jclouds/collect/AdvanceUntilEmptyIterable.java b/core/src/main/java/org/jclouds/collect/AdvanceUntilEmptyIterable.java new file mode 100644 index 0000000000..309a530311 --- /dev/null +++ b/core/src/main/java/org/jclouds/collect/AdvanceUntilEmptyIterable.java @@ -0,0 +1,146 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy current the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.collect; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.Iterator; + +import com.google.common.annotations.Beta; +import com.google.common.base.Objects; +import com.google.common.base.Supplier; +import com.google.common.collect.AbstractIterator; +import com.google.common.collect.FluentIterable; +import com.google.common.collect.Iterators; +import com.google.common.collect.UnmodifiableIterator; + +/** + * continues to supply iterables until the last was empty + * + * @param + */ +@Beta +public class AdvanceUntilEmptyIterable extends FluentIterable> { + + public static AdvanceUntilEmptyIterable create(Supplier> nextIterable){ + return new AdvanceUntilEmptyIterable(nextIterable); + } + + private final AdvanceUntilEmptyIterator iterator; + + protected AdvanceUntilEmptyIterable(Supplier> nextIterable) { + this.iterator = new AdvanceUntilEmptyIterator(checkNotNull(nextIterable, "next iterable")); + } + + @Override + public Iterator> iterator() { + return iterator; + } + + static class AdvanceUntilEmptyIterator extends AbstractIterator> { + + private final Supplier> nextIterable; + private transient FluentIterable current; + private transient boolean unread = true; + + AdvanceUntilEmptyIterator(Supplier> nextIterable) { + this.nextIterable = checkNotNull(nextIterable, "next iterable"); + } + + /** + * {@inheritDoc} + */ + @Override + protected FluentIterable computeNext() { + if (unread) + try { + return current = nextIterable.get(); + } finally { + unread = false; + } + else if (current.size() > 0) + return current = nextIterable.get(); + else + return endOfData(); + } + + /** + * {@inheritDoc} + */ + @Override + public int hashCode() { + return Objects.hashCode(current, unread); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null || getClass() != obj.getClass()) + return false; + AdvanceUntilEmptyIterator other = AdvanceUntilEmptyIterator.class.cast(obj); + return Objects.equal(this.current, other.current) && Objects.equal(this.unread, other.unread); + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return Objects.toStringHelper("").omitNullValues().add("current", current).add("unread", unread).toString(); + } + } + + /** + * Combines all the pages into a single unmodifiable iterable. ex. + * + *

+    * FluentIterable blobs = blobstore.list(...).concat();
+    * for (StorageMetadata blob : blobs) {
+    *     process(blob);
+    * }
+    * 
+ * + * @see Iterators#concat + */ + public FluentIterable concat() { + final Iterator> iterator = iterator(); + final UnmodifiableIterator> unmodifiable = new UnmodifiableIterator>() { + @Override + public boolean hasNext() { + return iterator.hasNext(); + } + + @Override + public Iterator next() { + return iterator.next().iterator(); + } + }; + return new FluentIterable() { + @Override + public Iterator iterator() { + return Iterators.concat(unmodifiable); + } + }; + } + +} \ No newline at end of file diff --git a/core/src/main/java/org/jclouds/collect/IterableWithMarkers.java b/core/src/main/java/org/jclouds/collect/IterableWithMarkers.java index f84211281c..bcb1f5caeb 100644 --- a/core/src/main/java/org/jclouds/collect/IterableWithMarkers.java +++ b/core/src/main/java/org/jclouds/collect/IterableWithMarkers.java @@ -26,6 +26,7 @@ import org.jclouds.javax.annotation.Nullable; import com.google.common.annotations.Beta; import com.google.common.base.Optional; +import com.google.common.collect.ImmutableSet; /** * Utilities for using {@link IterableWithMarker}s. @@ -34,6 +35,9 @@ import com.google.common.base.Optional; */ @Beta public class IterableWithMarkers { + + @SuppressWarnings("rawtypes") + public static final IterableWithMarker EMPTY = from(ImmutableSet.of()); /** * Returns a paginated iterable containing the given elements and null marker. diff --git a/core/src/main/java/org/jclouds/collect/PagedIterables.java b/core/src/main/java/org/jclouds/collect/PagedIterables.java index b98c03865d..87988bc7be 100644 --- a/core/src/main/java/org/jclouds/collect/PagedIterables.java +++ b/core/src/main/java/org/jclouds/collect/PagedIterables.java @@ -35,6 +35,17 @@ import com.google.common.collect.ImmutableSet; */ @Beta public class PagedIterables { + + @SuppressWarnings("rawtypes") + public static final PagedIterable EMPTY = new PagedIterable() { + + @Override + public Iterator iterator() { + return ImmutableSet.of(IterableWithMarkers.EMPTY).iterator(); + } + + }; + /** * @param only * the only page of data diff --git a/core/src/main/java/org/jclouds/concurrent/MoreExecutors.java b/core/src/main/java/org/jclouds/concurrent/MoreExecutors.java index c1de84c3cf..3d91414466 100644 --- a/core/src/main/java/org/jclouds/concurrent/MoreExecutors.java +++ b/core/src/main/java/org/jclouds/concurrent/MoreExecutors.java @@ -34,7 +34,6 @@ package org.jclouds.concurrent; -import java.util.Collections; import java.util.List; import java.util.concurrent.AbstractExecutorService; import java.util.concurrent.ExecutorService; @@ -46,6 +45,7 @@ import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import com.google.common.annotations.Beta; +import com.google.common.collect.ImmutableList; /** * functions related to or replacing those in @@ -146,7 +146,7 @@ public class MoreExecutors { @Override public List shutdownNow() { shutdown(); - return Collections.emptyList(); + return ImmutableList.of(); } @Override diff --git a/core/src/main/java/org/jclouds/concurrent/internal/SyncProxy.java b/core/src/main/java/org/jclouds/concurrent/internal/SyncProxy.java index 13b30caf7f..bd6450ca82 100644 --- a/core/src/main/java/org/jclouds/concurrent/internal/SyncProxy.java +++ b/core/src/main/java/org/jclouds/concurrent/internal/SyncProxy.java @@ -21,6 +21,7 @@ package org.jclouds.concurrent.internal; import static com.google.common.base.Preconditions.checkState; import java.lang.reflect.InvocationHandler; +import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.Arrays; @@ -41,6 +42,7 @@ import org.jclouds.util.Throwables2; import com.google.common.base.Function; import com.google.common.base.Optional; +import com.google.common.base.Throwables; import com.google.common.cache.LoadingCache; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; @@ -158,7 +160,11 @@ public class SyncProxy implements InvocationHandler { } return returnVal; } else if (syncMethodMap.containsKey(method)) { - return syncMethodMap.get(method).invoke(delegate, args); + try { + return syncMethodMap.get(method).invoke(delegate, args); + } catch (InvocationTargetException e) { + throw Throwables.propagate(e.getCause()); + } } else { try { return ((ListenableFuture) methodMap.get(method).invoke(delegate, args)).get(timeoutMap.get(method), diff --git a/core/src/main/java/org/jclouds/config/BindNameToContext.java b/core/src/main/java/org/jclouds/config/BindNameToContext.java new file mode 100644 index 0000000000..b95eeb3d94 --- /dev/null +++ b/core/src/main/java/org/jclouds/config/BindNameToContext.java @@ -0,0 +1,39 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.config; + +import com.google.inject.AbstractModule; +import org.jclouds.annotations.Name; + +/** + * Binds name to Context. + */ +public class BindNameToContext extends AbstractModule { + + private final String name; + + public BindNameToContext(String name) { + this.name = name; + } + + @Override + protected void configure() { + bind(String.class).annotatedWith(Name.class).toInstance(name); + } +} \ No newline at end of file diff --git a/core/src/main/java/org/jclouds/crypto/CryptoStreams.java b/core/src/main/java/org/jclouds/crypto/CryptoStreams.java index 5111fcb2d1..86026786bc 100644 --- a/core/src/main/java/org/jclouds/crypto/CryptoStreams.java +++ b/core/src/main/java/org/jclouds/crypto/CryptoStreams.java @@ -24,7 +24,6 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; -import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; @@ -342,16 +341,12 @@ public class CryptoStreams { int currentPos = 0; public boolean processBytes(byte[] buf, int off, int len) { - try { - if (currentPos == 0 && new String(Arrays.copyOfRange(buf, off, 2), "ASCII").equals("0x")) { - off += 2; - } - byte[] decoded = hex(new String(Arrays.copyOfRange(buf, off, len), "ASCII")); - out.write(decoded, 0, decoded.length); - currentPos += len; - } catch (UnsupportedEncodingException e) { - throw new IllegalStateException("ASCII must be supported"); + if (currentPos == 0 && new String(Arrays.copyOfRange(buf, off, 2), Charsets.US_ASCII).equals("0x")) { + off += 2; } + byte[] decoded = hex(new String(Arrays.copyOfRange(buf, off, len), Charsets.US_ASCII)); + out.write(decoded, 0, decoded.length); + currentPos += len; return true; } diff --git a/core/src/main/java/org/jclouds/http/HttpRequest.java b/core/src/main/java/org/jclouds/http/HttpRequest.java index cc14b31893..b17ea21027 100644 --- a/core/src/main/java/org/jclouds/http/HttpRequest.java +++ b/core/src/main/java/org/jclouds/http/HttpRequest.java @@ -26,7 +26,6 @@ import static org.jclouds.io.Payloads.newUrlEncodedFormPayload; import static org.jclouds.util.Multimaps2.replaceEntries; import java.net.URI; -import java.util.Collections; import java.util.List; import org.jclouds.io.Payload; @@ -35,6 +34,7 @@ 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; +import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.Iterables; import com.google.common.collect.Multimap; @@ -138,7 +138,7 @@ public class HttpRequest extends HttpMessage { private T replaceQuery(Multimap map) { URI oldURI = endpoint; String query = makeQueryLine(map, null, Chars.toArray(skips.build())); - endpoint = new UriBuilderImpl().uri(oldURI).replaceQuery(query).buildFromEncodedMap(Collections.EMPTY_MAP); + endpoint = new UriBuilderImpl().uri(oldURI).replaceQuery(query).buildFromEncodedMap(ImmutableMap.of()); return self(); } @@ -150,7 +150,7 @@ public class HttpRequest extends HttpMessage { checkNotNull(endpoint, "endpoint"); checkNotNull(path, "path"); URI oldURI = endpoint; - endpoint = new UriBuilderImpl().uri(oldURI).replacePath(path).buildFromEncodedMap(Collections.EMPTY_MAP); + endpoint = new UriBuilderImpl().uri(oldURI).replacePath(path).buildFromEncodedMap(ImmutableMap.of()); return self(); } diff --git a/core/src/main/java/org/jclouds/http/HttpUtils.java b/core/src/main/java/org/jclouds/http/HttpUtils.java index 43d1de5605..3b80018bbe 100644 --- a/core/src/main/java/org/jclouds/http/HttpUtils.java +++ b/core/src/main/java/org/jclouds/http/HttpUtils.java @@ -50,7 +50,6 @@ import javax.inject.Singleton; import org.jclouds.Constants; import org.jclouds.crypto.CryptoStreams; import org.jclouds.io.ContentMetadata; -import org.jclouds.io.InputSuppliers; import org.jclouds.io.MutableContentMetadata; import org.jclouds.io.Payload; import org.jclouds.io.PayloadEnclosing; @@ -304,17 +303,9 @@ public class HttpUtils { if (message.getPayload().getContentMetadata().getContentLength() != null) logger.debug("%s %s: %s", prefix, CONTENT_LENGTH, message.getPayload().getContentMetadata() .getContentLength()); - if (message.getPayload().getContentMetadata().getContentMD5() != null) - try { - logger.debug( - "%s %s: %s", - prefix, - "Content-MD5", - CryptoStreams.base64Encode(InputSuppliers.of(message.getPayload().getContentMetadata() - .getContentMD5()))); - } catch (IOException e) { - logger.warn(e, " error getting md5 for %s", message); - } + byte[] md5 = message.getPayload().getContentMetadata().getContentMD5(); + if (md5 != null) + logger.debug("%s %s: %s", prefix, "Content-MD5", CryptoStreams.base64(md5)); if (message.getPayload().getContentMetadata().getContentDisposition() != null) logger.debug("%s %s: %s", prefix, "Content-Disposition", message.getPayload().getContentMetadata() .getContentDisposition()); diff --git a/core/src/main/java/org/jclouds/internal/ContextImpl.java b/core/src/main/java/org/jclouds/internal/ContextImpl.java index 114b24917e..8c92c27839 100644 --- a/core/src/main/java/org/jclouds/internal/ContextImpl.java +++ b/core/src/main/java/org/jclouds/internal/ContextImpl.java @@ -18,15 +18,12 @@ */ package org.jclouds.internal; -import static com.google.common.base.Preconditions.checkNotNull; - -import java.net.URI; -import java.util.Map; -import java.util.Set; - -import javax.inject.Inject; - +import com.google.common.base.Objects; +import com.google.common.collect.ImmutableMap; +import com.google.common.io.Closeables; +import com.google.inject.Singleton; import org.jclouds.Context; +import org.jclouds.annotations.Name; import org.jclouds.domain.Credentials; import org.jclouds.domain.Location; import org.jclouds.domain.LocationScope; @@ -35,10 +32,12 @@ import org.jclouds.providers.ProviderMetadata; import org.jclouds.rest.Utils; import org.jclouds.rest.annotations.Identity; -import com.google.common.base.Objects; -import com.google.common.collect.ImmutableMap; -import com.google.common.io.Closeables; -import com.google.inject.Singleton; +import javax.inject.Inject; +import java.net.URI; +import java.util.Map; +import java.util.Set; + +import static com.google.common.base.Preconditions.checkNotNull; /** * @author Adrian Cole @@ -50,14 +49,16 @@ public class ContextImpl implements Context { private final String identity; private final Utils utils; private final Closer closer; + private final String name; @Inject - protected ContextImpl(ProviderMetadata providerMetadata, @Identity String identity, Utils utils, Closer closer) { + protected ContextImpl(@Name String name, ProviderMetadata providerMetadata, @Identity String identity, Utils utils, Closer closer) { this.providerMetadata = checkNotNull(providerMetadata, "providerMetadata"); this.identity = checkNotNull(identity, "identity"); this.utils = checkNotNull(utils, "utils"); this.closer = checkNotNull(closer, "closer"); - } + this.name = checkNotNull(name, "name"); + } /** * {@inheritDoc} @@ -75,7 +76,15 @@ public class ContextImpl implements Context { return providerMetadata; } - /** + /** + * {@inheritDoc} + */ + @Override + public String getName() { + return name; + } + + /** * {@inheritDoc} */ @Override diff --git a/core/src/main/java/org/jclouds/io/InputSuppliers.java b/core/src/main/java/org/jclouds/io/InputSuppliers.java index 90630a2817..51cb0d4d2b 100644 --- a/core/src/main/java/org/jclouds/io/InputSuppliers.java +++ b/core/src/main/java/org/jclouds/io/InputSuppliers.java @@ -82,11 +82,8 @@ public class InputSuppliers { }; } - public static InputSupplier of(byte[] in) { - return ByteStreams.newInputStreamSupplier(checkNotNull(in, "in")); - } - public static InputSupplier of(String in) { - return of(checkNotNull(in, "in").getBytes(Charsets.UTF_8)); + byte[] bytes = checkNotNull(in, "in").getBytes(Charsets.UTF_8); + return ByteStreams.newInputStreamSupplier(bytes); } } diff --git a/core/src/main/java/org/jclouds/io/payloads/BaseMutableContentMetadata.java b/core/src/main/java/org/jclouds/io/payloads/BaseMutableContentMetadata.java index ac2045e966..a4db8f1fd6 100644 --- a/core/src/main/java/org/jclouds/io/payloads/BaseMutableContentMetadata.java +++ b/core/src/main/java/org/jclouds/io/payloads/BaseMutableContentMetadata.java @@ -26,8 +26,6 @@ import org.jclouds.io.ContentMetadataBuilder; import org.jclouds.io.MutableContentMetadata; import org.jclouds.javax.annotation.Nullable; -import com.google.common.collect.Multimap; - /** * @author Adrian Cole */ diff --git a/core/src/main/java/org/jclouds/json/config/GsonModule.java b/core/src/main/java/org/jclouds/json/config/GsonModule.java index 8d273c54ce..fa2728f5b6 100644 --- a/core/src/main/java/org/jclouds/json/config/GsonModule.java +++ b/core/src/main/java/org/jclouds/json/config/GsonModule.java @@ -39,6 +39,8 @@ import org.jclouds.json.Json; import org.jclouds.json.internal.DeserializationConstructorAndReflectiveTypeAdapterFactory; import org.jclouds.json.internal.EnumTypeAdapterThatReturnsFromValue; import org.jclouds.json.internal.GsonWrapper; +import org.jclouds.json.internal.IgnoreNullFluentIterableTypeAdapterFactory; +import org.jclouds.json.internal.IgnoreNullIterableTypeAdapterFactory; import org.jclouds.json.internal.IgnoreNullMapTypeAdapterFactory; import org.jclouds.json.internal.IgnoreNullMultimapTypeAdapterFactory; import org.jclouds.json.internal.IgnoreNullSetTypeAdapterFactory; @@ -81,7 +83,10 @@ public class GsonModule extends AbstractModule { @Provides @Singleton Gson provideGson(TypeAdapter jsonAdapter, DateAdapter adapter, ByteListAdapter byteListAdapter, - ByteArrayAdapter byteArrayAdapter, PropertiesAdapter propertiesAdapter, JsonAdapterBindings bindings) + ByteArrayAdapter byteArrayAdapter, PropertiesAdapter propertiesAdapter, JsonAdapterBindings bindings, + OptionalTypeAdapterFactory optional, IgnoreNullSetTypeAdapterFactory set, + IgnoreNullMapTypeAdapterFactory map, IgnoreNullMultimapTypeAdapterFactory multimap, + IgnoreNullIterableTypeAdapterFactory iterable, IgnoreNullFluentIterableTypeAdapterFactory fluentIterable) throws Exception { FieldNamingStrategy serializationPolicy = new AnnotationOrNameFieldNamingStrategy(new ExtractSerializedName(), @@ -96,10 +101,12 @@ public class GsonModule extends AbstractModule { }.getType(), byteListAdapter.nullSafe()); builder.registerTypeAdapter(byte[].class, byteArrayAdapter.nullSafe()); builder.registerTypeAdapter(JsonBall.class, jsonAdapter.nullSafe()); - builder.registerTypeAdapterFactory(new OptionalTypeAdapterFactory()); - builder.registerTypeAdapterFactory(new IgnoreNullSetTypeAdapterFactory()); - builder.registerTypeAdapterFactory(new IgnoreNullMapTypeAdapterFactory()); - builder.registerTypeAdapterFactory(new IgnoreNullMultimapTypeAdapterFactory()); + builder.registerTypeAdapterFactory(optional); + builder.registerTypeAdapterFactory(iterable); + builder.registerTypeAdapterFactory(set); + builder.registerTypeAdapterFactory(map); + builder.registerTypeAdapterFactory(multimap); + builder.registerTypeAdapterFactory(fluentIterable); AnnotationConstructorNamingStrategy deserializationPolicy = new AnnotationConstructorNamingStrategy( diff --git a/core/src/main/java/org/jclouds/json/internal/DeserializationConstructorAndReflectiveTypeAdapterFactory.java b/core/src/main/java/org/jclouds/json/internal/DeserializationConstructorAndReflectiveTypeAdapterFactory.java index 4da8913ecd..c6628a63f6 100644 --- a/core/src/main/java/org/jclouds/json/internal/DeserializationConstructorAndReflectiveTypeAdapterFactory.java +++ b/core/src/main/java/org/jclouds/json/internal/DeserializationConstructorAndReflectiveTypeAdapterFactory.java @@ -68,8 +68,8 @@ import com.google.gson.stream.JsonWriter; * new ExtractSerializedName(), new ExtractNamed()); * * deserializationStrategy = new AnnotationConstructorNamingStrategy( - * Collections.singleton(javax.inject.Inject.class), - * Collections.singleton(new ExtractNamed())); + * ImmutableSet.of(javax.inject.Inject.class), + * ImmutableSet.of(new ExtractNamed())); * * factory = new DeserializationConstructorAndReflectiveTypeAdapterFactory(new ConstructorConstructor(), * serializationStrategy, Excluder.DEFAULT, deserializationStrategy); diff --git a/core/src/main/java/org/jclouds/json/internal/IgnoreNullFluentIterableTypeAdapterFactory.java b/core/src/main/java/org/jclouds/json/internal/IgnoreNullFluentIterableTypeAdapterFactory.java new file mode 100644 index 0000000000..42d31e28e1 --- /dev/null +++ b/core/src/main/java/org/jclouds/json/internal/IgnoreNullFluentIterableTypeAdapterFactory.java @@ -0,0 +1,78 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.json.internal; + +import java.io.IOException; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; + +import com.google.common.collect.FluentIterable; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableList.Builder; +import com.google.gson.Gson; +import com.google.gson.TypeAdapter; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; + +/** + * Eliminates null values when deserializing FluentIterables + *

+ * Treats [null] as the empty set; [A, null] as [A]; etc. + * + * @author Adam Lowe + */ +public class IgnoreNullFluentIterableTypeAdapterFactory implements TypeAdapterFactory { + + @SuppressWarnings("unchecked") + public TypeAdapter create(Gson gson, TypeToken typeToken) { + Type type = typeToken.getType(); + if (typeToken.getRawType() != FluentIterable.class || !(type instanceof ParameterizedType)) { + return null; + } + + Type elementType = ((ParameterizedType) type).getActualTypeArguments()[0]; + TypeAdapter elementAdapter = gson.getAdapter(TypeToken.get(elementType)); + return (TypeAdapter) newFluentIterableAdapter(elementAdapter); + } + + protected TypeAdapter> newFluentIterableAdapter(final TypeAdapter elementAdapter) { + return new TypeAdapter>() { + public void write(JsonWriter out, FluentIterable value) throws IOException { + out.beginArray(); + for (E element : value) { + elementAdapter.write(out, element); + } + out.endArray(); + } + + public FluentIterable read(JsonReader in) throws IOException { + in.beginArray(); + Builder builder = ImmutableList.builder(); + while (in.hasNext()) { + E element = elementAdapter.read(in); + if (element != null) builder.add(element); + } + in.endArray(); + return FluentIterable.from(builder.build()); + } + }.nullSafe(); + } +} diff --git a/core/src/main/java/org/jclouds/json/internal/IgnoreNullIterableTypeAdapterFactory.java b/core/src/main/java/org/jclouds/json/internal/IgnoreNullIterableTypeAdapterFactory.java new file mode 100644 index 0000000000..f4c88fbadb --- /dev/null +++ b/core/src/main/java/org/jclouds/json/internal/IgnoreNullIterableTypeAdapterFactory.java @@ -0,0 +1,77 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.json.internal; + +import java.io.IOException; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableList.Builder; +import com.google.gson.Gson; +import com.google.gson.TypeAdapter; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; + +/** + * Eliminates null values when deserializing Iterables + *

+ * Treats [null] as the empty set; [A, null] as [A]; etc. + * + * @author Adam Lowe + */ +public class IgnoreNullIterableTypeAdapterFactory implements TypeAdapterFactory { + + @SuppressWarnings("unchecked") + public TypeAdapter create(Gson gson, TypeToken typeToken) { + Type type = typeToken.getType(); + if (typeToken.getRawType() != Iterable.class || !(type instanceof ParameterizedType)) { + return null; + } + + Type elementType = ((ParameterizedType) type).getActualTypeArguments()[0]; + TypeAdapter elementAdapter = gson.getAdapter(TypeToken.get(elementType)); + return (TypeAdapter) newIterableAdapter(elementAdapter); + } + + protected TypeAdapter> newIterableAdapter(final TypeAdapter elementAdapter) { + return new TypeAdapter>() { + public void write(JsonWriter out, Iterable value) throws IOException { + out.beginArray(); + for (E element : value) { + elementAdapter.write(out, element); + } + out.endArray(); + } + + public Iterable read(JsonReader in) throws IOException { + in.beginArray(); + Builder builder = ImmutableList.builder(); + while (in.hasNext()) { + E element = elementAdapter.read(in); + if (element != null) builder.add(element); + } + in.endArray(); + return builder.build(); + } + }.nullSafe(); + } +} diff --git a/core/src/main/java/org/jclouds/json/internal/IgnoreNullMapTypeAdapterFactory.java b/core/src/main/java/org/jclouds/json/internal/IgnoreNullMapTypeAdapterFactory.java index 7fcfb2b9d3..71d032f631 100644 --- a/core/src/main/java/org/jclouds/json/internal/IgnoreNullMapTypeAdapterFactory.java +++ b/core/src/main/java/org/jclouds/json/internal/IgnoreNullMapTypeAdapterFactory.java @@ -54,7 +54,7 @@ public class IgnoreNullMapTypeAdapterFactory implements TypeAdapterFactory { return (TypeAdapter) newMapAdapter(keyAdapter, valueAdapter); } - private TypeAdapter> newMapAdapter(final TypeAdapter keyAdapter, final TypeAdapter valueAdapter) { + protected TypeAdapter> newMapAdapter(final TypeAdapter keyAdapter, final TypeAdapter valueAdapter) { return new TypeAdapter>() { public void write(JsonWriter out, Map value) throws IOException { out.beginObject(); diff --git a/core/src/main/java/org/jclouds/json/internal/IgnoreNullMultimapTypeAdapterFactory.java b/core/src/main/java/org/jclouds/json/internal/IgnoreNullMultimapTypeAdapterFactory.java index 77938bda58..6a2827c407 100644 --- a/core/src/main/java/org/jclouds/json/internal/IgnoreNullMultimapTypeAdapterFactory.java +++ b/core/src/main/java/org/jclouds/json/internal/IgnoreNullMultimapTypeAdapterFactory.java @@ -51,10 +51,10 @@ public class IgnoreNullMultimapTypeAdapterFactory implements TypeAdapterFactory Type valueType = ((ParameterizedType) type).getActualTypeArguments()[1]; TypeAdapter keyAdapter = gson.getAdapter(TypeToken.get(keyType)); TypeAdapter valueAdapter = gson.getAdapter(TypeToken.get(valueType)); - return (TypeAdapter) newMapAdapter(keyAdapter, valueAdapter); + return (TypeAdapter) newMultimapAdapter(keyAdapter, valueAdapter); } - private TypeAdapter> newMapAdapter(final TypeAdapter keyAdapter, final TypeAdapter valueAdapter) { + protected TypeAdapter> newMultimapAdapter(final TypeAdapter keyAdapter, final TypeAdapter valueAdapter) { return new TypeAdapter>() { public void write(JsonWriter out, Multimap map) throws IOException { out.beginObject(); diff --git a/core/src/main/java/org/jclouds/json/internal/IgnoreNullSetTypeAdapterFactory.java b/core/src/main/java/org/jclouds/json/internal/IgnoreNullSetTypeAdapterFactory.java index 393a710f3a..1ae22c367f 100644 --- a/core/src/main/java/org/jclouds/json/internal/IgnoreNullSetTypeAdapterFactory.java +++ b/core/src/main/java/org/jclouds/json/internal/IgnoreNullSetTypeAdapterFactory.java @@ -23,7 +23,7 @@ import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.Set; -import com.google.common.collect.Sets; +import com.google.common.collect.ImmutableSet; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapterFactory; @@ -32,7 +32,7 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; /** - * Eliminates null values when deserializing Sets + * Eliminates null values when deserializing Sets. *

* Treats [null] as the empty set; [A, null] as [A]; etc. * @@ -52,7 +52,7 @@ public class IgnoreNullSetTypeAdapterFactory implements TypeAdapterFactory { return (TypeAdapter) newSetAdapter(elementAdapter); } - private TypeAdapter> newSetAdapter(final TypeAdapter elementAdapter) { + protected TypeAdapter> newSetAdapter(final TypeAdapter elementAdapter) { return new TypeAdapter>() { public void write(JsonWriter out, Set value) throws IOException { out.beginArray(); @@ -63,14 +63,15 @@ public class IgnoreNullSetTypeAdapterFactory implements TypeAdapterFactory { } public Set read(JsonReader in) throws IOException { - Set result = Sets.newLinkedHashSet(); + ImmutableSet.Builder result = ImmutableSet. builder(); in.beginArray(); while (in.hasNext()) { E element = elementAdapter.read(in); - if (element != null) result.add(element); + if (element != null) + result.add(element); } in.endArray(); - return result; + return result.build(); } }.nullSafe(); } diff --git a/core/src/main/java/org/jclouds/json/internal/OptionalTypeAdapterFactory.java b/core/src/main/java/org/jclouds/json/internal/OptionalTypeAdapterFactory.java index 1855e8e7db..0e57f8eaaf 100644 --- a/core/src/main/java/org/jclouds/json/internal/OptionalTypeAdapterFactory.java +++ b/core/src/main/java/org/jclouds/json/internal/OptionalTypeAdapterFactory.java @@ -48,10 +48,10 @@ public class OptionalTypeAdapterFactory implements TypeAdapterFactory { Type elementType = ((ParameterizedType) type).getActualTypeArguments()[0]; TypeAdapter elementAdapter = gson.getAdapter(TypeToken.get(elementType)); - return (TypeAdapter) newMultisetAdapter(elementAdapter); + return (TypeAdapter) newOptionalAdapter(elementAdapter); } - private TypeAdapter> newMultisetAdapter( + protected TypeAdapter> newOptionalAdapter( final TypeAdapter elementAdapter) { return new TypeAdapter>() { public void write(JsonWriter out, Optional value) throws IOException { diff --git a/core/src/main/java/org/jclouds/location/suppliers/derived/RegionIdsFromRegionIdToURIKeySet.java b/core/src/main/java/org/jclouds/location/suppliers/derived/RegionIdsFromRegionIdToURIKeySet.java index 6808ae5a13..c0e1bc4481 100644 --- a/core/src/main/java/org/jclouds/location/suppliers/derived/RegionIdsFromRegionIdToURIKeySet.java +++ b/core/src/main/java/org/jclouds/location/suppliers/derived/RegionIdsFromRegionIdToURIKeySet.java @@ -18,6 +18,7 @@ */ package org.jclouds.location.suppliers.derived; +import java.lang.reflect.UndeclaredThrowableException; import java.net.URI; import java.util.Map; import java.util.Set; @@ -28,6 +29,7 @@ import org.jclouds.location.Region; import org.jclouds.location.suppliers.RegionIdsSupplier; import com.google.common.base.Supplier; +import com.google.common.base.Throwables; import com.google.inject.Inject; /** @@ -45,6 +47,10 @@ public class RegionIdsFromRegionIdToURIKeySet implements RegionIdsSupplier { @Override public Set get() { - return regionIdToURISupplier.get().keySet(); + try { + return regionIdToURISupplier.get().keySet(); + } catch (UndeclaredThrowableException e) { + throw Throwables.propagate(e.getCause()); + } } } \ No newline at end of file diff --git a/core/src/main/java/org/jclouds/osgi/MetadataBundleListener.java b/core/src/main/java/org/jclouds/osgi/MetadataBundleListener.java index 07cbf585c4..32b2a3dac4 100644 --- a/core/src/main/java/org/jclouds/osgi/MetadataBundleListener.java +++ b/core/src/main/java/org/jclouds/osgi/MetadataBundleListener.java @@ -18,6 +18,8 @@ */ package org.jclouds.osgi; +import com.google.common.base.Charsets; + import org.jclouds.apis.ApiMetadata; import org.jclouds.apis.ApiRegistry; import org.jclouds.providers.ProviderMetadata; @@ -158,7 +160,7 @@ public class MetadataBundleListener implements BundleListener { try { is = resource.openStream(); - reader = new InputStreamReader(is, "UTF-8"); + reader = new InputStreamReader(is, Charsets.UTF_8); bufferedReader = new BufferedReader(reader); String line; while ((line = bufferedReader.readLine()) != null) { diff --git a/core/src/main/java/org/jclouds/predicates/RetryablePredicate.java b/core/src/main/java/org/jclouds/predicates/RetryablePredicate.java index 79d142b1ef..d607589c76 100644 --- a/core/src/main/java/org/jclouds/predicates/RetryablePredicate.java +++ b/core/src/main/java/org/jclouds/predicates/RetryablePredicate.java @@ -44,6 +44,9 @@ import com.google.common.base.Predicate; * @author Adrian Cole */ public class RetryablePredicate implements Predicate { + public static final long DEFAULT_PERIOD = 50l; + public static final long DEFAULT_MAX_PERIOD = 1000l; + private final long maxWait; private final long period; private final long maxPeriod; @@ -63,8 +66,12 @@ public class RetryablePredicate implements Predicate { this(predicate, maxWait, period, period * 10l, unit); } + public RetryablePredicate(Predicate predicate, long maxWait, long period, long maxPeriod) { + this(predicate, maxWait, period, maxPeriod, TimeUnit.MILLISECONDS); + } + public RetryablePredicate(Predicate predicate, long maxWait) { - this(predicate, maxWait, 50l, 1000l, TimeUnit.MILLISECONDS); + this(predicate, maxWait, DEFAULT_PERIOD, DEFAULT_MAX_PERIOD, TimeUnit.MILLISECONDS); } @Override diff --git a/core/src/main/java/org/jclouds/rest/config/RestModule.java b/core/src/main/java/org/jclouds/rest/config/RestModule.java index 99e12558b8..d7c0fa9090 100644 --- a/core/src/main/java/org/jclouds/rest/config/RestModule.java +++ b/core/src/main/java/org/jclouds/rest/config/RestModule.java @@ -20,6 +20,7 @@ package org.jclouds.rest.config; import static org.jclouds.Constants.PROPERTY_TIMEOUTS_PREFIX; +import java.lang.reflect.Method; import java.net.URI; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; @@ -46,6 +47,7 @@ import org.jclouds.rest.HttpClient; import org.jclouds.rest.binders.BindToJsonPayloadWrappedWith; import org.jclouds.rest.internal.AsyncRestClientProxy; import org.jclouds.rest.internal.RestAnnotationProcessor; +import org.jclouds.rest.internal.RestAnnotationProcessor.MethodKey; import org.jclouds.rest.internal.SeedAnnotationCache; import org.jclouds.util.Maps2; import org.jclouds.util.Predicates2; @@ -53,6 +55,7 @@ import org.jclouds.util.Predicates2; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.base.Supplier; +import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; @@ -107,7 +110,19 @@ public class RestModule extends AbstractModule { }).to(FilterStringsBoundToInjectorByName.class); installLocations(); } - + + /** + * Shared for all types of rest clients. this is read-only in this class, and + * currently populated only by {@link SeedAnnotationCache} + * + * @see SeedAnnotationCache + */ + @Provides + @Singleton + protected Cache delegationMap(){ + return CacheBuilder.newBuilder().build(); + } + @Provides @Singleton @Named("TIMEOUTS") diff --git a/core/src/main/java/org/jclouds/rest/functions/ReturnEmptyFluentIterableOnNotFoundOr404.java b/core/src/main/java/org/jclouds/rest/functions/ReturnEmptyFluentIterableOnNotFoundOr404.java new file mode 100644 index 0000000000..b2711c5109 --- /dev/null +++ b/core/src/main/java/org/jclouds/rest/functions/ReturnEmptyFluentIterableOnNotFoundOr404.java @@ -0,0 +1,59 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.rest.functions; + +import static com.google.common.base.Preconditions.checkNotNull; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.http.functions.ReturnTrueOn404; +import org.jclouds.rest.ResourceNotFoundException; + +import com.google.common.base.Function; +import com.google.common.base.Throwables; +import com.google.common.collect.FluentIterable; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Iterables; + +/** + * + * @author Adrian Cole + */ +@Singleton +public class ReturnEmptyFluentIterableOnNotFoundOr404 implements Function { + private final ReturnTrueOn404 rto404; + + @Inject + private ReturnEmptyFluentIterableOnNotFoundOr404(ReturnTrueOn404 rto404) { + this.rto404 = checkNotNull(rto404, "rto404"); + } + + public Object apply(Exception from) { + Iterable throwables = Iterables.filter(Throwables.getCausalChain(from), + ResourceNotFoundException.class); + if (Iterables.size(throwables) >= 1) { + return FluentIterable.from(ImmutableSet.of()); + } else if (rto404.apply(from)) { + return FluentIterable.from(ImmutableSet.of()); + } + throw Throwables.propagate(from); + } + +} diff --git a/core/src/main/java/org/jclouds/rest/functions/ReturnEmptyIterableWithMarkerOnNotFoundOr404.java b/core/src/main/java/org/jclouds/rest/functions/ReturnEmptyIterableWithMarkerOnNotFoundOr404.java new file mode 100644 index 0000000000..ff5cbeafd6 --- /dev/null +++ b/core/src/main/java/org/jclouds/rest/functions/ReturnEmptyIterableWithMarkerOnNotFoundOr404.java @@ -0,0 +1,58 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.rest.functions; + +import static com.google.common.base.Preconditions.checkNotNull; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.collect.IterableWithMarkers; +import org.jclouds.http.functions.ReturnTrueOn404; +import org.jclouds.rest.ResourceNotFoundException; + +import com.google.common.base.Function; +import com.google.common.base.Throwables; +import com.google.common.collect.Iterables; + +/** + * + * @author Adrian Cole + */ +@Singleton +public class ReturnEmptyIterableWithMarkerOnNotFoundOr404 implements Function { + private final ReturnTrueOn404 rto404; + + @Inject + private ReturnEmptyIterableWithMarkerOnNotFoundOr404(ReturnTrueOn404 rto404) { + this.rto404 = checkNotNull(rto404, "rto404"); + } + + public Object apply(Exception from) { + Iterable throwables = Iterables.filter(Throwables.getCausalChain(from), + ResourceNotFoundException.class); + if (Iterables.size(throwables) >= 1) { + return IterableWithMarkers.EMPTY; + } else if (rto404.apply(from)) { + return IterableWithMarkers.EMPTY; + } + throw Throwables.propagate(from); + } + +} diff --git a/core/src/main/java/org/jclouds/rest/functions/ReturnEmptyListOnNotFoundOr404.java b/core/src/main/java/org/jclouds/rest/functions/ReturnEmptyListOnNotFoundOr404.java index e7ad30afcd..46ed693cb7 100644 --- a/core/src/main/java/org/jclouds/rest/functions/ReturnEmptyListOnNotFoundOr404.java +++ b/core/src/main/java/org/jclouds/rest/functions/ReturnEmptyListOnNotFoundOr404.java @@ -20,8 +20,6 @@ package org.jclouds.rest.functions; import static com.google.common.base.Preconditions.checkNotNull; -import java.util.List; - import javax.inject.Inject; import javax.inject.Singleton; diff --git a/core/src/main/java/org/jclouds/rest/functions/ReturnEmptyMapOnNotFoundOr404.java b/core/src/main/java/org/jclouds/rest/functions/ReturnEmptyMapOnNotFoundOr404.java index 156abab47f..50f37c9e8d 100644 --- a/core/src/main/java/org/jclouds/rest/functions/ReturnEmptyMapOnNotFoundOr404.java +++ b/core/src/main/java/org/jclouds/rest/functions/ReturnEmptyMapOnNotFoundOr404.java @@ -20,8 +20,6 @@ package org.jclouds.rest.functions; import static com.google.common.base.Preconditions.checkNotNull; -import java.util.Map; - import javax.inject.Inject; import javax.inject.Singleton; diff --git a/core/src/main/java/org/jclouds/rest/functions/ReturnEmptyMultimapOnNotFoundOr404.java b/core/src/main/java/org/jclouds/rest/functions/ReturnEmptyMultimapOnNotFoundOr404.java index 763190cce4..9f365d1627 100644 --- a/core/src/main/java/org/jclouds/rest/functions/ReturnEmptyMultimapOnNotFoundOr404.java +++ b/core/src/main/java/org/jclouds/rest/functions/ReturnEmptyMultimapOnNotFoundOr404.java @@ -30,7 +30,6 @@ import com.google.common.base.Function; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.Iterables; -import com.google.common.collect.Multimap; /** * diff --git a/core/src/main/java/org/jclouds/rest/functions/ReturnEmptyPagedIterableOnNotFoundOr404.java b/core/src/main/java/org/jclouds/rest/functions/ReturnEmptyPagedIterableOnNotFoundOr404.java new file mode 100644 index 0000000000..48905ab413 --- /dev/null +++ b/core/src/main/java/org/jclouds/rest/functions/ReturnEmptyPagedIterableOnNotFoundOr404.java @@ -0,0 +1,58 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.rest.functions; + +import static com.google.common.base.Preconditions.checkNotNull; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.collect.PagedIterables; +import org.jclouds.http.functions.ReturnTrueOn404; +import org.jclouds.rest.ResourceNotFoundException; + +import com.google.common.base.Function; +import com.google.common.base.Throwables; +import com.google.common.collect.Iterables; + +/** + * + * @author Adrian Cole + */ +@Singleton +public class ReturnEmptyPagedIterableOnNotFoundOr404 implements Function { + private final ReturnTrueOn404 rto404; + + @Inject + private ReturnEmptyPagedIterableOnNotFoundOr404(ReturnTrueOn404 rto404) { + this.rto404 = checkNotNull(rto404, "rto404"); + } + + public Object apply(Exception from) { + Iterable throwables = Iterables.filter(Throwables.getCausalChain(from), + ResourceNotFoundException.class); + if (Iterables.size(throwables) >= 1) { + return PagedIterables.EMPTY; + } else if (rto404.apply(from)) { + return PagedIterables.EMPTY; + } + throw Throwables.propagate(from); + } + +} diff --git a/core/src/main/java/org/jclouds/rest/functions/ReturnEmptySetOnNotFoundOr404.java b/core/src/main/java/org/jclouds/rest/functions/ReturnEmptySetOnNotFoundOr404.java index cdd6615f17..b8be87efba 100644 --- a/core/src/main/java/org/jclouds/rest/functions/ReturnEmptySetOnNotFoundOr404.java +++ b/core/src/main/java/org/jclouds/rest/functions/ReturnEmptySetOnNotFoundOr404.java @@ -20,8 +20,6 @@ package org.jclouds.rest.functions; import static com.google.common.base.Preconditions.checkNotNull; -import java.util.Set; - import javax.inject.Inject; import javax.inject.Singleton; diff --git a/core/src/main/java/org/jclouds/rest/internal/AsyncRestClientProxy.java b/core/src/main/java/org/jclouds/rest/internal/AsyncRestClientProxy.java index b670359028..5732010210 100644 --- a/core/src/main/java/org/jclouds/rest/internal/AsyncRestClientProxy.java +++ b/core/src/main/java/org/jclouds/rest/internal/AsyncRestClientProxy.java @@ -22,7 +22,6 @@ import java.lang.annotation.Annotation; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Type; -import java.util.NoSuchElementException; import java.util.concurrent.ExecutionException; import javax.annotation.Resource; @@ -49,12 +48,14 @@ import com.google.common.base.Function; import com.google.common.base.Optional; import com.google.common.base.Predicate; import com.google.common.base.Supplier; +import com.google.common.base.Throwables; import com.google.common.cache.LoadingCache; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.inject.Binding; +import com.google.inject.ConfigurationException; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Key; @@ -176,8 +177,10 @@ public class AsyncRestClientProxy implements InvocationHandler { try { Annotation qualifier = Iterables.find(ImmutableList.copyOf(method.getAnnotations()), isQualifierPresent); return getInstanceOfTypeWithQualifier(genericReturnType, qualifier); - } catch (NoSuchElementException e) { - return getInstanceOfType(genericReturnType); + } catch (ProvisionException e) { + throw Throwables.propagate(e.getCause()); + } catch (RuntimeException e) { + return instanceOfTypeOrPropagate(genericReturnType, e); } } catch (ProvisionException e) { AuthorizationException aex = Throwables2.getFirstThrowableOfType(e, AuthorizationException.class); @@ -188,19 +191,23 @@ public class AsyncRestClientProxy implements InvocationHandler { } // TODO: tidy - private Object getInstanceOfType(Type genericReturnType) { - // look for an existing binding - Binding binding = injector.getExistingBinding(Key.get(genericReturnType)); - if (binding != null) - return binding.getProvider().get(); + private Object instanceOfTypeOrPropagate(Type genericReturnType, RuntimeException e) { + try { + // look for an existing binding + Binding binding = injector.getExistingBinding(Key.get(genericReturnType)); + if (binding != null) + return binding.getProvider().get(); - // then, try looking via supplier - binding = injector.getExistingBinding(Key.get(Types.newParameterizedType(Supplier.class, genericReturnType))); - if (binding != null) - return Supplier.class.cast(binding.getProvider().get()).get(); + // then, try looking via supplier + binding = injector.getExistingBinding(Key.get(Types.newParameterizedType(Supplier.class, genericReturnType))); + if (binding != null) + return Supplier.class.cast(binding.getProvider().get()).get(); - // else try to create an instance - return injector.getInstance(Key.get(genericReturnType)); + // else try to create an instance + return injector.getInstance(Key.get(genericReturnType)); + } catch (ConfigurationException ce) { + throw e; + } } // TODO: tidy diff --git a/core/src/main/java/org/jclouds/rest/internal/RestAnnotationProcessor.java b/core/src/main/java/org/jclouds/rest/internal/RestAnnotationProcessor.java index 215821a815..d01dbdd0be 100644 --- a/core/src/main/java/org/jclouds/rest/internal/RestAnnotationProcessor.java +++ b/core/src/main/java/org/jclouds/rest/internal/RestAnnotationProcessor.java @@ -43,7 +43,6 @@ import java.lang.reflect.Type; import java.lang.reflect.WildcardType; import java.net.URI; import java.util.Collection; -import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; @@ -140,11 +139,13 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Function; import com.google.common.base.Functions; import com.google.common.base.Objects; +import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.base.Supplier; import com.google.common.base.Throwables; +import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; @@ -167,7 +168,7 @@ import com.google.inject.util.Types; /** * Creates http methods based on annotations on a class or interface. - * + * * @author Adrian Cole */ public class RestAnnotationProcessor { @@ -190,18 +191,8 @@ public class RestAnnotationProcessor { static final LoadingCache>> methodToIndexOfParamToPostParamAnnotations = createMethodToIndexOfParamToAnnotation(PayloadParam.class); static final LoadingCache>> methodToIndexOfParamToPartParamAnnotations = createMethodToIndexOfParamToAnnotation(PartParam.class); static final LoadingCache>> methodToIndexOfParamToParamParserAnnotations = createMethodToIndexOfParamToAnnotation(ParamParser.class); - - /** - * Shared for all types of rest clients. this is read-only in this class, and - * currently populated only by {@link SeedAnnotationCache} - * - * @see SeedAnnotationCache - */ - // TODO: change this to a private final LoadingCache - // supplied by guice. The CacheLoader can be refactored - // out from SeedAnnotationCache. Potentially, preseed the cache, but only if - // this is uncomplicated. - static final Map delegationMap = newHashMap(); + + final Cache delegationMap; static LoadingCache>> createMethodToIndexOfParamToAnnotation( final Class annotation) { @@ -330,7 +321,7 @@ public class RestAnnotationProcessor { @SuppressWarnings("unchecked") @Inject - public RestAnnotationProcessor(Injector injector, LoadingCache, Boolean> seedAnnotationCache, + public RestAnnotationProcessor(Injector injector, LoadingCache, Boolean> seedAnnotationCache, Cache delegationMap, @ApiVersion String apiVersion, @BuildVersion String buildVersion, ParseSax.Factory parserFactory, HttpUtils utils, ContentMetadataCodec contentMetadataCodec, TypeLiteral typeLiteral) throws ExecutionException { this.declaring = (Class) typeLiteral.getRawType(); @@ -341,6 +332,7 @@ public class RestAnnotationProcessor { this.uriBuilderProvider = injector.getProvider(UriBuilder.class); this.seedAnnotationCache = seedAnnotationCache; seedAnnotationCache.get(declaring); + this.delegationMap = delegationMap; if (declaring.isAnnotationPresent(SkipEncoding.class)) { skips = declaring.getAnnotation(SkipEncoding.class).value(); } else { @@ -350,8 +342,9 @@ public class RestAnnotationProcessor { this.buildVersion = buildVersion; } + public Method getDelegateOrNull(Method in) { - return delegationMap.get(new MethodKey(in)); + return delegationMap.getIfPresent(new MethodKey(in)); } public static class MethodKey { @@ -370,7 +363,7 @@ public class RestAnnotationProcessor { && Objects.equal(this.name, that.name) && Objects.equal(this.parametersTypeHashCode, that.parametersTypeHashCode); } - + private final String name; private final int parametersTypeHashCode; private final Class declaringClass; @@ -844,7 +837,7 @@ public class RestAnnotationProcessor { Type returnVal = getReturnTypeForMethod(method); return getJsonParserKeyForMethodAnType(method, returnVal); } - + @SuppressWarnings("unchecked") public static Key> getJAXBParserKeyForMethod(Method method) { Type returnVal = getReturnTypeForMethod(method); @@ -1014,7 +1007,7 @@ public class RestAnnotationProcessor { Annotation[] annotations = request.getJavaMethod().getParameterAnnotations()[entry.getKey()]; for (Annotation a : annotations) { - if (Nullable.class.isAssignableFrom(a.annotationType())) + if (NULLABLE.apply(a)) continue OUTER; } Preconditions.checkNotNull(null, request.getJavaMethod().getName() + " parameter " + (entry.getKey() + 1)); @@ -1093,7 +1086,7 @@ public class RestAnnotationProcessor { } private static List getAcceptHeadersOrNull(Method method) { - List accept = Collections.emptyList(); + List accept = ImmutableList.of(); if (method.getDeclaringClass().isAnnotationPresent(Consumes.class)) { Consumes header = method.getDeclaringClass().getAnnotation(Consumes.class); accept = asList(header.value()); @@ -1188,17 +1181,11 @@ public class RestAnnotationProcessor { for (Annotation key : entry.getValue()) { Set extractors = indexToParamExtractor.get(entry.getKey()); String paramKey = ((PathParam) key).value(); - String paramValue; - if (extractors != null && extractors.size() > 0) { - ParamParser extractor = (ParamParser) extractors.iterator().next(); - paramValue = injector.getInstance(extractor.value()).apply(args[entry.getKey()]); - } else { - paramValue = args[entry.getKey()].toString(); - } - pathParamValues.put(paramKey, paramValue); + Optional paramValue = getParamValue(method, args, extractors, entry, paramKey); + if (paramValue.isPresent()) + pathParamValues.put(paramKey, paramValue.get().toString()); } } - if (method.isAnnotationPresent(PathParam.class) && method.isAnnotationPresent(ParamParser.class)) { String paramKey = method.getAnnotation(PathParam.class).value(); String paramValue = injector.getInstance(method.getAnnotation(ParamParser.class).value()).apply(args); @@ -1208,6 +1195,42 @@ public class RestAnnotationProcessor { return pathParamValues; } + protected Optional getParamValue(Method method, Object[] args, Set extractors, + Entry> entry, String paramKey) { + Integer argIndex = entry.getKey(); + Object arg = args[argIndex]; + if (extractors != null && extractors.size() > 0 && checkPresentOrNullable(method, paramKey, argIndex, arg)) { + ParamParser extractor = (ParamParser) extractors.iterator().next(); + // ParamParsers can deal with nullable parameters + arg = injector.getInstance(extractor.value()).apply(arg); + } + checkPresentOrNullable(method, paramKey, argIndex, arg); + return Optional.fromNullable(arg); + } + + private static boolean checkPresentOrNullable(Method method, String paramKey, Integer argIndex, Object arg) { + if (arg == null && !argNullable(method, argIndex)) + throw new NullPointerException(String.format("param{%s} for method %s.%s", paramKey, method + .getDeclaringClass().getSimpleName(), method.getName())); + return true; + } + + private static boolean argNullable(Method method, Integer argIndex) { + return containsNullable(method.getParameterAnnotations()[argIndex]); + } + + private static final Predicate NULLABLE = new Predicate() { + + @Override + public boolean apply(Annotation in) { + return Nullable.class.isAssignableFrom(in.annotationType()); + } + }; + + private static boolean containsNullable(Annotation[] annotations) { + return Iterables.any(ImmutableSet.copyOf(annotations), NULLABLE); + } + private Multimap encodeValues(Multimap unencoded, char... skips) { Multimap encoded = LinkedHashMultimap.create(); for (Entry entry : unencoded.entries()) { @@ -1226,14 +1249,9 @@ public class RestAnnotationProcessor { for (Annotation key : entry.getValue()) { Set extractors = indexToParamExtractor.get(entry.getKey()); String paramKey = ((MatrixParam) key).value(); - String paramValue; - if (extractors != null && extractors.size() > 0) { - ParamParser extractor = (ParamParser) extractors.iterator().next(); - paramValue = injector.getInstance(extractor.value()).apply(args[entry.getKey()]); - } else { - paramValue = args[entry.getKey()].toString(); - } - matrixParamValues.put(paramKey, paramValue); + Optional paramValue = getParamValue(method, args, extractors, entry, paramKey); + if (paramValue.isPresent()) + matrixParamValues.put(paramKey, paramValue.get().toString()); } } @@ -1257,16 +1275,9 @@ public class RestAnnotationProcessor { for (Annotation key : entry.getValue()) { Set extractors = indexToParamExtractor.get(entry.getKey()); String paramKey = ((FormParam) key).value(); - String paramValue; - if (extractors != null && extractors.size() > 0) { - ParamParser extractor = (ParamParser) extractors.iterator().next(); - paramValue = injector.getInstance(extractor.value()).apply(args[entry.getKey()]); - } else { - Object pvo = args[entry.getKey()]; - Preconditions.checkNotNull(pvo, paramKey); - paramValue = pvo.toString(); - } - formParamValues.put(paramKey, paramValue); + Optional paramValue = getParamValue(method, args, extractors, entry, paramKey); + if (paramValue.isPresent()) + formParamValues.put(paramKey, paramValue.get().toString()); } } @@ -1289,16 +1300,9 @@ public class RestAnnotationProcessor { for (Annotation key : entry.getValue()) { Set extractors = indexToParamExtractor.get(entry.getKey()); String paramKey = ((QueryParam) key).value(); - Object paramValue; - if (extractors != null && extractors.size() > 0) { - ParamParser extractor = (ParamParser) extractors.iterator().next(); - paramValue = injector.getInstance(extractor.value()).apply(args[entry.getKey()]); - } else { - paramValue = args[entry.getKey()]; - } - if (paramValue != null) { - queryParamValues.put(paramKey, paramValue.toString()); - } + Optional paramValue = getParamValue(method, args, extractors, entry, paramKey); + if (paramValue.isPresent()) + queryParamValues.put(paramKey, paramValue.get().toString()); } } @@ -1321,18 +1325,18 @@ public class RestAnnotationProcessor { for (Annotation key : entry.getValue()) { Set extractors = indexToParamExtractor.get(entry.getKey()); String paramKey = ((PayloadParam) key).value(); - Object paramValue; - if (extractors != null && extractors.size() > 0) { - ParamParser extractor = (ParamParser) extractors.iterator().next(); - paramValue = injector.getInstance(extractor.value()).apply(args[entry.getKey()]); - } else { - paramValue = args[entry.getKey()] != null ? args[entry.getKey()] : null; - } - postParams.put(paramKey, paramValue); - + Optional paramValue = getParamValue(method, args, extractors, entry, paramKey); + if (paramValue.isPresent()) + postParams.put(paramKey, paramValue.get()); } } return postParams; } + /** + * the class that is being processed + */ + public Class getDeclaring(){ + return declaring; + } } diff --git a/core/src/main/java/org/jclouds/rest/internal/RestContextImpl.java b/core/src/main/java/org/jclouds/rest/internal/RestContextImpl.java index c592d98809..ed78b52328 100644 --- a/core/src/main/java/org/jclouds/rest/internal/RestContextImpl.java +++ b/core/src/main/java/org/jclouds/rest/internal/RestContextImpl.java @@ -22,6 +22,7 @@ import static com.google.common.base.Preconditions.checkNotNull; import javax.inject.Inject; +import org.jclouds.annotations.Name; import org.jclouds.internal.ContextImpl; import org.jclouds.lifecycle.Closer; import org.jclouds.providers.ProviderMetadata; @@ -44,9 +45,9 @@ public class RestContextImpl extends ContextImpl implements RestContext syncApi, TypeLiteral asyncApi) { - super(providerMetadata, identity, utils, closer); + super(name, providerMetadata, identity, utils, closer); checkNotNull(injector, "injector"); this.asyncApi = injector.getInstance(Key.get(checkNotNull(asyncApi, "asyncApi"))); this.syncApi = injector.getInstance(Key.get(checkNotNull(syncApi, "syncApi"))); diff --git a/core/src/main/java/org/jclouds/rest/internal/SeedAnnotationCache.java b/core/src/main/java/org/jclouds/rest/internal/SeedAnnotationCache.java index 486bf6f988..6318c24bcc 100644 --- a/core/src/main/java/org/jclouds/rest/internal/SeedAnnotationCache.java +++ b/core/src/main/java/org/jclouds/rest/internal/SeedAnnotationCache.java @@ -19,7 +19,6 @@ package org.jclouds.rest.internal; import static com.google.common.collect.Sets.difference; -import static org.jclouds.rest.internal.RestAnnotationProcessor.delegationMap; import static org.jclouds.rest.internal.RestAnnotationProcessor.getHttpMethods; import static org.jclouds.rest.internal.RestAnnotationProcessor.methodToIndexOfParamToBinderParamAnnotation; import static org.jclouds.rest.internal.RestAnnotationProcessor.methodToIndexOfParamToEndpointAnnotations; @@ -48,6 +47,7 @@ import org.jclouds.rest.RestContext; import org.jclouds.rest.annotations.Delegate; import org.jclouds.rest.internal.RestAnnotationProcessor.MethodKey; +import com.google.common.cache.Cache; import com.google.common.cache.CacheLoader; import com.google.common.collect.ImmutableSet; import com.google.inject.Inject; @@ -68,10 +68,12 @@ public class SeedAnnotationCache extends CacheLoader, Boolean> { protected Logger logger = Logger.NULL; protected final Injector injector; + protected final Cache delegationMap; @Inject - public SeedAnnotationCache(Injector injector) { + public SeedAnnotationCache(Injector injector, Cache delegationMap) { this.injector = injector; + this.delegationMap = delegationMap; } @Override diff --git a/core/src/test/java/org/jclouds/ContextBuilderTest.java b/core/src/test/java/org/jclouds/ContextBuilderTest.java index 4d9ea2788e..a7b55ff3ae 100644 --- a/core/src/test/java/org/jclouds/ContextBuilderTest.java +++ b/core/src/test/java/org/jclouds/ContextBuilderTest.java @@ -40,6 +40,8 @@ import org.jclouds.logging.jdk.config.JDKLoggingModule; import org.jclouds.providers.AnonymousProviderMetadata; import org.jclouds.providers.ProviderMetadata; import org.jclouds.rest.ConfiguresRestClient; +import org.jclouds.rest.annotations.ApiVersion; +import org.jclouds.rest.annotations.Identity; import org.jclouds.rest.config.CredentialStoreModule; import org.testng.annotations.Test; @@ -82,6 +84,14 @@ public class ContextBuilderTest { assertEquals(endpoint, URI.create("http://foo.service.com")); } + @Test + public void testContextName() { + ContextBuilder withNoName = testContextBuilder().endpoint("http://${jclouds.identity}.service.com").name("mytest") + .credentials("foo", "bar"); + Context context = withNoName.build(); + assertEquals(context.getName(), "mytest"); + } + @Test public void testProviderMetadataBoundWithCorrectEndpoint() { ContextBuilder withVariablesToReplace = testContextBuilder().endpoint("http://${jclouds.identity}.service.com") @@ -99,6 +109,24 @@ public class ContextBuilderTest { assertEquals(codes, ImmutableSet. of()); } + @Test + public void testProviderMetadataWithCredentialsSetViaProperty() { + Properties overrides = new Properties(); + overrides.setProperty(Constants.PROPERTY_IDENTITY, "foo"); + overrides.setProperty(Constants.PROPERTY_CREDENTIAL, "BAR"); + ContextBuilder withCredsInProps = testContextBuilder().overrides(overrides); + String identity = withCredsInProps.buildInjector().getInstance(Key.get(String.class, Identity.class)); + assertEquals(identity, "foo"); + } + + @Test + public void testProviderMetadataWithVersionSetViaProperty() { + Properties overrides = new Properties(); + overrides.setProperty(Constants.PROPERTY_API_VERSION, "1.1"); + ContextBuilder withVersionInProps = testContextBuilder().overrides(overrides); + String version = withVersionInProps.buildInjector().getInstance(Key.get(String.class, ApiVersion.class)); + assertEquals(version, "1.1"); + } @Test public void testAddHttpModuleIfNotPresent() { diff --git a/core/src/test/java/org/jclouds/cache/RetryingCacheLoaderDecoratorTest.java b/core/src/test/java/org/jclouds/cache/RetryingCacheLoaderDecoratorTest.java index 38c52aa7a8..4325dacb05 100644 --- a/core/src/test/java/org/jclouds/cache/RetryingCacheLoaderDecoratorTest.java +++ b/core/src/test/java/org/jclouds/cache/RetryingCacheLoaderDecoratorTest.java @@ -24,7 +24,7 @@ import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; import static org.testng.Assert.assertSame; -import static org.testng.Assert.assertTrue; +import static org.testng.Assert.fail; import org.jclouds.rest.ResourceNotFoundException; import org.testng.annotations.BeforeMethod; @@ -76,10 +76,10 @@ public class RetryingCacheLoaderDecoratorTest { replay(mock); try { backoff.load("foo"); - assertTrue(false); + fail(); } catch (ResourceNotFoundException e) { } verify(mock); } -} \ No newline at end of file +} diff --git a/core/src/test/java/org/jclouds/cache/internal/BackoffExponentiallyAndRetryOnThrowableCacheLoaderTest.java b/core/src/test/java/org/jclouds/cache/internal/BackoffExponentiallyAndRetryOnThrowableCacheLoaderTest.java index 0b0517aef2..c47314b3fe 100644 --- a/core/src/test/java/org/jclouds/cache/internal/BackoffExponentiallyAndRetryOnThrowableCacheLoaderTest.java +++ b/core/src/test/java/org/jclouds/cache/internal/BackoffExponentiallyAndRetryOnThrowableCacheLoaderTest.java @@ -23,7 +23,10 @@ import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; import static org.testng.Assert.assertSame; -import static org.testng.Assert.assertTrue; +import static org.testng.Assert.fail; + +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeoutException; import org.jclouds.rest.ResourceNotFoundException; import org.testng.annotations.BeforeMethod; @@ -67,10 +70,28 @@ public class BackoffExponentiallyAndRetryOnThrowableCacheLoaderTest { replay(mock); try { backoff.load("foo"); - assertTrue(false); + fail(); } catch (ResourceNotFoundException e) { } verify(mock); } -} \ No newline at end of file + + @Test + void testThrowsTimeoutException() throws Exception { + int attempts = 3; + BackoffExponentiallyAndRetryOnThrowableCacheLoader backoff = new BackoffExponentiallyAndRetryOnThrowableCacheLoader( + ResourceNotFoundException.class, 50l, 500l, attempts, mock); + + expect(mock.load("foo")).andThrow(new ExecutionException(new TimeoutException())); + + replay(mock); + try { + backoff.load("foo"); + fail(); + } catch (TimeoutException e) { + + } + verify(mock); + } +} diff --git a/core/src/test/java/org/jclouds/cache/internal/BackoffExponentiallyAndRetryOnThrowableCallableTest.java b/core/src/test/java/org/jclouds/cache/internal/BackoffExponentiallyAndRetryOnThrowableCallableTest.java index 4e370a6109..a206d52a89 100644 --- a/core/src/test/java/org/jclouds/cache/internal/BackoffExponentiallyAndRetryOnThrowableCallableTest.java +++ b/core/src/test/java/org/jclouds/cache/internal/BackoffExponentiallyAndRetryOnThrowableCallableTest.java @@ -23,7 +23,7 @@ import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; +import static org.testng.Assert.fail; import java.util.concurrent.Callable; @@ -66,7 +66,7 @@ public class BackoffExponentiallyAndRetryOnThrowableCallableTest { replay(mock); try { backoff.call(); - assertTrue(false); + fail(); } catch (ResourceNotFoundException e) { } diff --git a/core/src/test/java/org/jclouds/collect/AdvanceUntilEmptyIterableTest.java b/core/src/test/java/org/jclouds/collect/AdvanceUntilEmptyIterableTest.java new file mode 100644 index 0000000000..e3354fce81 --- /dev/null +++ b/core/src/test/java/org/jclouds/collect/AdvanceUntilEmptyIterableTest.java @@ -0,0 +1,80 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy current the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.collect; + +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expect; + +import org.easymock.EasyMock; +import org.testng.Assert; +import org.testng.annotations.Test; + +import com.google.common.base.Supplier; +import com.google.common.collect.FluentIterable; +import com.google.common.collect.ImmutableSet; + +/** + * Tests behavior of {@code AdvanceUntilEmptyIterable}. + * + * @author Adrian Cole + */ +@Test(testName = "AdvanceUntilEmptyIterableTest") +public class AdvanceUntilEmptyIterableTest { + + @SuppressWarnings("unchecked") + @Test + public void testSinglePageResultReturnsSame() { + + FluentIterable initial = FluentIterable.from(ImmutableSet.of("foo", "bar")); + Supplier> nextIterable = createMock(Supplier.class); + expect(nextIterable.get()).andReturn(initial); + + EasyMock.replay(nextIterable); + + AdvanceUntilEmptyIterable iterable = new AdvanceUntilEmptyIterable(nextIterable); + + Assert.assertSame(iterable.get(0), initial); + + EasyMock.verify(nextIterable); + } + + @SuppressWarnings("unchecked") + @Test + public void testConcatStopsWhenEmpty() { + + Supplier> nextIterable = createMock(Supplier.class); + + expect(nextIterable.get()).andReturn(FluentIterable.from(ImmutableSet.of("foo", "bar"))); + expect(nextIterable.get()).andReturn(FluentIterable.from(ImmutableSet.of("boo", "baz"))); + + expect(nextIterable.get()).andReturn(FluentIterable.from(ImmutableSet.of("ham", "cheeze"))); + expect(nextIterable.get()).andReturn(FluentIterable.from(ImmutableSet.of())); + + EasyMock.replay(nextIterable); + + AdvanceUntilEmptyIterable iterable = new AdvanceUntilEmptyIterable(nextIterable); + + Assert.assertEquals(iterable.concat().toImmutableSet(), + ImmutableSet.of("foo", "bar", "boo", "baz", "ham", "cheeze")); + + EasyMock.verify(nextIterable); + + } + +} diff --git a/core/src/test/java/org/jclouds/collect/PagedIterablesTest.java b/core/src/test/java/org/jclouds/collect/PagedIterablesTest.java index 9ce207dc6b..93c56dfda0 100644 --- a/core/src/test/java/org/jclouds/collect/PagedIterablesTest.java +++ b/core/src/test/java/org/jclouds/collect/PagedIterablesTest.java @@ -1,3 +1,21 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy current the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package org.jclouds.collect; import static org.easymock.EasyMock.createMock; diff --git a/core/src/test/java/org/jclouds/config/BindRestContextWithWildcardExtendsExplicitAndRawTypeTest.java b/core/src/test/java/org/jclouds/config/BindRestContextWithWildcardExtendsExplicitAndRawTypeTest.java index 08aafc8262..f47c6dcd6c 100644 --- a/core/src/test/java/org/jclouds/config/BindRestContextWithWildcardExtendsExplicitAndRawTypeTest.java +++ b/core/src/test/java/org/jclouds/config/BindRestContextWithWildcardExtendsExplicitAndRawTypeTest.java @@ -73,6 +73,7 @@ public class BindRestContextWithWildcardExtendsExplicitAndRawTypeTest { private Injector injectorFor(ProviderMetadata md) { return Guice.createInjector( + new BindNameToContext("test"), new BindProviderMetadataContextAndCredentials(md, new Credentials("user", "pass")), new BindRestContextWithWildcardExtendsExplicitAndRawType(RestApiMetadata.class.cast(md .getApiMetadata())), diff --git a/core/src/test/java/org/jclouds/http/BaseHttpCommandExecutorServiceIntegrationTest.java b/core/src/test/java/org/jclouds/http/BaseHttpCommandExecutorServiceIntegrationTest.java index d388d9ea53..52162b28ca 100644 --- a/core/src/test/java/org/jclouds/http/BaseHttpCommandExecutorServiceIntegrationTest.java +++ b/core/src/test/java/org/jclouds/http/BaseHttpCommandExecutorServiceIntegrationTest.java @@ -45,6 +45,7 @@ import org.jclouds.util.Throwables2; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; +import com.google.common.collect.ImmutableList; import com.google.common.collect.Multimap; import com.google.common.io.Closeables; @@ -195,7 +196,7 @@ public abstract class BaseHttpCommandExecutorServiceIntegrationTest extends Base payload.getContentMetadata().setContentMD5(digest); Multimap headers = client.postPayloadAndReturnHeaders("", payload); assertEquals(headers.get("x-Content-MD5"), - Collections.singleton(CryptoStreams.base64Encode(InputSuppliers.of(digest)))); + ImmutableList.of(CryptoStreams.base64(digest))); payload.release(); } finally { if (os != null) @@ -235,7 +236,7 @@ public abstract class BaseHttpCommandExecutorServiceIntegrationTest extends Base Payload payload = Payloads.newStringPayload("foo"); payload.getContentMetadata().setContentDisposition("attachment; filename=photo.jpg"); Multimap headers = client.postPayloadAndReturnHeaders("", payload); - assertEquals(headers.get("x-Content-Disposition"), Collections.singleton("attachment; filename=photo.jpg")); + assertEquals(headers.get("x-Content-Disposition"), ImmutableList.of("attachment; filename=photo.jpg")); payload.release(); } @@ -244,7 +245,7 @@ public abstract class BaseHttpCommandExecutorServiceIntegrationTest extends Base Payload payload = Payloads.newStringPayload("foo"); payload.getContentMetadata().setContentEncoding("gzip"); Multimap headers = client.postPayloadAndReturnHeaders("", payload); - assertEquals(headers.get("x-Content-Encoding"), Collections.singleton("gzip")); + assertEquals(headers.get("x-Content-Encoding"), ImmutableList.of("gzip")); payload.release(); } @@ -253,7 +254,7 @@ public abstract class BaseHttpCommandExecutorServiceIntegrationTest extends Base Payload payload = Payloads.newStringPayload("foo"); payload.getContentMetadata().setContentLanguage("mi, en"); Multimap headers = client.postPayloadAndReturnHeaders("", payload); - assertEquals(headers.get("x-Content-Language"), Collections.singleton("mi, en")); + assertEquals(headers.get("x-Content-Language"), ImmutableList.of("mi, en")); payload.release(); } diff --git a/core/src/test/java/org/jclouds/http/BaseJettyTest.java b/core/src/test/java/org/jclouds/http/BaseJettyTest.java index 68055e507a..f2b7e8105d 100644 --- a/core/src/test/java/org/jclouds/http/BaseJettyTest.java +++ b/core/src/test/java/org/jclouds/http/BaseJettyTest.java @@ -115,7 +115,7 @@ public abstract class BaseJettyTest { response.setContentType("text/plain"); response.setHeader("Content-MD5", md5); response.setStatus(HttpServletResponse.SC_OK); - copy(oneHundredOneConstitutions.getInput(), response.getOutputStream()); + copy(oneHundredOneConstitutions, response.getOutputStream()); } else if (request.getMethod().equals("PUT")) { if (request.getContentLength() > 0) { response.setStatus(HttpServletResponse.SC_OK); diff --git a/core/src/test/java/org/jclouds/http/filters/BasicAuthenticationTest.java b/core/src/test/java/org/jclouds/http/filters/BasicAuthenticationTest.java index 6576789252..726cfecc6e 100644 --- a/core/src/test/java/org/jclouds/http/filters/BasicAuthenticationTest.java +++ b/core/src/test/java/org/jclouds/http/filters/BasicAuthenticationTest.java @@ -20,7 +20,6 @@ package org.jclouds.http.filters; import static org.testng.Assert.assertEquals; -import java.io.UnsupportedEncodingException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; @@ -40,11 +39,11 @@ public class BasicAuthenticationTest { private static final String USER = "Aladdin"; private static final String PASSWORD = "open sesame"; - public void testAuth() throws UnsupportedEncodingException, NoSuchAlgorithmException, CertificateException { + public void testAuth() throws NoSuchAlgorithmException, CertificateException { BasicAuthentication filter = new BasicAuthentication(USER, PASSWORD, new JCECrypto(null)); HttpRequest request = HttpRequest.builder().method("GET").endpoint("http://localhost").build(); request = filter.filter(request); assertEquals(request.getFirstHeaderOrNull(HttpHeaders.AUTHORIZATION), "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="); } -} \ No newline at end of file +} diff --git a/core/src/test/java/org/jclouds/internal/BaseViewTest.java b/core/src/test/java/org/jclouds/internal/BaseViewTest.java index 506899d066..8dc4488628 100644 --- a/core/src/test/java/org/jclouds/internal/BaseViewTest.java +++ b/core/src/test/java/org/jclouds/internal/BaseViewTest.java @@ -19,9 +19,10 @@ package org.jclouds.internal; import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expect; import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotEquals; +import static org.testng.Assert.fail; import org.jclouds.lifecycle.Closer; import org.jclouds.providers.ProviderMetadata; @@ -36,10 +37,11 @@ import com.google.common.reflect.TypeToken; */ @Test(groups = "unit", testName = "BaseViewTest") public class BaseViewTest { + private static class Water extends ContextImpl { protected Water() { - super(createMock(ProviderMetadata.class), "identity", createMock(Utils.class), createMock(Closer.class)); + super("water", createMock(ProviderMetadata.class), "identity", createMock(Utils.class), createMock(Closer.class)); } @Override @@ -55,7 +57,7 @@ public class BaseViewTest { private static class PeanutButter extends ContextImpl { protected PeanutButter() { - super(createMock(ProviderMetadata.class), "identity", createMock(Utils.class), createMock(Closer.class)); + super("peanutbutter", createMock(ProviderMetadata.class), "identity", createMock(Utils.class), createMock(Closer.class)); } @Override @@ -87,7 +89,7 @@ public class BaseViewTest { assertNotEquals(wine.getBackendType(), TypeToken.of(PeanutButter.class)); try { wine.unwrap(TypeToken.of(PeanutButter.class)); - assertFalse(true); + fail(); } catch (IllegalArgumentException e) { assertEquals(e.getMessage(), "backend type: org.jclouds.internal.BaseViewTest$Water not assignable from org.jclouds.internal.BaseViewTest$PeanutButter"); } diff --git a/core/src/test/java/org/jclouds/rest/internal/BaseRestApiExpectTest.java b/core/src/test/java/org/jclouds/rest/internal/BaseRestApiExpectTest.java index dfe4789c48..b922cbec82 100644 --- a/core/src/test/java/org/jclouds/rest/internal/BaseRestApiExpectTest.java +++ b/core/src/test/java/org/jclouds/rest/internal/BaseRestApiExpectTest.java @@ -73,7 +73,6 @@ import org.jclouds.providers.ProviderMetadata; import org.jclouds.rest.RestApiMetadata; import org.jclouds.rest.config.CredentialStoreModule; import org.jclouds.util.Strings2; -import org.testng.annotations.Test; import org.w3c.dom.Node; import com.google.common.annotations.Beta; diff --git a/core/src/test/java/org/jclouds/rest/internal/RestAnnotationProcessorTest.java b/core/src/test/java/org/jclouds/rest/internal/RestAnnotationProcessorTest.java index f14de94dd5..f1a8736d8a 100644 --- a/core/src/test/java/org/jclouds/rest/internal/RestAnnotationProcessorTest.java +++ b/core/src/test/java/org/jclouds/rest/internal/RestAnnotationProcessorTest.java @@ -40,9 +40,9 @@ import java.net.URI; import java.net.URLEncoder; import java.security.NoSuchAlgorithmException; import java.util.Collection; -import java.util.Collections; import java.util.Date; import java.util.Map; +import java.util.NoSuchElementException; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; @@ -146,6 +146,7 @@ import com.google.common.base.Joiner; import com.google.common.base.Optional; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; +import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.ImmutableSet; @@ -499,6 +500,12 @@ public class RestAnnotationProcessorTest extends BaseRestApiTest { @QueryParams(keys = { "foo", "fooble" }, values = { "bar", "baz" }) public void foo3(@QueryParam("robbie") String robbie) { } + + @FOO + @Path("/") + @QueryParams(keys = { "foo", "fooble" }, values = { "bar", "baz" }) + public void foo3Nullable(@Nullable @QueryParam("robbie") String robbie) { + } } public void testUnEncodeQuery() { @@ -537,6 +544,25 @@ public class RestAnnotationProcessorTest extends BaseRestApiTest { assertEquals(request.getEndpoint().getQuery(), "x-ms-version=2009-07-17&foo=bar&fooble=baz&robbie=wonder"); assertEquals(request.getMethod(), "FOO"); } + + @Test + public void testNiceNPEQueryParam() throws SecurityException, NoSuchMethodException, IOException { + Method method = TestQuery.class.getMethod("foo3", String.class); + try { + factory(TestPath.class).createRequest(method, (String) null); + } catch (NullPointerException e) { + assertEquals(e.getMessage(), "param{robbie} for method TestQuery.foo3"); + } + } + + public void testNoNPEOnQueryParamWithNullable() throws SecurityException, NoSuchMethodException { + Method method = TestQuery.class.getMethod("foo3Nullable", String.class); + HttpRequest request = factory(TestPath.class).createRequest(method, (String) null); + assertEquals(request.getEndpoint().getHost(), "localhost"); + assertEquals(request.getEndpoint().getPath(), "/"); + assertEquals(request.getEndpoint().getQuery(), "foo=bar&fooble=baz"); + assertEquals(request.getMethod(), "FOO"); + } public interface TestPayloadParamVarargs { @POST @@ -578,7 +604,7 @@ public class RestAnnotationProcessorTest extends BaseRestApiTest { assertNonPayloadHeadersEqual(request, ""); assertPayloadEquals(request, "foo", "application/octet-stream", false); } - + public void testHttpRequestWithOnlyContentType() throws SecurityException, NoSuchMethodException, IOException { Method method = TestPayloadParamVarargs.class.getMethod("post", HttpRequestOptions.class); HttpRequest request = factory(TestPayloadParamVarargs.class).createRequest(method, new TestHttpRequestOptions().payload("fooya")); @@ -1397,6 +1423,11 @@ public class RestAnnotationProcessorTest extends BaseRestApiTest { @Path("/{path}") public void onePath(@PathParam("path") String path) { } + + @GET + @Path("/{path}") + public void onePathNullable(@Nullable @PathParam("path") String path) { + } @GET @Path("/{path1}/{path2}") @@ -1435,7 +1466,17 @@ public class RestAnnotationProcessorTest extends BaseRestApiTest { public void onePathParamExtractorMethod(String path) { } } - + + @Test + public void testNiceNPEPathParam() throws SecurityException, NoSuchMethodException, IOException { + Method method = TestPath.class.getMethod("onePath", String.class); + try { + factory(TestPath.class).createRequest(method, (String) null); + } catch (NullPointerException e) { + assertEquals(e.getMessage(), "param{path} for method TestPath.onePath"); + } + } + @Test public void testPathParamExtractor() throws SecurityException, NoSuchMethodException, IOException { Method method = TestPath.class.getMethod("onePathParamExtractor", String.class); @@ -1462,7 +1503,17 @@ public class RestAnnotationProcessorTest extends BaseRestApiTest { assertNonPayloadHeadersEqual(request, ""); assertPayloadEquals(request, null, null, false); } - + + @Test + public void testNiceNPEMatrixParam() throws SecurityException, NoSuchMethodException, IOException { + Method method = TestPath.class.getMethod("oneMatrixParamExtractor", String.class); + try { + factory(TestPath.class).createRequest(method, (String) null); + } catch (NullPointerException e) { + assertEquals(e.getMessage(), "param{one} for method TestPath.oneMatrixParamExtractor"); + } + } + @Test public void testFormParamExtractor() throws SecurityException, NoSuchMethodException, IOException { Method method = TestPath.class.getMethod("oneFormParamExtractor", String.class); @@ -1471,7 +1522,17 @@ public class RestAnnotationProcessorTest extends BaseRestApiTest { assertNonPayloadHeadersEqual(request, ""); assertPayloadEquals(request, "one=l", "application/x-www-form-urlencoded", false); } - + + @Test + public void testNiceNPEFormParam() throws SecurityException, NoSuchMethodException, IOException { + Method method = TestPath.class.getMethod("oneFormParamExtractor", String.class); + try { + factory(TestPath.class).createRequest(method, (String) null); + } catch (NullPointerException e) { + assertEquals(e.getMessage(), "param{one} for method TestPath.oneFormParamExtractor"); + } + } + @Test public void testParamExtractorMethod() throws SecurityException, NoSuchMethodException { Method method = TestPath.class.getMethod("onePathParamExtractorMethod", String.class); @@ -1525,8 +1586,8 @@ public class RestAnnotationProcessorTest extends BaseRestApiTest { Multimap headers = factory(TestHeader.class).createRequest(oneHeader, new Object[] { "robot" }) .getHeaders(); assertEquals(headers.size(), 2); - assertEquals(headers.get("slash"), Collections.singletonList("/robot")); - assertEquals(headers.get("hyphen"), Collections.singletonList("-robot")); + assertEquals(headers.get("slash"), ImmutableList.of("/robot")); + assertEquals(headers.get("hyphen"), ImmutableList.of("-robot")); } @Headers(keys = "x-amz-copy-source", values = "/{bucket}") @@ -1543,7 +1604,7 @@ public class RestAnnotationProcessorTest extends BaseRestApiTest { Multimap headers = factory(TestClassHeader.class).createRequest(oneHeader, new Object[] { "robot" }).getHeaders(); assertEquals(headers.size(), 1); - assertEquals(headers.get("x-amz-copy-source"), Collections.singletonList("/robot")); + assertEquals(headers.get("x-amz-copy-source"), ImmutableList.of("/robot")); } @Test @@ -1552,7 +1613,7 @@ public class RestAnnotationProcessorTest extends BaseRestApiTest { Multimap headers = factory(TestHeader.class).createRequest(oneHeader, new Object[] { "robot" }) .getHeaders(); assertEquals(headers.size(), 1); - assertEquals(headers.get("x-amz-copy-source"), Collections.singletonList("/robot")); + assertEquals(headers.get("x-amz-copy-source"), ImmutableList.of("/robot")); } @Test @@ -1561,7 +1622,7 @@ public class RestAnnotationProcessorTest extends BaseRestApiTest { Multimap headers = factory(TestHeader.class).createRequest(twoHeaders, new Object[] { "robot", "eggs" }).getHeaders(); assertEquals(headers.size(), 1); - assertEquals(headers.get("x-amz-copy-source"), Collections.singletonList("/robot/eggs")); + assertEquals(headers.get("x-amz-copy-source"), ImmutableList.of("/robot/eggs")); } @Test @@ -1570,7 +1631,7 @@ public class RestAnnotationProcessorTest extends BaseRestApiTest { Multimap headers = factory(TestHeader.class).createRequest(twoHeadersOutOfOrder, new Object[] { "robot", "eggs" }).getHeaders(); assertEquals(headers.size(), 1); - assertEquals(headers.get("x-amz-copy-source"), Collections.singletonList("/eggs/robot")); + assertEquals(headers.get("x-amz-copy-source"), ImmutableList.of("/eggs/robot")); } public class TestReplaceQueryOptions extends BaseHttpRequestOptions { @@ -2038,9 +2099,9 @@ public class RestAnnotationProcessorTest extends BaseRestApiTest { assertEquals(request.getEndpoint().getPath(), "/1"); assertEquals(request.getMethod(), HttpMethod.GET); assertEquals(request.getHeaders().size(), 2); - assertEquals(request.getHeaders().get(HttpHeaders.HOST), Collections.singletonList("localhost:9999")); + assertEquals(request.getHeaders().get(HttpHeaders.HOST), ImmutableList.of("localhost:9999")); assertEquals(request.getHeaders().get(HttpHeaders.IF_MODIFIED_SINCE), - Collections.singletonList(dateService.rfc822DateFormat(date))); + ImmutableList.of(dateService.rfc822DateFormat(date))); } public void testCreateGetOptionsThatProducesHeaders() throws SecurityException, NoSuchMethodException { @@ -2052,9 +2113,9 @@ public class RestAnnotationProcessorTest extends BaseRestApiTest { assertEquals(request.getEndpoint().getPath(), "/1"); assertEquals(request.getMethod(), HttpMethod.GET); assertEquals(request.getHeaders().size(), 2); - assertEquals(request.getHeaders().get(HttpHeaders.HOST), Collections.singletonList("localhost:9999")); + assertEquals(request.getHeaders().get(HttpHeaders.HOST), ImmutableList.of("localhost:9999")); assertEquals(request.getHeaders().get(HttpHeaders.IF_MODIFIED_SINCE), - Collections.singletonList(dateService.rfc822DateFormat(date))); + ImmutableList.of(dateService.rfc822DateFormat(date))); } public class PrefixOptions extends BaseHttpRequestOptions { @@ -2136,7 +2197,7 @@ public class RestAnnotationProcessorTest extends BaseRestApiTest { assertEquals(request.getEndpoint().getPath(), "/" + key); assertEquals(request.getMethod(), HttpMethod.GET); assertEquals(request.getHeaders().size(), 1); - assertEquals(request.getHeaders().get(HttpHeaders.HOST), Collections.singletonList("localhost")); + assertEquals(request.getHeaders().get(HttpHeaders.HOST), ImmutableList.of("localhost")); } public void testCreatePutRequest() throws SecurityException, NoSuchMethodException, IOException { @@ -2175,7 +2236,7 @@ public class RestAnnotationProcessorTest extends BaseRestApiTest { assertEquals(request.getEndpoint().getPath(), "/1"); assertEquals(request.getMethod(), HttpMethod.GET); assertEquals(request.getHeaders().size(), 1); - assertEquals(request.getHeaders().get(HttpHeaders.HOST), Collections.singletonList("localhost:9999")); + assertEquals(request.getHeaders().get(HttpHeaders.HOST), ImmutableList.of("localhost:9999")); } public interface TestVirtualHost { @@ -2198,7 +2259,7 @@ public class RestAnnotationProcessorTest extends BaseRestApiTest { assertEquals(request.getEndpoint().getPath(), "/1"); assertEquals(request.getMethod(), HttpMethod.GET); assertEquals(request.getHeaders().size(), 1); - assertEquals(request.getHeaders().get(HttpHeaders.HOST), Collections.singletonList("localhost:9999")); + assertEquals(request.getHeaders().get(HttpHeaders.HOST), ImmutableList.of("localhost:9999")); } @Test @@ -2237,7 +2298,7 @@ public class RestAnnotationProcessorTest extends BaseRestApiTest { Multimap headers = factory(TestHeaders.class).buildHeaders( ImmutableMultimap. of().entries(), method, "robot"); assertEquals(headers.size(), 1); - assertEquals(headers.get("header"), Collections.singletonList("robot")); + assertEquals(headers.get("header"), ImmutableList.of("robot")); } @Test @@ -2246,7 +2307,7 @@ public class RestAnnotationProcessorTest extends BaseRestApiTest { Multimap headers = factory(TestHeaders.class).buildHeaders( ImmutableMultimap. of().entries(), method, 1); assertEquals(headers.size(), 1); - assertEquals(headers.get("header"), Collections.singletonList("1")); + assertEquals(headers.get("header"), ImmutableList.of("1")); } @Test @@ -2255,8 +2316,8 @@ public class RestAnnotationProcessorTest extends BaseRestApiTest { Multimap headers = factory(TestHeaders.class).buildHeaders( ImmutableMultimap. of().entries(), method, "robot", "egg"); assertEquals(headers.size(), 2); - assertEquals(headers.get("header1"), Collections.singletonList("robot")); - assertEquals(headers.get("header2"), Collections.singletonList("egg")); + assertEquals(headers.get("header1"), ImmutableList.of("robot")); + assertEquals(headers.get("header2"), ImmutableList.of("egg")); } @Test @@ -2416,6 +2477,10 @@ public class RestAnnotationProcessorTest extends BaseRestApiTest { @Provides Set exception(); + @Named("NoSuchElementException") + @Provides + Set noSuchElementException(); + @POST @Path("/") void oneForm(@PathParam("bucket") String path); @@ -2437,7 +2502,12 @@ public class RestAnnotationProcessorTest extends BaseRestApiTest { public void testProvidesWithGenericQualifiedAuthorizationException() throws SecurityException, NoSuchMethodException { injector.getInstance(AsyncClientFactory.class).create(TestClassForm.class).exception(); } - + + @Test(expectedExceptions = NoSuchElementException.class) + public void testProvidesWithGenericQualifiedNoSuchElementException() throws SecurityException, NoSuchMethodException { + injector.getInstance(AsyncClientFactory.class).create(TestClassForm.class).noSuchElementException(); + } + @Test public void testBuildOneClassForm() throws SecurityException, NoSuchMethodException { Method oneForm = TestClassForm.class.getMethod("oneForm", String.class); @@ -2604,7 +2674,13 @@ public class RestAnnotationProcessorTest extends BaseRestApiTest { Set exception() { throw new AuthorizationException(); } - + + @Provides + @Named("NoSuchElementException") + Set noSuchElementException() { + throw new NoSuchElementException(); + } + })).buildInjector(); parserFactory = injector.getInstance(ParseSax.Factory.class); crypto = injector.getInstance(Crypto.class); diff --git a/demos/getpath/pom.xml b/demos/getpath/pom.xml index 0ad9f65930..5c782d0885 100644 --- a/demos/getpath/pom.xml +++ b/demos/getpath/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-demos-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT jclouds-demo-getpath jclouds getpath diff --git a/demos/getpath/src/test/java/org/jclouds/blobstore/GetPathLiveTest.java b/demos/getpath/src/test/java/org/jclouds/blobstore/GetPathLiveTest.java index 0a8704ebc2..eb35d71f82 100644 --- a/demos/getpath/src/test/java/org/jclouds/blobstore/GetPathLiveTest.java +++ b/demos/getpath/src/test/java/org/jclouds/blobstore/GetPathLiveTest.java @@ -22,7 +22,6 @@ import static com.google.common.base.Preconditions.checkNotNull; import static org.testng.Assert.assertEquals; import java.io.File; -import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.List; @@ -33,17 +32,18 @@ import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeoutException; import org.jclouds.logging.log4j.config.Log4JLoggingModule; -import org.jclouds.util.Strings2; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeClass; import org.testng.annotations.Optional; import org.testng.annotations.Parameters; import org.testng.annotations.Test; +import com.google.common.base.Charsets; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.collect.Sets; +import com.google.common.io.Files; /** * @@ -153,8 +153,8 @@ public class GetPathLiveTest { new File(tmpDirectory).mkdirs(); GetPath.main(uriKey, tmpDirectory); for (Entry entry : fiveStrings.entrySet()) { - assertEquals(Strings2.toStringAndClose(new FileInputStream(new File(tmpDirectory, entry - .getKey()))), entry.getValue()); + assertEquals(Files.toString(new File(tmpDirectory, entry.getKey()), + Charsets.UTF_8), entry.getValue()); } } diff --git a/demos/googleappengine/pom.xml b/demos/googleappengine/pom.xml index abcd66b18b..ca2ad29420 100644 --- a/demos/googleappengine/pom.xml +++ b/demos/googleappengine/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-demos-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT jclouds-demo-googleappengine war diff --git a/demos/perftest/README.txt b/demos/perftest/README.txt deleted file mode 100644 index 52d0bf1f4a..0000000000 --- a/demos/perftest/README.txt +++ /dev/null @@ -1,57 +0,0 @@ -==== - Licensed to jclouds, Inc. (jclouds) under one or more - contributor license agreements. See the NOTICE file - distributed with this work for additional information - regarding copyright ownership. jclouds licenses this file - to you under the Apache License, Version 2.0 (the - "License"); you may not use this file except in compliance - with the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, - software distributed under the License is distributed on an - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - KIND, either express or implied. See the License for the - specific language governing permissions and limitations - under the License. -==== - -This sample uses the Google App Engine for Java SDK located at http://googleappengine.googlecode.com/files/appengine-java-sdk-1.3.5.zip - -Please unzip the above file and modify your maven settings.xml like below before attempting to run 'mvn -Plive install' - - - appengine - - true - - - /path/to/appengine-java-sdk-1.3.5 - - - - - aws - - true - - - YOUR_ACCESS_KEY_ID - YOUR_SECRET_KEY - - - - - - jclouds - http://jclouds.googlecode.com/svn/trunk/repo - - - jclouds-rimu-snapshots-nexus - http://jclouds.rimuhosting.com:8081/nexus/content/repositories/snapshots - - true - - - diff --git a/demos/perftest/pom.xml b/demos/perftest/pom.xml deleted file mode 100644 index 327d12ff70..0000000000 --- a/demos/perftest/pom.xml +++ /dev/null @@ -1,217 +0,0 @@ - - - - 4.0.0 - - org.jclouds - jclouds-demos-project - 1.5.0-SNAPSHOT - - jclouds-demo-perftest - jclouds Performance test verses Amazon SDK implementation - Performance test verses Amazon SDK implementation - - - 100 - ${test.aws.identity} - ${test.aws.credential} - 1.5.0-SNAPSHOT - 1.6.5 - - - - - org.jclouds.provider - aws-s3 - ${jclouds.version} - - - com.amazonaws - aws-java-sdk - 1.3.8 - - - net.java.dev.jets3t - jets3t - 0.9.0 - - - org.jclouds.driver - jclouds-enterprise - ${jclouds.version} - - - org.jclouds.driver - jclouds-netty - ${jclouds.version} - - - org.jclouds.driver - jclouds-apachehc - ${jclouds.version} - - - org.jclouds.driver - jclouds-gae - ${jclouds.version} - - - org.jclouds - jclouds-blobstore - ${jclouds.version} - test-jar - test - - - org.jclouds.api - s3 - ${jclouds.version} - test-jar - test - - - org.jclouds.provider - aws-s3 - ${jclouds.version} - test-jar - test - - - - com.google.appengine - appengine-api-1.0-sdk - ${appengine.sdk.version} - compile - - - com.google.appengine - appengine-api-stubs - ${appengine.sdk.version} - test - - - com.google.appengine - appengine-testing - ${appengine.sdk.version} - test - - - - - - maven-surefire-plugin - - - integration - integration-test - - test - - - 1 - - ${test.aws-s3.identity} - ${test.aws-s3.credential} - ${test.initializer} - ${test.aws-s3.loopcount} - - - - - - - com.ning.maven.plugins - maven-duplicate-finder-plugin - - - - - - - com.amazonaws - aws-java-sdk - 1.3.8 - - - com.google.appengine - appengine-api-1.0-sdk - ${appengine.sdk.version} - - - - META-INF/javamail.providers - - - - - - - com.google.appengine - appengine-api-1.0-sdk - ${appengine.sdk.version} - - - com.google.appengine - appengine-testing - ${appengine.sdk.version} - test - - - - com.google - - - - - - - - - - live - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration - integration-test - - test - - - - ${test.aws-s3.identity} - ${test.aws-s3.credential} - ${test.aws-s3.loopcount} - - - - - - - - - - diff --git a/demos/perftest/src/test/java/org/jclouds/aws/s3/AmazonPerformanceLiveTest.java b/demos/perftest/src/test/java/org/jclouds/aws/s3/AmazonPerformanceLiveTest.java deleted file mode 100644 index 9c6d63e9ea..0000000000 --- a/demos/perftest/src/test/java/org/jclouds/aws/s3/AmazonPerformanceLiveTest.java +++ /dev/null @@ -1,118 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.aws.s3; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.InputStream; -import java.util.Properties; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; - -import org.jclouds.blobstore.BlobStoreContext; -import org.testng.annotations.Test; - -import com.amazonaws.auth.BasicAWSCredentials; -import com.amazonaws.services.s3.AmazonS3; -import com.amazonaws.services.s3.AmazonS3Client; -import com.amazonaws.services.s3.model.ObjectMetadata; -import com.amazonaws.services.s3.model.PutObjectRequest; -import com.google.inject.Module; - -/** - * Runs operations that amazon s3 sample code is capable of performing. - * - * @author Adrian Cole - */ -@Test(singleThreaded = true, timeOut = 2 * 60 * 1000, groups = "live", testName = "AmazonPerformanceLiveTest") -public class AmazonPerformanceLiveTest extends BasePerformanceLiveTest { - - public AmazonPerformanceLiveTest(){ - exec = Executors.newCachedThreadPool(); - } - - private AmazonS3 s3; - - @Override - protected BlobStoreContext createView(Properties props, Iterable modules) { - s3 = new AmazonS3Client(new BasicAWSCredentials(System.getProperty("test.aws-s3.identity"), - System.getProperty("test.aws-s3.credential"))); - return super.createView(props, modules); - } - - @Override - @Test(enabled = false) - public void testPutStringSerial() throws Exception { - throw new UnsupportedOperationException(); - } - - @Override - @Test(enabled = false) - public void testPutStringParallel() throws InterruptedException, ExecutionException { - throw new UnsupportedOperationException(); - } - - @Override - protected Future putByteArray(final String bucket, final String key, final byte[] data, final String contentType) { - - return exec.submit(new Callable() { - @Override - public String call() throws Exception { - ObjectMetadata md = new ObjectMetadata(); - md.setContentType(contentType); - md.setContentLength(data.length); - return s3.putObject(new PutObjectRequest(bucket, key, new ByteArrayInputStream(data), md)).getETag(); - } - }); - } - - @Override - protected Future putFile(final String bucket, final String key, final File data, String contentType) { - - return exec.submit(new Callable() { - @Override - public String call() throws Exception { - return s3.putObject(new PutObjectRequest(bucket, key, data)).getETag(); - } - }); - } - - @Override - protected Future putInputStream(final String bucket, final String key, final InputStream data, - final String contentType) { - - return exec.submit(new Callable() { - @Override - public String call() throws Exception { - ObjectMetadata md = new ObjectMetadata(); - md.setContentType(contentType); - md.setContentLength(data.available()); - return s3.putObject(new PutObjectRequest(bucket, key, data, md)).getETag(); - } - }); - } - - @Override - protected Future putString(String bucket, String key, String data, String contentType) { - throw new UnsupportedOperationException(); - } - -} diff --git a/demos/perftest/src/test/java/org/jclouds/aws/s3/BaseJCloudsPerformanceLiveTest.java b/demos/perftest/src/test/java/org/jclouds/aws/s3/BaseJCloudsPerformanceLiveTest.java deleted file mode 100644 index 8d23bbd640..0000000000 --- a/demos/perftest/src/test/java/org/jclouds/aws/s3/BaseJCloudsPerformanceLiveTest.java +++ /dev/null @@ -1,95 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.aws.s3; - -import static org.jclouds.Constants.PROPERTY_IO_WORKER_THREADS; -import static org.jclouds.Constants.PROPERTY_MAX_CONNECTIONS_PER_CONTEXT; -import static org.jclouds.Constants.PROPERTY_MAX_CONNECTIONS_PER_HOST; -import static org.jclouds.Constants.PROPERTY_USER_THREADS; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; -import java.util.concurrent.Future; - -import org.jclouds.s3.S3AsyncClient; -import org.jclouds.s3.domain.S3Object; - -import com.google.common.base.Throwables; - -/** - * // TODO: Adrian: Document this! - * - * @author Adrian Cole - */ -public abstract class BaseJCloudsPerformanceLiveTest extends BasePerformanceLiveTest { - - protected void printPropertiesOfContext(Properties overrides, String contextName) { - System.out.printf("%s: loopCount(%s), perContext(%s), perHost(%s), ioWorkers(%s), userThreads(%s)%n", contextName, - loopCount, overrides.getProperty(PROPERTY_MAX_CONNECTIONS_PER_CONTEXT), overrides - .getProperty(PROPERTY_MAX_CONNECTIONS_PER_HOST), overrides.getProperty(PROPERTY_IO_WORKER_THREADS), - overrides.getProperty(PROPERTY_USER_THREADS)); - } - - @Override - protected Future putByteArray(String bucket, String key, byte[] data, String contentType) { - S3Object object = newObject(key); - object.setPayload(data); - object.getPayload().getContentMetadata().setContentType(contentType); - return getApi().putObject(bucket, object); - } - - public abstract S3AsyncClient getApi(); - - @Override - protected Future putFile(String bucket, String key, File data, String contentType) { - S3Object object = newObject(key); - object.setPayload(data); - object.getPayload().getContentMetadata().setContentType(contentType); - return getApi().putObject(bucket, object); - } - - private S3Object newObject(String key) { - S3Object object = getApi().newS3Object(); - object.getMetadata().setKey(key); - return object; - } - - @Override - protected Future putInputStream(String bucket, String key, InputStream data, String contentType) { - S3Object object = newObject(key); - object.setPayload(data); - try { - object.getPayload().getContentMetadata().setContentLength(Long.valueOf(data.available())); - } catch (IOException e) { - Throwables.propagate(e); - } - object.getPayload().getContentMetadata().setContentType(contentType); - return getApi().putObject(bucket, object); - } - - @Override - protected Future putString(String bucket, String key, String data, String contentType) { - S3Object object = newObject(key); - object.setPayload(data); - object.getPayload().getContentMetadata().setContentType(contentType); - return getApi().putObject(bucket, object); - } -} diff --git a/demos/perftest/src/test/java/org/jclouds/aws/s3/BasePerformanceLiveTest.java b/demos/perftest/src/test/java/org/jclouds/aws/s3/BasePerformanceLiveTest.java deleted file mode 100644 index 1c3e14ce02..0000000000 --- a/demos/perftest/src/test/java/org/jclouds/aws/s3/BasePerformanceLiveTest.java +++ /dev/null @@ -1,230 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.aws.s3; - -import static org.jclouds.concurrent.FutureIterables.awaitCompletion; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.InputStream; -import java.util.Map; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Future; -import java.util.concurrent.TimeoutException; -import java.util.concurrent.atomic.AtomicInteger; - -import javax.inject.Provider; - -import org.jclouds.blobstore.integration.internal.BaseBlobStoreIntegrationTest; -import org.jclouds.logging.Logger; -import org.testng.annotations.Test; - -import com.google.common.collect.Maps; -import com.google.common.util.concurrent.JdkFutureAdapters; -import com.google.common.util.concurrent.ListenableFuture; - -/** - * Tests relative performance of S3 functions. - * - * @author Adrian Cole - */ -public abstract class BasePerformanceLiveTest extends BaseBlobStoreIntegrationTest { - - public BasePerformanceLiveTest(){ - provider = "aws-s3"; - } - - static { - containerCount = 1; - } - - protected int timeoutSeconds = 15; - protected int loopCount = Integer.parseInt(System.getProperty("test.aws-s3.loopcount", "1000")); - protected ExecutorService exec; - protected Logger logger = Logger.NULL;; - - @Test(enabled = false) - public void testPutBytesSerial() throws Exception { - String bucketName = getContainerName(); - try { - doSerial(new PutBytesFuture(bucketName), loopCount / 10); - } finally { - returnContainer(bucketName); - } - } - - @Test - public void testPutBytesParallel() throws InterruptedException, ExecutionException, TimeoutException { - String bucketName = getContainerName(); - try { - doParallel(new PutBytesFuture(bucketName), loopCount, bucketName); - } finally { - returnContainer(bucketName); - } - } - - @Test(enabled = false) - public void testPutFileSerial() throws Exception { - String bucketName = getContainerName(); - try { - doSerial(new PutFileFuture(bucketName), loopCount / 10); - } finally { - returnContainer(bucketName); - } - } - - @Test - public void testPutFileParallel() throws InterruptedException, ExecutionException, TimeoutException { - String bucketName = getContainerName(); - try { - doParallel(new PutFileFuture(bucketName), loopCount, bucketName); - } finally { - returnContainer(bucketName); - } - } - - @Test(enabled = false) - public void testPutInputStreamSerial() throws Exception { - String bucketName = getContainerName(); - try { - doSerial(new PutInputStreamFuture(bucketName), loopCount / 10); - } finally { - returnContainer(bucketName); - } - } - - @Test - public void testPutInputStreamParallel() throws InterruptedException, ExecutionException, TimeoutException { - String bucketName = getContainerName(); - try { - doParallel(new PutInputStreamFuture(bucketName), loopCount, bucketName); - } finally { - returnContainer(bucketName); - } - } - - @Test(enabled = false) - public void testPutStringSerial() throws Exception { - String bucketName = getContainerName(); - try { - doSerial(new PutStringFuture(bucketName), loopCount / 10); - } finally { - returnContainer(bucketName); - } - } - - @Test - public void testPutStringParallel() throws InterruptedException, ExecutionException, TimeoutException { - String bucketName = getContainerName(); - try { - doParallel(new PutStringFuture(bucketName), loopCount, bucketName); - } finally { - returnContainer(bucketName); - } - } - - private void doSerial(Provider> provider, int loopCount) throws Exception, ExecutionException { - for (int i = 0; i < loopCount; i++) - assert provider.get().get() != null; - } - - private void doParallel(Provider> provider, int loopCount, String containerName) - throws InterruptedException, ExecutionException, TimeoutException { - Map> responses = Maps.newHashMap(); - for (int i = 0; i < loopCount; i++) - responses.put(i, provider.get()); - - Map exceptions = awaitCompletion(responses, exec, null, Logger.NULL, String.format( - "putting into containerName: %s", containerName)); - - assert exceptions.size() == 0 : exceptions; - - } - - class PutBytesFuture implements Provider> { - final AtomicInteger key = new AtomicInteger(0); - protected byte[] test = new byte[1024 * 2]; - private final String bucketName; - - public PutBytesFuture(String bucketName) { - this.bucketName = bucketName; - } - - public ListenableFuture get() { - return JdkFutureAdapters.listenInPoolThread(putByteArray(bucketName, key.getAndIncrement() + "", test, - "application/octetstring")); - } - } - - class PutFileFuture implements Provider> { - final AtomicInteger key = new AtomicInteger(0); - protected File file = new File(getClass().getResource("/testimg.png").getFile()); - private final String bucketName; - - public PutFileFuture(String bucketName) { - this.bucketName = bucketName; - } - - public ListenableFuture get() { - return JdkFutureAdapters.listenInPoolThread(putFile(bucketName, key.getAndIncrement() + "", file, "text/xml")); - } - } - - class PutInputStreamFuture extends PutBytesFuture { - final AtomicInteger key = new AtomicInteger(0); - private final String bucketName; - - public PutInputStreamFuture(String bucketName) { - super(bucketName); - this.bucketName = bucketName; - } - - @Override - public ListenableFuture get() { - - return JdkFutureAdapters.listenInPoolThread(putInputStream(bucketName, key.getAndIncrement() + "", new ByteArrayInputStream( - test), "application/octetstring")); - - } - } - - class PutStringFuture implements Provider> { - final AtomicInteger key = new AtomicInteger(0); - protected String testString = "hello world!"; - private final String bucketName; - - public PutStringFuture(String bucketName) { - this.bucketName = bucketName; - } - - public ListenableFuture get() { - return JdkFutureAdapters.listenInPoolThread(putString(bucketName, key.getAndIncrement() + "", testString, "text/plain")); - } - } - - protected abstract Future putByteArray(String bucket, String key, byte[] data, String contentType); - - protected abstract Future putFile(String bucket, String key, File data, String contentType); - - protected abstract Future putInputStream(String bucket, String key, InputStream data, String contentType); - - protected abstract Future putString(String bucket, String key, String data, String contentType); - -} diff --git a/demos/perftest/src/test/java/org/jclouds/aws/s3/JCloudsApacheHCPerformanceLiveTest.java b/demos/perftest/src/test/java/org/jclouds/aws/s3/JCloudsApacheHCPerformanceLiveTest.java deleted file mode 100644 index 507f9fb22c..0000000000 --- a/demos/perftest/src/test/java/org/jclouds/aws/s3/JCloudsApacheHCPerformanceLiveTest.java +++ /dev/null @@ -1,74 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.aws.s3; - -import static org.jclouds.Constants.PROPERTY_CONNECTION_TIMEOUT; -import static org.jclouds.Constants.PROPERTY_IO_WORKER_THREADS; -import static org.jclouds.Constants.PROPERTY_MAX_CONNECTIONS_PER_CONTEXT; -import static org.jclouds.Constants.PROPERTY_MAX_CONNECTIONS_PER_HOST; -import static org.jclouds.Constants.PROPERTY_SO_TIMEOUT; -import static org.jclouds.Constants.PROPERTY_USER_THREADS; - -import java.util.Properties; -import java.util.concurrent.Executors; - -import org.jclouds.enterprise.config.EnterpriseConfigurationModule; -import org.jclouds.http.apachehc.config.ApacheHCHttpCommandExecutorServiceModule; -import org.jclouds.logging.config.NullLoggingModule; -import org.jclouds.netty.config.NettyPayloadModule; -import org.jclouds.s3.S3AsyncClient; -import org.testng.annotations.Test; - -import com.google.common.collect.ImmutableSet; -import com.google.inject.Module; - -@Test(singleThreaded = true, timeOut = 2 * 60 * 1000, groups = "live", testName = "JCloudsApacheHCPerformanceLiveTest") -public class JCloudsApacheHCPerformanceLiveTest extends BaseJCloudsPerformanceLiveTest { - - public JCloudsApacheHCPerformanceLiveTest(){ - exec = Executors.newCachedThreadPool(); - } - - @Override - protected Properties setupProperties() { - Properties overrides = super.setupProperties(); - overrides.setProperty(PROPERTY_SO_TIMEOUT, 5000 + ""); - overrides.setProperty(PROPERTY_CONNECTION_TIMEOUT, 5000 + ""); - overrides.setProperty(PROPERTY_MAX_CONNECTIONS_PER_CONTEXT, 20 + ""); - overrides.setProperty(PROPERTY_MAX_CONNECTIONS_PER_HOST, 0 + ""); - overrides.setProperty(PROPERTY_IO_WORKER_THREADS, 50 + ""); - overrides.setProperty(PROPERTY_USER_THREADS, 0 + ""); - printPropertiesOfContext(overrides, "apachehc"); - return overrides; - } - - @Override - protected Iterable setupModules() { - return ImmutableSet.builder() - .add(new NullLoggingModule()) - .add(new NettyPayloadModule()) - .add(new ApacheHCHttpCommandExecutorServiceModule()) - .add(new EnterpriseConfigurationModule()).build(); - } - - @Override - public S3AsyncClient getApi() { - return view.unwrap(AWSS3ApiMetadata.CONTEXT_TOKEN).getAsyncApi(); - } -} diff --git a/demos/perftest/src/test/java/org/jclouds/aws/s3/JCloudsGaePerformanceLiveTest.java b/demos/perftest/src/test/java/org/jclouds/aws/s3/JCloudsGaePerformanceLiveTest.java deleted file mode 100644 index 742d0f198d..0000000000 --- a/demos/perftest/src/test/java/org/jclouds/aws/s3/JCloudsGaePerformanceLiveTest.java +++ /dev/null @@ -1,154 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.aws.s3; - -import java.io.File; -import java.io.InputStream; -import java.util.Properties; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; -import java.util.concurrent.TimeoutException; - -import org.jclouds.enterprise.config.EnterpriseConfigurationModule; -import org.jclouds.gae.config.AsyncGoogleAppEngineConfigurationModule; -import org.jclouds.logging.config.NullLoggingModule; -import org.jclouds.s3.S3AsyncClient; -import org.testng.annotations.BeforeMethod; -import org.testng.annotations.Test; - -import com.google.appengine.tools.development.testing.LocalServiceTestHelper; -import com.google.appengine.tools.development.testing.LocalURLFetchServiceTestConfig; -import com.google.common.collect.ImmutableSet; -import com.google.inject.Module; - -/** - * - * This test is disabled due to timeout limitations in the google app engine sdk - * - * @author Adrian Cole - */ -@Test(enabled = false, singleThreaded = true, timeOut = 2 * 60 * 1000, groups = "live", testName = "JCloudsGaePerformanceLiveTest") -public class JCloudsGaePerformanceLiveTest extends BaseJCloudsPerformanceLiveTest { - - @Override - @Test(enabled = false) - public void testPutBytesParallel() throws InterruptedException, ExecutionException, TimeoutException { - throw new UnsupportedOperationException(); - } - - @Override - @Test(enabled = false) - public void testPutBytesSerial() throws Exception { - throw new UnsupportedOperationException(); - } - - @Override - @Test(enabled = false) - public void testPutFileParallel() throws InterruptedException, ExecutionException, TimeoutException { - throw new UnsupportedOperationException(); - } - - @Override - @Test(enabled = false) - public void testPutFileSerial() throws Exception { - throw new UnsupportedOperationException(); - } - - @Override - @Test(enabled = false) - public void testPutInputStreamParallel() throws InterruptedException, ExecutionException, TimeoutException { - throw new UnsupportedOperationException(); - } - - @Override - @Test(enabled = false) - public void testPutInputStreamSerial() throws Exception { - throw new UnsupportedOperationException(); - } - - @Override - @Test(enabled = false) - public void testPutStringParallel() throws InterruptedException, ExecutionException, TimeoutException { - throw new UnsupportedOperationException(); - } - - @Override - @Test(enabled = false) - public void testPutStringSerial() throws Exception { - throw new UnsupportedOperationException(); - } - - public JCloudsGaePerformanceLiveTest() { - super(); - // otherwise, we'll get timeout errors - // TODO sdk 1.2.3 should give the ability to set a higher timeout then 5 - // seconds allowing this - // to be removed - loopCount = 5; - } - - @Override - protected Future putByteArray(String bucket, String key, byte[] data, String contentType) { - setupApiProxy(); - return super.putByteArray(bucket, key, data, contentType); - } - - @Override - protected Future putFile(String bucket, String key, File data, String contentType) { - setupApiProxy(); - return super.putFile(bucket, key, data, contentType); - } - - @Override - protected Future putInputStream(String bucket, String key, InputStream data, String contentType) { - setupApiProxy(); - return super.putInputStream(bucket, key, data, contentType); - } - - @Override - protected Future putString(String bucket, String key, String data, String contentType) { - setupApiProxy(); - return super.putString(bucket, key, data, contentType); - } - - @BeforeMethod - void setupApiProxy() { - new LocalServiceTestHelper(new LocalURLFetchServiceTestConfig()).setUp(); - } - - @Override - protected Properties setupProperties() { - Properties overrides = super.setupProperties(); - printPropertiesOfContext(overrides, "apachehc"); - return overrides; - } - - @Override - protected Iterable setupModules() { - return ImmutableSet.builder() - .add(new NullLoggingModule()) - .add(new AsyncGoogleAppEngineConfigurationModule()) - .add(new EnterpriseConfigurationModule()).build(); - } - - @Override - public S3AsyncClient getApi() { - return view.unwrap(AWSS3ApiMetadata.CONTEXT_TOKEN).getAsyncApi(); - } -} \ No newline at end of file diff --git a/demos/perftest/src/test/java/org/jclouds/aws/s3/JCloudsPerformanceLiveTest.java b/demos/perftest/src/test/java/org/jclouds/aws/s3/JCloudsPerformanceLiveTest.java deleted file mode 100644 index 4335999c7f..0000000000 --- a/demos/perftest/src/test/java/org/jclouds/aws/s3/JCloudsPerformanceLiveTest.java +++ /dev/null @@ -1,74 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.aws.s3; - -import static org.jclouds.Constants.PROPERTY_IO_WORKER_THREADS; -import static org.jclouds.Constants.PROPERTY_MAX_CONNECTIONS_PER_CONTEXT; -import static org.jclouds.Constants.PROPERTY_MAX_CONNECTIONS_PER_HOST; -import static org.jclouds.Constants.PROPERTY_USER_THREADS; - -import java.util.Properties; -import java.util.concurrent.Executors; - -import org.jclouds.enterprise.config.EnterpriseConfigurationModule; -import org.jclouds.logging.config.NullLoggingModule; -import org.jclouds.netty.config.NettyPayloadModule; -import org.jclouds.s3.S3AsyncClient; -import org.testng.annotations.Test; - -import com.google.common.collect.ImmutableSet; -import com.google.inject.Module; - -/** - * Tests the default JClouds client. - * - * @author Adrian Cole - * - */ -@Test(singleThreaded = true, timeOut = 2 * 60 * 1000, groups = "live", testName = "JCloudsPerformanceLiveTest") -public class JCloudsPerformanceLiveTest extends BaseJCloudsPerformanceLiveTest { - - public JCloudsPerformanceLiveTest(){ - exec = Executors.newCachedThreadPool(); - } - - @Override - protected Properties setupProperties() { - Properties overrides = super.setupProperties(); - overrides.setProperty(PROPERTY_MAX_CONNECTIONS_PER_CONTEXT, 50 + ""); - overrides.setProperty(PROPERTY_MAX_CONNECTIONS_PER_HOST, 30 + ""); - overrides.setProperty(PROPERTY_IO_WORKER_THREADS, 50 + ""); - overrides.setProperty(PROPERTY_USER_THREADS, 0 + ""); - printPropertiesOfContext(overrides, "default"); - return overrides; - } - - @Override - protected Iterable setupModules() { - return ImmutableSet.builder() - .add(new NullLoggingModule()) - .add(new NettyPayloadModule()) - .add(new EnterpriseConfigurationModule()).build(); - } - - @Override - public S3AsyncClient getApi() { - return view.unwrap(AWSS3ApiMetadata.CONTEXT_TOKEN).getAsyncApi(); - } -} \ No newline at end of file diff --git a/demos/perftest/src/test/java/org/jclouds/aws/s3/Jets3tPerformanceLiveTest.java b/demos/perftest/src/test/java/org/jclouds/aws/s3/Jets3tPerformanceLiveTest.java deleted file mode 100644 index fc06a48a63..0000000000 --- a/demos/perftest/src/test/java/org/jclouds/aws/s3/Jets3tPerformanceLiveTest.java +++ /dev/null @@ -1,146 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.aws.s3; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; - -import org.jclouds.blobstore.BlobStoreContext; -import org.jets3t.service.S3Service; -import org.jets3t.service.S3ServiceException; -import org.jets3t.service.impl.rest.httpclient.RestS3Service; -import org.jets3t.service.model.S3Object; -import org.jets3t.service.security.AWSCredentials; -import org.testng.annotations.Test; - -import com.google.appengine.repackaged.com.google.common.base.Throwables; -import com.google.inject.Module; - -/** - * Runs operations that jets3t is capable of performing. - * - * @author Adrian Cole - */ -@Test(singleThreaded = true, timeOut = 2 * 60 * 1000, groups = "live", testName = "Jets3tPerformanceLiveTest") -public class Jets3tPerformanceLiveTest extends BasePerformanceLiveTest { - - public Jets3tPerformanceLiveTest(){ - exec = Executors.newCachedThreadPool(); - } - - private S3Service jetClient; - - @Override - protected BlobStoreContext createView(Properties props, Iterable modules) { - try { - jetClient = new RestS3Service(new AWSCredentials(System.getProperty("test.aws-s3.identity"), - System.getProperty("test.aws-s3.credential"))); - } catch (S3ServiceException e) { - throw Throwables.propagate(e); - } - return super.createView(props, modules); - } - - @Override - @Test(enabled = false) - public void testPutStringSerial() throws Exception { - throw new UnsupportedOperationException(); - } - - @Override - @Test(enabled = false) - public void testPutBytesSerial() throws Exception { - throw new UnsupportedOperationException(); - } - - @Override - @Test(enabled = false) - public void testPutStringParallel() throws InterruptedException, ExecutionException { - throw new UnsupportedOperationException(); - } - - @Override - @Test(enabled = false) - public void testPutBytesParallel() throws InterruptedException, ExecutionException { - throw new UnsupportedOperationException(); - } - - @Override - @Test(enabled = false) - public void testPutInputStreamParallel() throws InterruptedException, ExecutionException { - throw new UnsupportedOperationException(); - } - - @Override - @Test(enabled = false) - public void testPutFileParallel() throws InterruptedException, ExecutionException { - throw new UnsupportedOperationException(); - } - - @Override - @Test(enabled = false) - protected Future putByteArray(String bucket, String key, byte[] data, String contentType) { - throw new UnsupportedOperationException(); - } - - @Override - protected Future putFile(final String bucket, String key, File data, String contentType) { - final org.jets3t.service.model.S3Object object = new org.jets3t.service.model.S3Object(key); - object.setContentType(contentType); - object.setDataInputFile(data); - object.setContentLength(data.length()); - return exec.submit(new Callable() { - @Override - public S3Object call() throws Exception { - return jetClient.putObject(bucket, object); - } - }); - - } - - @Override - protected Future putInputStream(final String bucket, String key, InputStream data, String contentType) { - final org.jets3t.service.model.S3Object object = new org.jets3t.service.model.S3Object(key); - object.setContentType(contentType); - object.setDataInputStream(data); - try { - object.setContentLength(data.available()); - } catch (IOException e) { - Throwables.propagate(e); - } - return exec.submit(new Callable() { - @Override - public S3Object call() throws Exception { - return jetClient.putObject(bucket, object); - } - }); - } - - @Override - protected Future putString(String bucket, String key, String data, String contentType) { - throw new UnsupportedOperationException(); - } - -} \ No newline at end of file diff --git a/demos/perftest/src/test/resources/log4j.xml b/demos/perftest/src/test/resources/log4j.xml deleted file mode 100644 index e2295224af..0000000000 --- a/demos/perftest/src/test/resources/log4j.xml +++ /dev/null @@ -1,51 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/demos/perftest/src/test/resources/testimg.png b/demos/perftest/src/test/resources/testimg.png deleted file mode 100644 index 9205c47587..0000000000 Binary files a/demos/perftest/src/test/resources/testimg.png and /dev/null differ diff --git a/demos/pom.xml b/demos/pom.xml index 215749b555..a58ef337f6 100644 --- a/demos/pom.xml +++ b/demos/pom.xml @@ -23,7 +23,7 @@ jclouds-project org.jclouds - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../project/pom.xml 4.0.0 @@ -33,11 +33,9 @@ getpath googleappengine - perftest speedtest-azurequeue speedtest-sqs simpledb - tweetstore diff --git a/demos/simpledb/pom.xml b/demos/simpledb/pom.xml index 57d14e9c35..a37d0aaca1 100644 --- a/demos/simpledb/pom.xml +++ b/demos/simpledb/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-demos-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT jclouds-demo-simpledb jclouds simpledb sample that putAttributes and select it diff --git a/demos/speedtest-azurequeue/pom.xml b/demos/speedtest-azurequeue/pom.xml index 17b1b8f2b5..5daf1e5e79 100644 --- a/demos/speedtest-azurequeue/pom.xml +++ b/demos/speedtest-azurequeue/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-demos-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT jclouds-demo-speedtest-azurequeue Speed tests of Azure's queue offering diff --git a/demos/speedtest-sqs/pom.xml b/demos/speedtest-sqs/pom.xml index cacecb85cb..deba908952 100644 --- a/demos/speedtest-sqs/pom.xml +++ b/demos/speedtest-sqs/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-demos-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT jclouds-demo-speedtest-sqs Speed tests of SQS across regions diff --git a/demos/tweetstore/cf-tweetstore-spring/README.txt b/demos/tweetstore/cf-tweetstore-spring/README.txt deleted file mode 100644 index c2af578674..0000000000 --- a/demos/tweetstore/cf-tweetstore-spring/README.txt +++ /dev/null @@ -1,41 +0,0 @@ -==== - Licensed to jclouds, Inc. (jclouds) under one or more - contributor license agreements. See the NOTICE file - distributed with this work for additional information - regarding copyright ownership. jclouds licenses this file - to you under the Apache License, Version 2.0 (the - "License"); you may not use this file except in compliance - with the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, - software distributed under the License is distributed on an - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - KIND, either express or implied. See the License for the - specific language governing permissions and limitations - under the License. -==== - -A guide to generating Twitter consumer keys and access tokens is at http://tinyurl.com/2fhebgb - -Please modify your maven settings.xml like below before attempting to run 'mvn -Plive install' - - - keys - - true - - - YOUR_ACCESS_KEY_ID - YOUR_SECRET_KEY - YOUR_USER - YOUR_HEX_KEY - YOUR_ACCOUNT - YOUR_BASE64_ENCODED_KEY - YOUR_TWITTER_CONSUMER_KEY - YOUR_TWITTER_CONSUMER_SECRET - YOUR_TWITTER_ACCESSTOKEN - YOUR_TWITTER_ACCESSTOKEN_SECRET - - \ No newline at end of file diff --git a/demos/tweetstore/cf-tweetstore-spring/pom.xml b/demos/tweetstore/cf-tweetstore-spring/pom.xml deleted file mode 100644 index df33d6288f..0000000000 --- a/demos/tweetstore/cf-tweetstore-spring/pom.xml +++ /dev/null @@ -1,191 +0,0 @@ - - - - 4.0.0 - - org.jclouds - jclouds-demos-tweetstore-project - 1.5.0-SNAPSHOT - - jclouds-demo-cf-tweetstore-spring - war - jclouds TweetStore for Cloud Foundry - jclouds TweetStore for Cloud Foundry using Spring for Dependency Injection - - - 0.8.1 - jclouds-tweetstore - http://api.cloudfoundry.com - test-${cloudfoundry.applicationid}.cloudfoundry.com - 80 - jclouds-cf-tweetstore-spring - - - - - - org.springframework - spring-context - 3.0.5.RELEASE - - - - commons-logging - commons-logging - - - - - org.springframework - spring-webmvc - 3.0.5.RELEASE - - - cglib - cglib-nodep - 2.2 - runtime - - - - org.quartz-scheduler - quartz - 2.1.3 - - - org.slf4j - slf4j-api - - - - - - - org.cloudfoundry - cloudfoundry-runtime - ${cloudfoundry.version} - - - org.cloudfoundry - cloudfoundry-client-lib - 0.7.1 - test - - - org.codehaus.plexus - plexus-archiver - 2.1.1 - test - - - - - - org.springframework.maven.milestone - http://maven.springframework.org/milestone - - false - - - - - - - live - - - - maven-surefire-plugin - - - integration - integration-test - - test - - - - ${test.twitter.gae-tweetstore-spring.consumer.identity} - ${test.twitter.gae-tweetstore-spring.consumer.credential} - ${test.twitter.gae-tweetstore-spring.access.identity} - ${test.twitter.gae-tweetstore-spring.access.credential} - ${test.azureblob.identity} - ${test.azureblob.credential} - ${test.cloudfiles-us.identity} - ${test.cloudfiles-us.credential} - ${test.aws-s3.identity} - ${test.aws-s3.credential} - ${test.cloudonestorage.identity} - ${test.cloudonestorage.credential} - ${test.ninefold-storage.identity} - ${test.ninefold-storage.credential} - ${test.cloudfoundry.address} - ${test.cloudfoundry.port} - ${test.cloudfoundry.target} - ${cloudfoundry.username} - ${cloudfoundry.password} - ${jclouds.tweetstore.blobstores} - test.${jclouds.tweetstore.container} - ${project.build.directory}/${project.build.finalName} - - - - - - - - - - - deploy - - - cf-tweetstore-spring - - - - org.springframework.maven.milestone - http://maven.springframework.org/milestone - - false - - - - - - - org.cloudfoundry - cf-maven-plugin - 1.0.0.M1 - - http://api.cloudfoundry.com - ${cloudfoundry.username} - ${cloudfoundry.password} - ${cloudfoundry.applicationid} - 256 - - - - - - - diff --git a/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/paas/PlatformServices.java b/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/paas/PlatformServices.java deleted file mode 100644 index 0997005157..0000000000 --- a/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/paas/PlatformServices.java +++ /dev/null @@ -1,64 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.paas; - -import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.demo.paas.config.PlatformServicesInitializer.PLATFORM_SERVICES_ATTRIBUTE_NAME; - -import java.util.Map; - -import javax.servlet.ServletContext; - -import org.jclouds.demo.paas.service.scheduler.Scheduler; -import org.jclouds.demo.paas.service.taskqueue.TaskQueue; -import org.jclouds.javax.annotation.Nullable; - -import com.google.common.collect.ImmutableMap; - -/** - * @author Andrew Phillips - */ -public class PlatformServices { - protected final String baseUrl; - protected final Scheduler scheduler; - private ImmutableMap taskQueues; - - public PlatformServices(String baseUrl, Scheduler scheduler, Map taskQueues) { - this.baseUrl = baseUrl; - this.scheduler = scheduler; - this.taskQueues = ImmutableMap.copyOf(taskQueues); - } - - public String getBaseUrl() { - return baseUrl; - } - - public Scheduler getScheduler() { - return scheduler; - } - - public @Nullable TaskQueue getTaskQueue(String name) { - return taskQueues.get(name); - } - - public static PlatformServices get(ServletContext context) { - return (PlatformServices) checkNotNull(context.getAttribute( - PLATFORM_SERVICES_ATTRIBUTE_NAME), PLATFORM_SERVICES_ATTRIBUTE_NAME); - } -} diff --git a/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/paas/RunnableHttpRequest.java b/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/paas/RunnableHttpRequest.java deleted file mode 100644 index ad72a1a58d..0000000000 --- a/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/paas/RunnableHttpRequest.java +++ /dev/null @@ -1,126 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.paas; - -import static java.lang.String.format; - -import org.jclouds.http.HttpCommand; -import org.jclouds.http.HttpCommandExecutorService; -import org.jclouds.http.HttpRequest; - -import com.google.common.collect.ImmutableMultimap; -import com.google.common.collect.Multimap; - -public class RunnableHttpRequest implements Runnable { - public static final String PLATFORM_REQUEST_ORIGINATOR_HEADER = "X-Platform-Originator"; - - public static Factory factory(HttpCommandExecutorService httpClient) { - return factory(httpClient, format("%s@%d", Factory.class.getName(), System.currentTimeMillis())); - } - - public static Factory factory(HttpCommandExecutorService httpClient, String originator) { - return new Factory(httpClient, originator); - } - - public static class Factory { - protected final HttpCommandExecutorService httpClient; - protected final String originator; - - private Factory(HttpCommandExecutorService httpClient, String originator) { - this.httpClient = httpClient; - this.originator = originator; - } - - public RunnableHttpRequest create(HttpRequest request) { - HttpRequest requestWithSubmitter = request.toBuilder() - .headers(copyOfWithEntry(request.getHeaders(), - PLATFORM_REQUEST_ORIGINATOR_HEADER, originator)).build(); - return new RunnableHttpRequest(httpClient, requestWithSubmitter); - } - - private static Multimap copyOfWithEntry( - Multimap multimap, K k1, V v1) { - return ImmutableMultimap.builder().putAll(multimap).put(k1, v1).build(); - } - } - - private final HttpCommandExecutorService httpClient; - private final HttpRequest request; - - private RunnableHttpRequest(HttpCommandExecutorService httpClient, HttpRequest request) { - this.httpClient = httpClient; - this.request = request; - } - - @Override - public void run() { - httpClient.submit(new ImmutableHttpCommand(request)); - } - - private class ImmutableHttpCommand implements HttpCommand { - private final HttpRequest request; - - public ImmutableHttpCommand(HttpRequest request) { - this.request = request; - } - - @Override - public void setException(Exception exception) { - } - - @Override - public void setCurrentRequest(HttpRequest request) { - } - - @Override - public boolean isReplayable() { - return false; - } - - @Override - public int incrementRedirectCount() { - return 0; - } - - @Override - public int incrementFailureCount() { - return 0; - } - - @Override - public int getRedirectCount() { - return 0; - } - - @Override - public int getFailureCount() { - return 0; - } - - @Override - public Exception getException() { - return null; - } - - @Override - public HttpRequest getCurrentRequest() { - return request; - } - } -} diff --git a/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/paas/config/HttpClientModule.java b/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/paas/config/HttpClientModule.java deleted file mode 100644 index 5aa077b6cd..0000000000 --- a/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/paas/config/HttpClientModule.java +++ /dev/null @@ -1,65 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.paas.config; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.inject.name.Names.bindProperties; -import static org.jclouds.Constants.*; - -import java.util.Properties; - -import javax.servlet.ServletContext; -import javax.ws.rs.core.UriBuilder; - -import org.jclouds.demo.tweetstore.config.util.PropertiesLoader; - -import com.google.inject.AbstractModule; -import com.sun.jersey.api.uri.UriBuilderImpl; - -/** - * @author Andrew Phillips - */ -public class HttpClientModule extends AbstractModule { - private final ServletContext context; - - HttpClientModule(ServletContext context) { - this.context = context; - } - - @Override - protected void configure() { - // URL connection defaults - Properties toBind = defaultProperties(); - toBind.putAll(checkNotNull(new PropertiesLoader(context).get(), "properties")); - toBind.putAll(System.getProperties()); - bindProperties(binder(), toBind); - bind(UriBuilder.class).to(UriBuilderImpl.class); - } - - private static Properties defaultProperties() { - Properties props = new Properties(); - props.setProperty(PROPERTY_MAX_CONNECTIONS_PER_CONTEXT, 20 + ""); - props.setProperty(PROPERTY_MAX_CONNECTIONS_PER_HOST, 0 + ""); - props.setProperty(PROPERTY_SO_TIMEOUT, 60000 + ""); - props.setProperty(PROPERTY_CONNECTION_TIMEOUT, 60000 + ""); - props.setProperty(PROPERTY_USER_THREADS, 0 + ""); - props.setProperty(PROPERTY_IO_WORKER_THREADS, 20 + ""); - return props; - } -} diff --git a/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/paas/config/PlatformServicesInitializer.java b/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/paas/config/PlatformServicesInitializer.java deleted file mode 100644 index 7e0aa429ce..0000000000 --- a/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/paas/config/PlatformServicesInitializer.java +++ /dev/null @@ -1,86 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.paas.config; - -import static java.util.concurrent.TimeUnit.SECONDS; - -import javax.servlet.ServletContext; -import javax.servlet.ServletContextEvent; -import javax.servlet.ServletContextListener; - -import org.cloudfoundry.runtime.env.ApplicationInstanceInfo; -import org.cloudfoundry.runtime.env.CloudEnvironment; -import org.jclouds.concurrent.config.ExecutorServiceModule; -import org.jclouds.demo.paas.PlatformServices; -import org.jclouds.demo.paas.service.scheduler.Scheduler; -import org.jclouds.demo.paas.service.taskqueue.TaskQueue; -import org.jclouds.http.HttpCommandExecutorService; -import org.jclouds.http.config.JavaUrlHttpCommandExecutorServiceModule; - -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableMap.Builder; -import com.google.inject.Guice; - -/** - * @author Andrew Phillips - */ -public class PlatformServicesInitializer implements ServletContextListener { - public static final String PLATFORM_SERVICES_ATTRIBUTE_NAME = PlatformServices.class.getName(); - - @Override - public void contextInitialized(ServletContextEvent contextEvent) { - ServletContext context = contextEvent.getServletContext(); - context.setAttribute(PLATFORM_SERVICES_ATTRIBUTE_NAME, createServices(context)); - } - - protected static PlatformServices createServices(ServletContext context) { - HttpCommandExecutorService httpClient = createHttpClient(context); - return new PlatformServices(getBaseUrl(context), new Scheduler(httpClient), - createTaskQueues(httpClient)); - } - - protected static HttpCommandExecutorService createHttpClient( - final ServletContext context) { - return Guice.createInjector(new ExecutorServiceModule(), - new JavaUrlHttpCommandExecutorServiceModule(), - new HttpClientModule(context)) - .getInstance(HttpCommandExecutorService.class); - } - - protected static String getBaseUrl(ServletContext context) { - ApplicationInstanceInfo instanceInfo = new CloudEnvironment().getInstanceInfo(); - // using localhost instead of instanceInfo.getHost(). See http://support.cloudfoundry.com/requests/102117 - return "http://127.0.0.1:" + instanceInfo.getPort() + context.getContextPath(); - } - - // TODO: make the number and names of queues configurable - protected static ImmutableMap createTaskQueues(HttpCommandExecutorService httpClient) { - Builder taskQueues = ImmutableMap.builder(); - taskQueues.put("twitter", TaskQueue.builder(httpClient) - .name("twitter").period(SECONDS.toMillis(30)) - .build()); - return taskQueues.build(); - } - - @Override - public void contextDestroyed(ServletContextEvent servletContextEvent) { - ServletContext context = servletContextEvent.getServletContext(); - context.removeAttribute(PLATFORM_SERVICES_ATTRIBUTE_NAME); - } -} diff --git a/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/paas/service/scheduler/HttpRequestJob.java b/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/paas/service/scheduler/HttpRequestJob.java deleted file mode 100644 index 902f5fe356..0000000000 --- a/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/paas/service/scheduler/HttpRequestJob.java +++ /dev/null @@ -1,69 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.paas.service.scheduler; - -import static com.google.common.base.Preconditions.checkNotNull; - -import java.net.URI; - -import javax.servlet.ServletContext; - -import org.jclouds.demo.paas.PlatformServices; -import org.jclouds.demo.paas.RunnableHttpRequest; -import org.jclouds.http.HttpRequest; -import org.quartz.Job; -import org.quartz.JobExecutionContext; -import org.quartz.JobExecutionException; -import org.quartz.SchedulerException; - -/** - * @author Andrew Phillips - */ -public class HttpRequestJob implements Job { - protected static final String URL_ATTRIBUTE_NAME = "url"; - - // keep in sync with "quartz:scheduler-context-servlet-context-key" param in web.xml - protected static final String SERVLET_CONTEXT_KEY = "servlet-context"; - - @Override - public void execute(JobExecutionContext context) throws JobExecutionException { - PlatformServices platform = JobContexts.getPlatform(context); - RunnableHttpRequest request = platform.getScheduler().getHttpRequestFactory().create( - HttpRequest.builder() - .endpoint(JobContexts.getTargetUrl(platform.getBaseUrl(), context)) - .method("GET").build()); - request.run(); - } - - private static class JobContexts { - private static URI getTargetUrl(String baseUrl, JobExecutionContext context) { - return URI.create(baseUrl + (String) checkNotNull( - context.getMergedJobDataMap().get(URL_ATTRIBUTE_NAME), URL_ATTRIBUTE_NAME)); - } - - private static PlatformServices getPlatform(JobExecutionContext jobContext) throws JobExecutionException { - try { - return PlatformServices.get((ServletContext) checkNotNull( - jobContext.getScheduler().getContext().get(SERVLET_CONTEXT_KEY), SERVLET_CONTEXT_KEY)); - } catch (SchedulerException exception) { - throw new JobExecutionException("Unable to get platform services from the job execution context", exception); - } - } - } -} diff --git a/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/paas/service/scheduler/quartz/plugins/TransactionlessXmlSchedulingDataProcessorPlugin.java b/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/paas/service/scheduler/quartz/plugins/TransactionlessXmlSchedulingDataProcessorPlugin.java deleted file mode 100644 index b47f81dfad..0000000000 --- a/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/paas/service/scheduler/quartz/plugins/TransactionlessXmlSchedulingDataProcessorPlugin.java +++ /dev/null @@ -1,401 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.paas.service.scheduler.quartz.plugins; - -import static org.quartz.SimpleScheduleBuilder.simpleSchedule; -import static org.quartz.TriggerBuilder.newTrigger; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.UnsupportedEncodingException; -import java.net.URL; -import java.net.URLDecoder; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Set; -import java.util.StringTokenizer; - -import org.jclouds.logging.Logger; -import org.quartz.JobBuilder; -import org.quartz.JobDetail; -import org.quartz.Scheduler; -import org.quartz.SchedulerException; -import org.quartz.SimpleTrigger; -import org.quartz.TriggerKey; -import org.quartz.jobs.FileScanJob; -import org.quartz.jobs.FileScanListener; -import org.quartz.plugins.xml.XMLSchedulingDataProcessorPlugin; -import org.quartz.simpl.CascadingClassLoadHelper; -import org.quartz.spi.ClassLoadHelper; -import org.quartz.spi.SchedulerPlugin; -import org.quartz.xml.XMLSchedulingDataProcessor; - -/** - * A copy of {@link XMLSchedulingDataProcessorPlugin} that does not reference - * {@code javax.transaction.UserTransaction} as so does not require a dependency - * on JTA. - * - * @author Andrew Phillips - * @see XMLSchedulingDataProcessorPlugin - */ -public class TransactionlessXmlSchedulingDataProcessorPlugin implements - FileScanListener, SchedulerPlugin { - - /* - * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - * - * Data members. - * - * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - */ - private static final int MAX_JOB_TRIGGER_NAME_LEN = 80; - private static final String JOB_INITIALIZATION_PLUGIN_NAME = "JobSchedulingDataLoaderPlugin"; - private static final String FILE_NAME_DELIMITERS = ","; - - private String name; - private Scheduler scheduler; - private final Logger log = Logger.CONSOLE; - - private boolean failOnFileNotFound = true; - - private String fileNames = XMLSchedulingDataProcessor.QUARTZ_XML_DEFAULT_FILE_NAME; - - // Populated by initialization - private Map jobFiles = new LinkedHashMap(); - - private long scanInterval = 0; - - boolean started = false; - - protected ClassLoadHelper classLoadHelper = null; - - private Set jobTriggerNameSet = new HashSet(); - - /* - * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - * - * Interface. - * - * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - */ - - /** - * Comma separated list of file names (with paths) to the XML files that should be read. - */ - public String getFileNames() { - return fileNames; - } - - /** - * The file name (and path) to the XML file that should be read. - */ - public void setFileNames(String fileNames) { - this.fileNames = fileNames; - } - - /** - * The interval (in seconds) at which to scan for changes to the file. - * If the file has been changed, it is re-loaded and parsed. The default - * value for the interval is 0, which disables scanning. - * - * @return Returns the scanInterval. - */ - public long getScanInterval() { - return scanInterval / 1000; - } - - /** - * The interval (in seconds) at which to scan for changes to the file. - * If the file has been changed, it is re-loaded and parsed. The default - * value for the interval is 0, which disables scanning. - * - * @param scanInterval The scanInterval to set. - */ - public void setScanInterval(long scanInterval) { - this.scanInterval = scanInterval * 1000; - } - - /** - * Whether or not initialization of the plugin should fail (throw an - * exception) if the file cannot be found. Default is true. - */ - public boolean isFailOnFileNotFound() { - return failOnFileNotFound; - } - - /** - * Whether or not initialization of the plugin should fail (throw an - * exception) if the file cannot be found. Default is true. - */ - public void setFailOnFileNotFound(boolean failOnFileNotFound) { - this.failOnFileNotFound = failOnFileNotFound; - } - - /* - * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - * - * SchedulerPlugin Interface. - * - * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - */ - - /** - *

- * Called during creation of the Scheduler in order to give - * the SchedulerPlugin a chance to initialize. - *

- * - * @throws org.quartz.SchedulerConfigException - * if there is an error initializing. - */ - @Override - public void initialize(String name, Scheduler scheduler) - throws SchedulerException { - this.name = name; - this.scheduler = scheduler; - - classLoadHelper = new CascadingClassLoadHelper(); - classLoadHelper.initialize(); - - log.info("Registering Quartz Job Initialization Plug-in."); - - // Create JobFile objects - StringTokenizer stok = new StringTokenizer(fileNames, FILE_NAME_DELIMITERS); - while (stok.hasMoreTokens()) { - final String fileName = stok.nextToken(); - final JobFile jobFile = new JobFile(fileName); - jobFiles.put(fileName, jobFile); - } - } - - @Override - public void start() { - try { - if (jobFiles.isEmpty() == false) { - - if (scanInterval > 0) { - scheduler.getContext().put(JOB_INITIALIZATION_PLUGIN_NAME + '_' + name, this); - } - - Iterator iterator = jobFiles.values().iterator(); - while (iterator.hasNext()) { - JobFile jobFile = iterator.next(); - - if (scanInterval > 0) { - String jobTriggerName = buildJobTriggerName(jobFile.getFileBasename()); - TriggerKey tKey = new TriggerKey(jobTriggerName, JOB_INITIALIZATION_PLUGIN_NAME); - - // remove pre-existing job/trigger, if any - scheduler.unscheduleJob(tKey); - - // TODO: convert to use builder - SimpleTrigger trig = newTrigger() - .withIdentity(jobTriggerName, JOB_INITIALIZATION_PLUGIN_NAME) - .startNow() - .endAt(null) - .withSchedule(simpleSchedule() - .repeatForever() - .withIntervalInMilliseconds(scanInterval)) - .build(); - - JobDetail job = JobBuilder.newJob(FileScanJob.class) - .withIdentity(jobTriggerName, JOB_INITIALIZATION_PLUGIN_NAME) - .build(); - job.getJobDataMap().put(FileScanJob.FILE_NAME, jobFile.getFileName()); - job.getJobDataMap().put(FileScanJob.FILE_SCAN_LISTENER_NAME, JOB_INITIALIZATION_PLUGIN_NAME + '_' + name); - - scheduler.scheduleJob(job, trig); - log.debug("Scheduled file scan job for data file: {}, at interval: {}", jobFile.getFileName(), scanInterval); - } - - processFile(jobFile); - } - } - } catch(SchedulerException se) { - log.error("Error starting background-task for watching jobs file.", se); - } finally { - started = true; - } - } - - /** - * Helper method for generating unique job/trigger name for the - * file scanning jobs (one per FileJob). The unique names are saved - * in jobTriggerNameSet. - */ - private String buildJobTriggerName( - String fileBasename) { - // Name w/o collisions will be prefix + _ + filename (with '.' of filename replaced with '_') - // For example: JobInitializationPlugin_jobInitializer_myjobs_xml - String jobTriggerName = JOB_INITIALIZATION_PLUGIN_NAME + '_' + name + '_' + fileBasename.replace('.', '_'); - - // If name is too long (DB column is 80 chars), then truncate to max length - if (jobTriggerName.length() > MAX_JOB_TRIGGER_NAME_LEN) { - jobTriggerName = jobTriggerName.substring(0, MAX_JOB_TRIGGER_NAME_LEN); - } - - // Make sure this name is unique in case the same file name under different - // directories is being checked, or had a naming collision due to length truncation. - // If there is a conflict, keep incrementing a _# suffix on the name (being sure - // not to get too long), until we find a unique name. - int currentIndex = 1; - while (jobTriggerNameSet.add(jobTriggerName) == false) { - // If not our first time through, then strip off old numeric suffix - if (currentIndex > 1) { - jobTriggerName = jobTriggerName.substring(0, jobTriggerName.lastIndexOf('_')); - } - - String numericSuffix = "_" + currentIndex++; - - // If the numeric suffix would make the name too long, then make room for it. - if (jobTriggerName.length() > (MAX_JOB_TRIGGER_NAME_LEN - numericSuffix.length())) { - jobTriggerName = jobTriggerName.substring(0, (MAX_JOB_TRIGGER_NAME_LEN - numericSuffix.length())); - } - - jobTriggerName += numericSuffix; - } - - return jobTriggerName; - } - - @Override - public void shutdown() { - // nothing to do - } - - private void processFile(JobFile jobFile) { - if (jobFile == null || !jobFile.getFileFound()) { - return; - } - - try { - XMLSchedulingDataProcessor processor = - new XMLSchedulingDataProcessor(this.classLoadHelper); - - processor.addJobGroupToNeverDelete(JOB_INITIALIZATION_PLUGIN_NAME); - processor.addTriggerGroupToNeverDelete(JOB_INITIALIZATION_PLUGIN_NAME); - - processor.processFileAndScheduleJobs( - jobFile.getFileName(), - jobFile.getFileName(), // systemId - scheduler); - } catch (Exception e) { - log.error("Error scheduling jobs: " + e.getMessage(), e); - } - } - - public void processFile(String filePath) { - processFile((JobFile)jobFiles.get(filePath)); - } - - /** - * @see org.quartz.jobs.FileScanListener#fileUpdated(java.lang.String) - */ - public void fileUpdated(String fileName) { - if (started) { - processFile(fileName); - } - } - - class JobFile { - private String fileName; - - // These are set by initialize() - private String filePath; - private String fileBasename; - private boolean fileFound; - - protected JobFile(String fileName) throws SchedulerException { - this.fileName = fileName; - initialize(); - } - - protected String getFileName() { - return fileName; - } - - protected boolean getFileFound() { - return fileFound; - } - - protected String getFilePath() { - return filePath; - } - - protected String getFileBasename() { - return fileBasename; - } - - private void initialize() throws SchedulerException { - InputStream f = null; - try { - String furl = null; - - File file = new File(getFileName()); // files in filesystem - if (!file.exists()) { - URL url = classLoadHelper.getResource(getFileName()); - if(url != null) { - try { - furl = URLDecoder.decode(url.getPath(), "UTF-8"); - } catch (UnsupportedEncodingException e) { - furl = url.getPath(); - } - file = new File(furl); - try { - f = url.openStream(); - } catch (IOException ignore) { - // Swallow the exception - } - } - } else { - try { - f = new java.io.FileInputStream(file); - }catch (FileNotFoundException e) { - // ignore - } - } - - if (f == null) { - if (isFailOnFileNotFound()) { - throw new SchedulerException( - "File named '" + getFileName() + "' does not exist."); - } else { - log.warn("File named '" + getFileName() + "' does not exist."); - } - } else { - fileFound = true; - } - filePath = (furl != null) ? furl : file.getAbsolutePath(); - fileBasename = file.getName(); - } finally { - try { - if (f != null) { - f.close(); - } - } catch (IOException ioe) { - log.warn("Error closing jobs file " + getFileName(), ioe); - } - } - } - } -} \ No newline at end of file diff --git a/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/paas/service/taskqueue/TaskQueue.java b/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/paas/service/taskqueue/TaskQueue.java deleted file mode 100644 index e317a305cf..0000000000 --- a/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/paas/service/taskqueue/TaskQueue.java +++ /dev/null @@ -1,107 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.paas.service.taskqueue; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; -import static java.lang.String.format; - -import java.util.Timer; -import java.util.TimerTask; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.TimeUnit; - -import org.jclouds.demo.paas.RunnableHttpRequest; -import org.jclouds.demo.paas.RunnableHttpRequest.Factory; -import org.jclouds.http.HttpCommandExecutorService; - -import com.google.inject.Provider; - -public class TaskQueue { - protected final Factory httpRequestFactory; - private final Timer timer; - private final ConcurrentLinkedQueue tasks = new ConcurrentLinkedQueue(); - - private TaskQueue(String name, long pollingIntervalMillis, Factory httpRequestFactory) { - this.httpRequestFactory = httpRequestFactory; - timer = new Timer(name); - timer.scheduleAtFixedRate(new TimerTask() { - @Override - public void run() { - Runnable task = tasks.poll(); - if (task != null) { - task.run(); - } - } - }, 0, pollingIntervalMillis); - } - - public void add(final Runnable task) { - tasks.add(task); - } - - public Factory getHttpRequestFactory() { - return httpRequestFactory; - } - - public void destroy() { - timer.cancel(); - tasks.clear(); - } - - public static Builder builder(HttpCommandExecutorService httpClient) { - return new Builder(httpClient); - } - - public static class Builder implements Provider { - protected final HttpCommandExecutorService httpClient; - protected String name = "default"; - protected long pollingIntervalMillis = TimeUnit.SECONDS.toMillis(1); - - private Builder(HttpCommandExecutorService httpClient) { - this.httpClient = checkNotNull(httpClient, "httpClient"); - } - - public Builder name(String name) { - this.name = checkNotNull(name, "name"); - return this; - } - - public Builder period(TimeUnit period) { - this.pollingIntervalMillis = checkNotNull(period, "period").toMillis(1); - return this; - } - - public Builder period(long pollingIntervalMillis) { - checkArgument(pollingIntervalMillis > 0, "pollingIntervalMillis"); - this.pollingIntervalMillis = pollingIntervalMillis; - return this; - } - - public TaskQueue build() { - return new TaskQueue(name, pollingIntervalMillis, - RunnableHttpRequest.factory(httpClient, format("taskqueue-%s", name))); - } - - @Override - public TaskQueue get() { - return build(); - } - } -} \ No newline at end of file diff --git a/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/config/DelegatingAutowireCapableBeanFactory.java b/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/config/DelegatingAutowireCapableBeanFactory.java deleted file mode 100644 index 7fda1bb2f0..0000000000 --- a/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/config/DelegatingAutowireCapableBeanFactory.java +++ /dev/null @@ -1,129 +0,0 @@ -package org.jclouds.demo.tweetstore.config; - -import java.util.Set; - -import org.springframework.beans.BeansException; -import org.springframework.beans.TypeConverter; -import org.springframework.beans.factory.NoSuchBeanDefinitionException; -import org.springframework.beans.factory.config.AutowireCapableBeanFactory; -import org.springframework.beans.factory.config.DependencyDescriptor; - -class DelegatingAutowireCapableBeanFactory implements AutowireCapableBeanFactory { - private final AutowireCapableBeanFactory delegate; - - DelegatingAutowireCapableBeanFactory(AutowireCapableBeanFactory delegate) { - this.delegate = delegate; - } - - public T createBean(Class beanClass) throws BeansException { - return delegate.createBean(beanClass); - } - - public void autowireBean(Object existingBean) throws BeansException { - delegate.autowireBean(existingBean); - } - - public Object configureBean(Object existingBean, String beanName) - throws BeansException { - return delegate.configureBean(existingBean, beanName); - } - - public Object getBean(String name) throws BeansException { - return delegate.getBean(name); - } - - public Object resolveDependency(DependencyDescriptor descriptor, - String beanName) throws BeansException { - return delegate.resolveDependency(descriptor, beanName); - } - - public T getBean(String name, Class requiredType) - throws BeansException { - return delegate.getBean(name, requiredType); - } - - @SuppressWarnings("rawtypes") - public Object createBean(Class beanClass, int autowireMode, - boolean dependencyCheck) throws BeansException { - return delegate.createBean(beanClass, autowireMode, dependencyCheck); - } - - public T getBean(Class requiredType) throws BeansException { - return delegate.getBean(requiredType); - } - - @SuppressWarnings("rawtypes") - public Object autowire(Class beanClass, int autowireMode, - boolean dependencyCheck) throws BeansException { - return delegate.autowire(beanClass, autowireMode, dependencyCheck); - } - - public Object getBean(String name, Object... args) throws BeansException { - return delegate.getBean(name, args); - } - - public void autowireBeanProperties(Object existingBean, int autowireMode, - boolean dependencyCheck) throws BeansException { - delegate.autowireBeanProperties(existingBean, autowireMode, - dependencyCheck); - } - - public boolean containsBean(String name) { - return delegate.containsBean(name); - } - - public boolean isSingleton(String name) - throws NoSuchBeanDefinitionException { - return delegate.isSingleton(name); - } - - public void applyBeanPropertyValues(Object existingBean, String beanName) - throws BeansException { - delegate.applyBeanPropertyValues(existingBean, beanName); - } - - public boolean isPrototype(String name) - throws NoSuchBeanDefinitionException { - return delegate.isPrototype(name); - } - - @SuppressWarnings("rawtypes") - public boolean isTypeMatch(String name, Class targetType) - throws NoSuchBeanDefinitionException { - return delegate.isTypeMatch(name, targetType); - } - - public Object initializeBean(Object existingBean, String beanName) - throws BeansException { - return delegate.initializeBean(existingBean, beanName); - } - - public Class getType(String name) throws NoSuchBeanDefinitionException { - return delegate.getType(name); - } - - public Object applyBeanPostProcessorsBeforeInitialization( - Object existingBean, String beanName) throws BeansException { - return delegate.applyBeanPostProcessorsBeforeInitialization( - existingBean, beanName); - } - - public String[] getAliases(String name) { - return delegate.getAliases(name); - } - - public Object applyBeanPostProcessorsAfterInitialization( - Object existingBean, String beanName) throws BeansException { - return delegate.applyBeanPostProcessorsAfterInitialization( - existingBean, beanName); - } - - public Object resolveDependency(DependencyDescriptor descriptor, - String beanName, Set autowiredBeanNames, - TypeConverter typeConverter) throws BeansException { - return delegate.resolveDependency(descriptor, beanName, - autowiredBeanNames, typeConverter); - } - - -} diff --git a/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/config/LoggingConfig.java b/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/config/LoggingConfig.java deleted file mode 100644 index e322b0551b..0000000000 --- a/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/config/LoggingConfig.java +++ /dev/null @@ -1,101 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.config; - -import static com.google.common.base.Preconditions.checkArgument; -import static java.lang.String.format; -import static org.jclouds.logging.LoggingModules.firstOrJDKLoggingModule; - -import java.util.Set; - -import javax.annotation.PostConstruct; - -import org.jclouds.logging.Logger; -import org.jclouds.logging.Logger.LoggerFactory; -import org.springframework.beans.BeansException; -import org.springframework.beans.TypeConverter; -import org.springframework.beans.factory.BeanFactory; -import org.springframework.beans.factory.BeanFactoryAware; -import org.springframework.beans.factory.config.AutowireCapableBeanFactory; -import org.springframework.beans.factory.config.DependencyDescriptor; -import org.springframework.context.annotation.AnnotationConfigUtils; -import org.springframework.context.annotation.CommonAnnotationBeanPostProcessor; - -/** - * Spring config that sets up {@link CommonAnnotationBeanPostProcessor} support - * for injecting loggers. - * - * @author Andrew Phillips - */ -abstract class LoggingConfig implements BeanFactoryAware { - protected static final LoggerFactory LOGGER_FACTORY = firstOrJDKLoggingModule().createLoggerFactory(); - - private static final Logger LOGGER = LOGGER_FACTORY.getLogger(LoggingConfig.class.getName()); - - private AutowireCapableBeanFactory beanFactory; - - @PostConstruct - public void initLoggerSupport() { - CommonAnnotationBeanPostProcessor resourceProcessor = - (CommonAnnotationBeanPostProcessor) beanFactory.getBean(AnnotationConfigUtils.COMMON_ANNOTATION_PROCESSOR_BEAN_NAME); - resourceProcessor.setResourceFactory(new LoggerResourceBeanFactory(beanFactory)); - } - - private static class LoggerResourceBeanFactory extends DelegatingAutowireCapableBeanFactory { - - LoggerResourceBeanFactory(AutowireCapableBeanFactory delegate) { - super(delegate); - } - - @Override - public Object resolveDependency(DependencyDescriptor descriptor, - String beanName, Set autowiredBeanNames, - TypeConverter typeConverter) throws BeansException { - if (descriptor.getDependencyType().equals(Logger.class)) { - Class requestingType = getType(beanName); - LOGGER.trace("About to resolve logger for bean '%s' of type '%s'", - beanName, requestingType); - Logger logger = resolveLogger(requestingType, autowiredBeanNames); - LOGGER.trace("Successfully resolved logger."); - return logger; - } - return super.resolveDependency(descriptor, beanName, autowiredBeanNames, typeConverter); - } - - private Logger resolveLogger(Class type, Set autowiredBeanNames) { - String loggerBeanName = format("%s#logger", type); - if (autowiredBeanNames.contains(loggerBeanName)) { - LOGGER.trace("Returning existing bean '%s'", loggerBeanName); - return (Logger) getBean(loggerBeanName); - } - - LOGGER.trace("About to create logger for type '%s'", type); - Logger logger = LOGGER_FACTORY.getLogger(type.getName()); - LOGGER.trace("Successfully created logger."); - return logger; - } - } - - @Override - public void setBeanFactory(BeanFactory beanFactory) throws BeansException { - checkArgument(beanFactory instanceof AutowireCapableBeanFactory, "expected an instance of '%s' but was '%s'", - AutowireCapableBeanFactory.class, beanFactory.getClass()); - this.beanFactory = (AutowireCapableBeanFactory) beanFactory; - } -} \ No newline at end of file diff --git a/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/config/SpringServletConfig.java b/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/config/SpringServletConfig.java deleted file mode 100644 index 3fd8549621..0000000000 --- a/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/config/SpringServletConfig.java +++ /dev/null @@ -1,242 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.config; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Preconditions.checkState; -import static com.google.common.base.Predicates.in; -import static com.google.common.collect.ImmutableSet.copyOf; -import static com.google.common.collect.Sets.filter; -import static org.jclouds.demo.tweetstore.reference.TweetStoreConstants.PROPERTY_TWEETSTORE_BLOBSTORES; -import static org.jclouds.demo.tweetstore.reference.TweetStoreConstants.PROPERTY_TWEETSTORE_CONTAINER; -import static org.jclouds.demo.tweetstore.reference.TwitterConstants.PROPERTY_TWITTER_ACCESSTOKEN; -import static org.jclouds.demo.tweetstore.reference.TwitterConstants.PROPERTY_TWITTER_ACCESSTOKEN_SECRET; -import static org.jclouds.demo.tweetstore.reference.TwitterConstants.PROPERTY_TWITTER_CONSUMER_KEY; -import static org.jclouds.demo.tweetstore.reference.TwitterConstants.PROPERTY_TWITTER_CONSUMER_SECRET; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Map; -import java.util.Properties; -import java.util.Set; - -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; -import javax.servlet.Servlet; -import javax.servlet.ServletConfig; -import javax.servlet.ServletException; - -import org.jclouds.ContextBuilder; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.demo.paas.PlatformServices; -import org.jclouds.demo.paas.service.taskqueue.TaskQueue; -import org.jclouds.demo.tweetstore.config.util.CredentialsCollector; -import org.jclouds.demo.tweetstore.controller.AddTweetsController; -import org.jclouds.demo.tweetstore.controller.ClearTweetsController; -import org.jclouds.demo.tweetstore.controller.EnqueueStoresController; -import org.jclouds.demo.tweetstore.controller.StoreTweetsController; -import org.jclouds.demo.tweetstore.functions.ServiceToStoredTweetStatuses; -import org.jclouds.logging.Logger; -import org.springframework.beans.factory.BeanCreationException; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.context.ServletConfigAware; -import org.springframework.web.servlet.HandlerAdapter; -import org.springframework.web.servlet.HandlerMapping; -import org.springframework.web.servlet.handler.SimpleServletHandlerAdapter; -import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping; - -import twitter4j.Twitter; -import twitter4j.TwitterFactory; -import twitter4j.conf.ConfigurationBuilder; - -import com.google.common.base.Splitter; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Maps; -import com.google.common.io.Closeables; -import com.google.inject.Module; - -/** - * Creates servlets (using resources from the {@link SpringAppConfig}) and mappings. - * - * @author Andrew Phillips - * @see SpringAppConfig - */ -@Configuration -public class SpringServletConfig extends LoggingConfig implements ServletConfigAware { - public static final String PROPERTY_BLOBSTORE_CONTEXTS = "blobstore.contexts"; - - private static final Logger LOGGER = LOGGER_FACTORY.getLogger(SpringServletConfig.class.getName()); - - private ServletConfig servletConfig; - - private Map providerTypeToBlobStoreMap; - private Twitter twitterClient; - private String container; - private TaskQueue queue; - private String baseUrl; - - @PostConstruct - public void initialize() throws IOException { - Properties props = loadJCloudsProperties(); - LOGGER.trace("About to initialize members."); - - Set modules = ImmutableSet.of(); - // shared across all blobstores and used to retrieve tweets - try { - twitter4j.conf.Configuration twitterConf = new ConfigurationBuilder() - .setOAuthConsumerKey(props.getProperty(PROPERTY_TWITTER_CONSUMER_KEY)) - .setOAuthConsumerSecret(props.getProperty(PROPERTY_TWITTER_CONSUMER_SECRET)) - .setOAuthAccessToken(props.getProperty(PROPERTY_TWITTER_ACCESSTOKEN)) - .setOAuthAccessTokenSecret(props.getProperty(PROPERTY_TWITTER_ACCESSTOKEN_SECRET)) - .build(); - twitterClient = new TwitterFactory(twitterConf).getInstance(); - } catch (IllegalArgumentException e) { - throw new IllegalArgumentException("properties for twitter not configured properly in " + props.toString(), e); - } - // common namespace for storing tweets - container = checkNotNull(props.getProperty(PROPERTY_TWEETSTORE_CONTAINER), PROPERTY_TWEETSTORE_CONTAINER); - - // instantiate and store references to all blobstores by provider name - providerTypeToBlobStoreMap = Maps.newHashMap(); - for (String hint : getBlobstoreContexts(props)) { - providerTypeToBlobStoreMap.put(hint, ContextBuilder.newBuilder(hint) - .modules(modules).overrides(props).build(BlobStoreContext.class)); - } - - // get a queue for submitting store tweet requests and the application's base URL - PlatformServices platform = PlatformServices.get(servletConfig.getServletContext()); - queue = platform.getTaskQueue("twitter"); - baseUrl = platform.getBaseUrl(); - - LOGGER.trace("Members initialized. Twitter: '%s', container: '%s', provider types: '%s'", twitterClient, - container, providerTypeToBlobStoreMap.keySet()); - } - - private static Iterable getBlobstoreContexts(Properties props) { - Set contexts = new CredentialsCollector().apply(props).keySet(); - String explicitContexts = props.getProperty(PROPERTY_TWEETSTORE_BLOBSTORES); - if (explicitContexts != null) { - contexts = filter(contexts, in(copyOf(Splitter.on(',').split(explicitContexts)))); - } - checkState(!contexts.isEmpty(), "no credentials available for any requested context"); - return contexts; - } - - private Properties loadJCloudsProperties() { - LOGGER.trace("About to read properties from '%s'", "/WEB-INF/jclouds.properties"); - Properties props = new Properties(); - InputStream input = servletConfig.getServletContext().getResourceAsStream("/WEB-INF/jclouds.properties"); - try { - props.load(input); - } catch (IOException e) { - throw new RuntimeException(e); - } finally { - Closeables.closeQuietly(input); - } - LOGGER.trace("Properties successfully read."); - return props; - } - - @Bean - public StoreTweetsController storeTweetsController() { - StoreTweetsController controller = new StoreTweetsController(providerTypeToBlobStoreMap, container, twitterClient); - injectServletConfig(controller); - return controller; - } - - @Bean - public AddTweetsController addTweetsController() { - AddTweetsController controller = new AddTweetsController(providerTypeToBlobStoreMap, - serviceToStoredTweetStatuses()); - injectServletConfig(controller); - return controller; - } - - @Bean - public EnqueueStoresController enqueueStoresController() { - return new EnqueueStoresController(providerTypeToBlobStoreMap, queue, baseUrl); - } - - @Bean - public ClearTweetsController clearTweetsController() { - return new ClearTweetsController(providerTypeToBlobStoreMap, container); - } - - private void injectServletConfig(Servlet servlet) { - LOGGER.trace("About to inject servlet config '%s'", servletConfig); - try { - servlet.init(checkNotNull(servletConfig)); - } catch (ServletException exception) { - throw new BeanCreationException("Unable to instantiate " + servlet, exception); - } - LOGGER.trace("Successfully injected servlet config."); - } - - @Bean - ServiceToStoredTweetStatuses serviceToStoredTweetStatuses() { - return new ServiceToStoredTweetStatuses(providerTypeToBlobStoreMap, container); - } - - @Bean - public HandlerMapping handlerMapping() { - SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping(); - Map urlMap = Maps.newHashMapWithExpectedSize(2); - urlMap.put("/store/*", storeTweetsController()); - urlMap.put("/tweets/*", addTweetsController()); - urlMap.put("/stores/*", enqueueStoresController()); - urlMap.put("/clear/*", clearTweetsController()); - mapping.setUrlMap(urlMap); - /* - * "/store", "/tweets" and "/stores" are part of the servlet mapping and thus - * stripped by the mapping if using default settings. - */ - mapping.setAlwaysUseFullPath(true); - return mapping; - } - - @Bean - public HandlerAdapter servletHandlerAdapter() { - return new SimpleServletHandlerAdapter(); - } - - @PreDestroy - public void destroy() throws Exception { - LOGGER.trace("About to close contexts."); - for (BlobStoreContext context : providerTypeToBlobStoreMap.values()) { - context.close(); - } - LOGGER.trace("Contexts closed."); - LOGGER.trace("About to purge request queue."); - queue.destroy(); - LOGGER.trace("Request queue purged."); - } - - /* - * (non-Javadoc) - * - * @see - * org.springframework.web.context.ServletConfigAware#setServletConfig(javax.servlet.ServletConfig - * ) - */ - @Override - public void setServletConfig(ServletConfig servletConfig) { - this.servletConfig = servletConfig; - } -} \ No newline at end of file diff --git a/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/config/util/CredentialsCollector.java b/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/config/util/CredentialsCollector.java deleted file mode 100644 index ce3943376e..0000000000 --- a/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/config/util/CredentialsCollector.java +++ /dev/null @@ -1,153 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.config.util; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Preconditions.checkState; -import static com.google.common.base.Predicates.notNull; -import static com.google.common.collect.Collections2.filter; -import static com.google.common.collect.Collections2.transform; -import static com.google.common.collect.ImmutableSet.copyOf; -import static com.google.common.collect.Maps.filterValues; -import static org.jclouds.util.Maps2.fromKeys; - -import java.util.Collection; -import java.util.Map; -import java.util.Properties; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.jclouds.demo.tweetstore.config.util.CredentialsCollector.Credential; - -import com.google.common.annotations.GwtIncompatible; -import com.google.common.base.Function; -import com.google.common.base.Predicate; - -/** - * Reads provider credentials from a {@link Properties} bag. - * - * @author Andrew Phillips - * - */ -public class CredentialsCollector implements Function> { - private static final String IDENTITY_PROPERTY_SUFFIX = ".identity"; - private static final String CREDENTIAL_PROPERTY_SUFFIX = ".credential"; - - // using the identity for provider name extraction - private static final Pattern IDENTITY_PROPERTY_PATTERN = - Pattern.compile("([a-zA-Z0-9-]+)" + Pattern.quote(IDENTITY_PROPERTY_SUFFIX)); - - @Override - public Map apply(final Properties properties) { - Collection providerNames = transform( - filter(properties.stringPropertyNames(), MatchesPattern.matches(IDENTITY_PROPERTY_PATTERN)), - new Function() { - @Override - public String apply(String input) { - Matcher matcher = IDENTITY_PROPERTY_PATTERN.matcher(input); - // as a side-effect, sets the matching group! - checkState(matcher.matches(), "'%s' should match '%s'", input, IDENTITY_PROPERTY_PATTERN); - return matcher.group(1); - } - }); - /* - * Providers without a credential property result in null values, which are - * removed from the returned map. - */ - return filterValues(fromKeys(copyOf(providerNames), new Function() { - @Override - public Credential apply(String providerName) { - String identity = properties.getProperty(providerName + IDENTITY_PROPERTY_SUFFIX); - String credential = properties.getProperty(providerName + CREDENTIAL_PROPERTY_SUFFIX); - return (((identity != null) && (credential != null)) - ? new Credential(identity, credential) - : null); - } - }), notNull()); - } - - public static class Credential { - private final String identity; - private final String credential; - - public Credential(String identity, String credential) { - this.identity = checkNotNull(identity, "identity"); - this.credential = checkNotNull(credential, "credential"); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result - + ((credential == null) ? 0 : credential.hashCode()); - result = prime * result - + ((identity == null) ? 0 : identity.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Credential other = (Credential) obj; - if (credential == null) { - if (other.credential != null) - return false; - } else if (!credential.equals(other.credential)) - return false; - if (identity == null) { - if (other.identity != null) - return false; - } else if (!identity.equals(other.identity)) - return false; - return true; - } - - public String getIdentity() { - return identity; - } - - public String getCredential() { - return credential; - } - } - - @GwtIncompatible(value = "java.util.regex.Pattern") - private static class MatchesPattern implements Predicate { - private final Pattern pattern; - - private MatchesPattern(Pattern pattern) { - this.pattern = pattern; - } - - @Override - public boolean apply(String input) { - return pattern.matcher(input).matches(); - } - - private static MatchesPattern matches(Pattern pattern) { - return new MatchesPattern(pattern); - } - } -} diff --git a/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/config/util/PropertiesLoader.java b/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/config/util/PropertiesLoader.java deleted file mode 100644 index dafa5c311b..0000000000 --- a/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/config/util/PropertiesLoader.java +++ /dev/null @@ -1,59 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.config.util; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; - -import javax.servlet.ServletContext; - -import com.google.common.io.Closeables; -import com.google.inject.Provider; - -/** - * @author Andrew Phillips - */ -public class PropertiesLoader implements Provider{ - private static final String PROPERTIES_FILE = "/WEB-INF/jclouds.properties"; - - private final Properties properties; - - public PropertiesLoader(ServletContext context) { - properties = loadJcloudsProperties(context); - } - - private static Properties loadJcloudsProperties(ServletContext context) { - InputStream input = context.getResourceAsStream(PROPERTIES_FILE); - Properties props = new Properties(); - try { - props.load(input); - } catch (IOException e) { - throw new RuntimeException(e); - } finally { - Closeables.closeQuietly(input); - } - return props; - } - - @Override - public Properties get() { - return properties; - } -} diff --git a/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/controller/AddTweetsController.java b/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/controller/AddTweetsController.java deleted file mode 100644 index 5a8e6baf4b..0000000000 --- a/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/controller/AddTweetsController.java +++ /dev/null @@ -1,96 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.controller; - -import java.io.IOException; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeoutException; - -import javax.annotation.Resource; -import javax.inject.Inject; -import javax.inject.Singleton; -import javax.servlet.RequestDispatcher; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.demo.tweetstore.domain.StoredTweetStatus; -import org.jclouds.demo.tweetstore.functions.ServiceToStoredTweetStatuses; -import org.jclouds.logging.Logger; - -import com.google.common.base.Function; -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; - -/** - * Shows an example of how to use @{link BlobStoreContext} injected with Guice. - * - * @author Adrian Cole - */ -@Singleton -public class AddTweetsController extends HttpServlet implements - Function, List> { - - /** The serialVersionUID */ - private static final long serialVersionUID = 3888348023150822683L; - private final Map contexts; - private final ServiceToStoredTweetStatuses blobStoreContextToContainerResult; - - @Resource - protected Logger logger = Logger.NULL; - - @Inject - public AddTweetsController(Map contexts, - ServiceToStoredTweetStatuses blobStoreContextToContainerResult) { - this.contexts = contexts; - this.blobStoreContextToContainerResult = blobStoreContextToContainerResult; - } - - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - try { - addMyTweetsToRequest(request); - RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/tweets.jsp"); - dispatcher.forward(request, response); - } catch (Exception e) { - logger.error(e, "Error listing containers"); - throw new ServletException(e); - } - } - - void addMyTweetsToRequest(HttpServletRequest request) throws InterruptedException, - ExecutionException, TimeoutException { - request.setAttribute("tweets", apply(contexts.keySet())); - } - - public List apply(Set in) { - List statuses = Lists.newArrayList(); - for (Iterable list : Iterables.transform(in, - blobStoreContextToContainerResult)) { - Iterables.addAll(statuses, list); - } - return statuses; - } -} \ No newline at end of file diff --git a/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/controller/ClearTweetsController.java b/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/controller/ClearTweetsController.java deleted file mode 100644 index e08cfbc19e..0000000000 --- a/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/controller/ClearTweetsController.java +++ /dev/null @@ -1,96 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.controller; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Strings.nullToEmpty; - -import java.io.IOException; -import java.util.Map; - -import javax.annotation.Resource; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.core.MediaType; - -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.jclouds.logging.Logger; - -import com.google.common.annotations.VisibleForTesting; - -/** - * Grab tweets related to me and store them into blobstores - * - * @author Adrian Cole - */ -@Singleton -public class ClearTweetsController extends HttpServlet { - /** The serialVersionUID */ - private static final long serialVersionUID = 7215420527854203714L; - - private final Map contexts; - private final String container; - - @Resource - protected Logger logger = Logger.NULL; - - @Inject - @VisibleForTesting - public ClearTweetsController(Map contexts, - @Named(TweetStoreConstants.PROPERTY_TWEETSTORE_CONTAINER) String container) { - this.container = container; - this.contexts = contexts; - } - - @VisibleForTesting - public void clearContainer(String contextName) { - BlobStoreContext context = checkNotNull(contexts.get(contextName), - "no context for %s in %s", contextName, contexts.keySet()); - try { - context.getBlobStore().clearContainer(container); - } catch (Exception e) { - logger.error(e, "Error clearing tweets in %s/%s", container, context); - } - } - - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - if (nullToEmpty(request.getHeader("X-Originator")).equals("admin")) { - try { - String contextName = checkNotNull(request.getHeader("context"), "missing header context"); - logger.info("clearing tweets in %s/%s", container, contextName); - clearContainer(contextName); - logger.debug("done clearing tweets"); - response.setContentType(MediaType.TEXT_PLAIN); - response.getWriter().println("Done!"); - } catch (Exception e) { - logger.error(e, "Error clearing tweets"); - throw new ServletException(e); - } - } else { - response.sendError(401); - } - } -} \ No newline at end of file diff --git a/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/controller/EnqueueStoresController.java b/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/controller/EnqueueStoresController.java deleted file mode 100644 index 592eaaa8bd..0000000000 --- a/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/controller/EnqueueStoresController.java +++ /dev/null @@ -1,101 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.controller; - -import static com.google.common.base.Strings.nullToEmpty; -import static org.jclouds.demo.paas.RunnableHttpRequest.PLATFORM_REQUEST_ORIGINATOR_HEADER; - -import java.io.IOException; -import java.net.URI; -import java.util.Map; -import java.util.Set; - -import javax.annotation.Resource; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.core.MediaType; - -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.demo.paas.reference.PaasConstants; -import org.jclouds.demo.paas.service.taskqueue.TaskQueue; -import org.jclouds.http.HttpRequest; -import org.jclouds.logging.Logger; - -import com.google.common.annotations.VisibleForTesting; -import com.google.common.collect.ImmutableMultimap; - -/** - * Adds tasks to retrieve and store tweets in all registered contexts to an async - * task queue. - * - * @author Andrew Phillips - * @see StoreTweetsController - */ -@Singleton -public class EnqueueStoresController extends HttpServlet { - /** The serialVersionUID */ - private static final long serialVersionUID = 7215420527854203714L; - - private final Set contextNames; - private final TaskQueue taskQueue; - private final String baseUrl; - - @Resource - protected Logger logger = Logger.NULL; - - @Inject - public EnqueueStoresController(Map contexts, TaskQueue taskQueue, - @Named(PaasConstants.PROPERTY_PLATFORM_BASE_URL) String baseUrl) { - contextNames = contexts.keySet(); - this.taskQueue = taskQueue; - this.baseUrl = baseUrl; - } - - @VisibleForTesting - void enqueueStoreTweetTasks() { - for (String contextName : contextNames) { - logger.debug("enqueuing task to store tweets in blobstore '%s'", contextName); - taskQueue.add(taskQueue.getHttpRequestFactory().create(HttpRequest.builder() - .endpoint(URI.create(baseUrl + "/store/do")) - .headers(ImmutableMultimap.of("context", contextName)) - .method("GET").build())); - } - } - - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - if (!nullToEmpty(request.getHeader(PLATFORM_REQUEST_ORIGINATOR_HEADER)).equals("scheduler")) { - response.sendError(401); - } - - try { - enqueueStoreTweetTasks(); - response.setContentType(MediaType.TEXT_PLAIN); - response.getWriter().println("Done!"); - } catch (Exception e) { - logger.error(e, "Error storing tweets"); - throw new ServletException(e); - } - } -} \ No newline at end of file diff --git a/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/controller/StoreTweetsController.java b/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/controller/StoreTweetsController.java deleted file mode 100644 index 725ba128f6..0000000000 --- a/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/controller/StoreTweetsController.java +++ /dev/null @@ -1,130 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.controller; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Strings.nullToEmpty; -import static org.jclouds.demo.paas.RunnableHttpRequest.PLATFORM_REQUEST_ORIGINATOR_HEADER; - -import java.io.IOException; -import java.util.Map; - -import javax.annotation.Resource; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.core.MediaType; - -import org.jclouds.blobstore.BlobMap; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.blobstore.domain.Blob; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.jclouds.logging.Logger; -import org.jclouds.rest.AuthorizationException; - -import twitter4j.Status; -import twitter4j.Twitter; - -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Function; - -/** - * Grab tweets related to me and store them into blobstores - * - * @author Adrian Cole - */ -@Singleton -public class StoreTweetsController extends HttpServlet { - - private static final class StatusToBlob implements Function { - private final BlobMap map; - - private StatusToBlob(BlobMap map) { - this.map = map; - } - - public Blob apply(Status from) { - Blob to = map.blobBuilder().name(from.getId() + "").build(); - to.setPayload(from.getText()); - to.getPayload().getContentMetadata().setContentType(MediaType.TEXT_PLAIN); - to.getMetadata().getUserMetadata().put(TweetStoreConstants.SENDER_NAME, from.getUser().getScreenName()); - return to; - } - } - - /** The serialVersionUID */ - private static final long serialVersionUID = 7215420527854203714L; - - private final Map contexts; - private final Twitter client; - private final String container; - - @Resource - protected Logger logger = Logger.NULL; - - @Inject - @VisibleForTesting - public StoreTweetsController(Map contexts, - @Named(TweetStoreConstants.PROPERTY_TWEETSTORE_CONTAINER) String container, Twitter client) { - this.container = container; - this.contexts = contexts; - this.client = client; - } - - @VisibleForTesting - public void addMyTweets(String contextName, Iterable responseList) { - BlobStoreContext context = checkNotNull(contexts.get(contextName), "no context for " + contextName + " in " - + contexts.keySet()); - BlobMap map = context.createBlobMap(container); - for (Status status : responseList) { - Blob blob = null; - try { - blob = new StatusToBlob(map).apply(status); - map.put(status.getId() + "", blob); - } catch (AuthorizationException e) { - throw e; - } catch (Exception e) { - logger.error(e, "Error storing tweet %s (blob[%s]) on map %s/%s", status.getId(), blob, context, container); - } - } - } - - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - if (nullToEmpty(request.getHeader(PLATFORM_REQUEST_ORIGINATOR_HEADER)).equals("taskqueue-twitter")) { - try { - String contextName = checkNotNull(request.getHeader("context"), "missing header context"); - logger.info("retrieving tweets"); - addMyTweets(contextName, client.getMentions()); - logger.debug("done storing tweets"); - response.setContentType(MediaType.TEXT_PLAIN); - response.getWriter().println("Done!"); - } catch (Exception e) { - logger.error(e, "Error storing tweets"); - throw new ServletException(e); - } - } else { - response.sendError(401); - } - } -} \ No newline at end of file diff --git a/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/domain/StoredTweetStatus.java b/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/domain/StoredTweetStatus.java deleted file mode 100644 index 42ad65df01..0000000000 --- a/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/domain/StoredTweetStatus.java +++ /dev/null @@ -1,149 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.domain; - -import java.io.Serializable; - -/** - * - * @author Adrian Cole - */ -public class StoredTweetStatus implements Comparable, Serializable { - - /** The serialVersionUID */ - private static final long serialVersionUID = -3257496189689220018L; - private final String service; - private final String host; - private final String container; - private final String id; - private final String from; - private final String tweet; - private final String status; - - @Override - public String toString() { - return "StoredTweetStatus [container=" + container + ", from=" + from + ", host=" + host - + ", id=" + id + ", service=" + service + ", status=" + status + ", tweet=" + tweet - + "]"; - } - - public StoredTweetStatus(String service, String host, String container, String id, String from, - String tweet, String status) { - this.service = service; - this.host = host; - this.container = container; - this.id = id; - this.from = from; - this.tweet = tweet; - this.status = status; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((container == null) ? 0 : container.hashCode()); - result = prime * result + ((from == null) ? 0 : from.hashCode()); - result = prime * result + ((host == null) ? 0 : host.hashCode()); - result = prime * result + ((id == null) ? 0 : id.hashCode()); - result = prime * result + ((service == null) ? 0 : service.hashCode()); - result = prime * result + ((tweet == null) ? 0 : tweet.hashCode()); - return result; - } - - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - StoredTweetStatus other = (StoredTweetStatus) obj; - if (container == null) { - if (other.container != null) - return false; - } else if (!container.equals(other.container)) - return false; - if (from == null) { - if (other.from != null) - return false; - } else if (!from.equals(other.from)) - return false; - if (host == null) { - if (other.host != null) - return false; - } else if (!host.equals(other.host)) - return false; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - if (service == null) { - if (other.service != null) - return false; - } else if (!service.equals(other.service)) - return false; - if (tweet == null) { - if (other.tweet != null) - return false; - } else if (!tweet.equals(other.tweet)) - return false; - return true; - } - - - public String getService() { - return service; - } - - public String getHost() { - return host; - } - - public String getContainer() { - return container; - } - - public String getFrom() { - return from; - } - - public String getTweet() { - return tweet; - } - - public String getStatus() { - return status; - } - - public int compareTo(StoredTweetStatus o) { - if (id == null) - return -1; - return (int) ((this == o) ? 0 : id.compareTo(o.id)); - } - - - public String getId() { - return id; - } - -} diff --git a/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/functions/KeyToStoredTweetStatus.java b/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/functions/KeyToStoredTweetStatus.java deleted file mode 100644 index f831b9780f..0000000000 --- a/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/functions/KeyToStoredTweetStatus.java +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.functions; - -import javax.annotation.Resource; - -import org.jclouds.blobstore.BlobMap; -import org.jclouds.blobstore.domain.Blob; -import org.jclouds.demo.tweetstore.domain.StoredTweetStatus; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.jclouds.logging.Logger; -import org.jclouds.util.Strings2; - -import com.google.common.base.Function; - -/** - * - * @author Adrian Cole - */ -public class KeyToStoredTweetStatus implements Function { - private final String host; - private final BlobMap map; - private final String service; - private final String container; - - @Resource - protected Logger logger = Logger.NULL; - - KeyToStoredTweetStatus(BlobMap map, String service, String host, String container) { - this.host = host; - this.map = map; - this.service = service; - this.container = container; - } - - public StoredTweetStatus apply(String id) { - String status; - String from; - String tweet; - try { - long start = System.currentTimeMillis(); - Blob blob = map.get(id); - status = ((System.currentTimeMillis() - start) + "ms"); - from = blob.getMetadata().getUserMetadata().get(TweetStoreConstants.SENDER_NAME); - tweet = Strings2.toString(blob.getPayload()); - } catch (Exception e) { - logger.error(e, "Error listing container %s//%s/%s", service, container, id); - status = (e.getMessage()); - tweet = ""; - from = ""; - } - return new StoredTweetStatus(service, host, container, id, from, tweet, status); - } -} diff --git a/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/functions/ServiceToStoredTweetStatuses.java b/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/functions/ServiceToStoredTweetStatuses.java deleted file mode 100644 index b29ec14549..0000000000 --- a/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/functions/ServiceToStoredTweetStatuses.java +++ /dev/null @@ -1,73 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.functions; - -import java.net.URI; -import java.util.Collections; -import java.util.Map; -import java.util.Set; - -import javax.annotation.Resource; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - -import org.jclouds.Context; -import org.jclouds.blobstore.BlobMap; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.demo.tweetstore.domain.StoredTweetStatus; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.jclouds.logging.Logger; - -import com.google.common.base.Function; -import com.google.common.collect.Iterables; - -@Singleton -public class ServiceToStoredTweetStatuses implements Function> { - - private final Map contexts; - private final String container; - - @Inject - public ServiceToStoredTweetStatuses(Map contexts, - @Named(TweetStoreConstants.PROPERTY_TWEETSTORE_CONTAINER) String container) { - this.contexts = contexts; - this.container = container; - } - - @Resource - protected Logger logger = Logger.NULL; - - public Iterable apply(String service) { - BlobStoreContext context = contexts.get(service); - String host = URI.create(context.unwrap(Context.class).getProviderMetadata().getEndpoint()).getHost(); - try { - BlobMap blobMap = context.createBlobMap(container); - Set blobs = blobMap.keySet(); - return Iterables.transform(blobs, new KeyToStoredTweetStatus(blobMap, service, host, - container)); - } catch (Exception e) { - StoredTweetStatus result = new StoredTweetStatus(service, host, container, null, null, - null, e.getMessage()); - logger.error(e, "Error listing service %s", service); - return Collections.singletonList(result); - } - - } -} \ No newline at end of file diff --git a/demos/tweetstore/cf-tweetstore-spring/src/main/platform/.gitignore b/demos/tweetstore/cf-tweetstore-spring/src/main/platform/.gitignore deleted file mode 100644 index 843dfe79c0..0000000000 --- a/demos/tweetstore/cf-tweetstore-spring/src/main/platform/.gitignore +++ /dev/null @@ -1 +0,0 @@ -# PaaS vendor specific files go in here \ No newline at end of file diff --git a/demos/tweetstore/cf-tweetstore-spring/src/main/resources/jobs.xml b/demos/tweetstore/cf-tweetstore-spring/src/main/resources/jobs.xml deleted file mode 100644 index b740fdd52f..0000000000 --- a/demos/tweetstore/cf-tweetstore-spring/src/main/resources/jobs.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - enqueue-store-tweet-tasks - Enqueue 'store tweet' tasks for all contexts - org.jclouds.demo.paas.service.scheduler.HttpRequestJob - - - url - /stores/do - - - - - - - submit-recurring-job - enqueue-store-tweet-tasks - 10 - MINUTE - - - - \ No newline at end of file diff --git a/demos/tweetstore/cf-tweetstore-spring/src/main/resources/quartz.properties b/demos/tweetstore/cf-tweetstore-spring/src/main/resources/quartz.properties deleted file mode 100644 index 12a0fcfe91..0000000000 --- a/demos/tweetstore/cf-tweetstore-spring/src/main/resources/quartz.properties +++ /dev/null @@ -1,28 +0,0 @@ -#============================================================================ -# Configure Main Scheduler Properties -#============================================================================ - -org.quartz.scheduler.skipUpdateCheck: true - -#============================================================================ -# Configure ThreadPool -#============================================================================ - -org.quartz.threadPool.class: org.quartz.simpl.SimpleThreadPool -org.quartz.threadPool.threadCount: 1 - -#============================================================================ -# Configure JobStore -#============================================================================ - -org.quartz.jobStore.class: org.quartz.simpl.RAMJobStore - -#============================================================================ -# Configure the Job Initialization Plugin -#============================================================================ - -org.quartz.plugin.jobInitializer.class: org.jclouds.demo.paas.service.scheduler.quartz.plugins.TransactionlessXmlSchedulingDataProcessorPlugin -org.quartz.plugin.jobInitializer.fileNames: jobs.xml -org.quartz.plugin.jobInitializer.failOnFileNotFound: true -org.quartz.plugin.jobInitializer.scanInterval: 0 -#org.quartz.plugin.jobInitializer.wrapInUserTransaction: false \ No newline at end of file diff --git a/demos/tweetstore/cf-tweetstore-spring/src/main/webapp/WEB-INF/web.xml b/demos/tweetstore/cf-tweetstore-spring/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index 51dd0744e1..0000000000 --- a/demos/tweetstore/cf-tweetstore-spring/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,78 +0,0 @@ - - - - jclouds-tweetstore - - - quartz:scheduler-context-servlet-context-key - servlet-context - - - - - org.jclouds.demo.paas.config.PlatformServicesInitializer - - - - org.quartz.ee.servlet.QuartzInitializerListener - - - - - dispatcher - org.springframework.web.servlet.DispatcherServlet - - - contextClass - org.springframework.web.context.support.AnnotationConfigWebApplicationContext - - - contextConfigLocation - org.jclouds.demo.tweetstore.config.SpringServletConfig - - - - - - dispatcher - /store/* - - - dispatcher - /tweets/* - - - dispatcher - /stores/* - - - dispatcher - /clear/* - - - - index.jsp - - \ No newline at end of file diff --git a/demos/tweetstore/cf-tweetstore-spring/src/main/webapp/images/cloudfoundry-logo.png b/demos/tweetstore/cf-tweetstore-spring/src/main/webapp/images/cloudfoundry-logo.png deleted file mode 100644 index 2df231c26c..0000000000 Binary files a/demos/tweetstore/cf-tweetstore-spring/src/main/webapp/images/cloudfoundry-logo.png and /dev/null differ diff --git a/demos/tweetstore/cf-tweetstore-spring/src/main/webapp/index.jsp b/demos/tweetstore/cf-tweetstore-spring/src/main/webapp/index.jsp deleted file mode 100644 index 6365c49c09..0000000000 --- a/demos/tweetstore/cf-tweetstore-spring/src/main/webapp/index.jsp +++ /dev/null @@ -1,30 +0,0 @@ -<%-- - - Licensed to jclouds, Inc. (jclouds) under one or more - contributor license agreements. See the NOTICE file - distributed with this work for additional information - regarding copyright ownership. jclouds licenses this file - to you under the Apache License, Version 2.0 (the - "License"); you may not use this file except in compliance - with the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, - software distributed under the License is distributed on an - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - KIND, either express or implied. See the License for the - specific language governing permissions and limitations - under the License. - ---%> - - -jclouds: anyweight cloudware for java - - -

Welcome!

-

Click here to see tweets about jclouds.

-

Powered by Cloud Foundry

- - diff --git a/demos/tweetstore/cf-tweetstore-spring/src/main/webapp/tweets.jsp b/demos/tweetstore/cf-tweetstore-spring/src/main/webapp/tweets.jsp deleted file mode 100644 index b066bd9167..0000000000 --- a/demos/tweetstore/cf-tweetstore-spring/src/main/webapp/tweets.jsp +++ /dev/null @@ -1,108 +0,0 @@ -<%-- - - Licensed to jclouds, Inc. (jclouds) under one or more - contributor license agreements. See the NOTICE file - distributed with this work for additional information - regarding copyright ownership. jclouds licenses this file - to you under the Apache License, Version 2.0 (the - "License"); you may not use this file except in compliance - with the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, - software distributed under the License is distributed on an - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - KIND, either express or implied. See the License for the - specific language governing permissions and limitations - under the License. - ---%> -<%@ page buffer="20kb"%> -<%@ taglib uri="http://displaytag.sf.net" prefix="display"%> - - -jclouds: anyweight cloudware for java - - - -

Tweets in Clouds

- - - - - - - -
-
- - - - - - - - -
-
Powered by Cloud Foundry
- - diff --git a/demos/tweetstore/cf-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/config/util/CredentialsCollectorTest.java b/demos/tweetstore/cf-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/config/util/CredentialsCollectorTest.java deleted file mode 100644 index 031bb199fc..0000000000 --- a/demos/tweetstore/cf-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/config/util/CredentialsCollectorTest.java +++ /dev/null @@ -1,82 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.config.util; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; - -import java.util.Map; -import java.util.Properties; - -import org.jclouds.demo.tweetstore.config.util.CredentialsCollector; -import org.jclouds.demo.tweetstore.config.util.CredentialsCollector.Credential; -import org.testng.annotations.Test; - -import com.google.common.collect.ImmutableMap; - -/** - * Tests behavior of {@code CredentialsCollector} - * - * @author Andrew Phillips - */ -@Test(groups = "unit") -public class CredentialsCollectorTest { - private CredentialsCollector collector = new CredentialsCollector(); - - public void testEmptyProperties() { - assertTrue(collector.apply(new Properties()).isEmpty(), - "Expected returned map to be empty"); - } - - public void testNoCredentials() { - Properties properties = propertiesOf(ImmutableMap.of("not-an-identity", - "v1", "not-a-credential", "v2")); - assertTrue(collector.apply(properties).isEmpty(), - "Expected returned map to be empty"); - } - - private static Properties propertiesOf(Map entries) { - Properties properties = new Properties(); - properties.putAll(entries); - return properties; - } - - public void testNonMatchingCredentials() { - Properties properties = propertiesOf(ImmutableMap.of("non_matching.identity", "v1", - "non_matching.credential", "v2")); - assertTrue(collector.apply(properties).isEmpty(), - "Expected returned map to be empty"); - } - - public void testIncompleteCredentials() { - Properties properties = propertiesOf(ImmutableMap.of("acme.identity", "v1", - "acme-2.credential", "v2")); - assertTrue(collector.apply(properties).isEmpty(), - "Expected returned map to be empty"); - } - - public void testCredentials() { - Properties properties = propertiesOf(ImmutableMap.of("acme.identity", "v1", - "acme.credential", "v2", "acme-2.identity", "v3", - "acme-2.credential", "v4")); - assertEquals(collector.apply(properties), - ImmutableMap.of("acme", new Credential("v1", "v2"), - "acme-2", new Credential("v3", "v4"))); - } -} \ No newline at end of file diff --git a/demos/tweetstore/cf-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/controller/AddTweetsControllerTest.java b/demos/tweetstore/cf-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/controller/AddTweetsControllerTest.java deleted file mode 100644 index 1c93403650..0000000000 --- a/demos/tweetstore/cf-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/controller/AddTweetsControllerTest.java +++ /dev/null @@ -1,78 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.controller; - -import static org.testng.Assert.assertEquals; - -import java.io.IOException; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ExecutionException; - -import org.jclouds.ContextBuilder; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.blobstore.TransientApiMetadata; -import org.jclouds.blobstore.domain.Blob; -import org.jclouds.demo.tweetstore.domain.StoredTweetStatus; -import org.jclouds.demo.tweetstore.functions.ServiceToStoredTweetStatuses; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.testng.annotations.Test; -import org.testng.collections.Maps; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableSet; - -/** - * Tests behavior of {@code AddTweetsController} - * - * @author Adrian Cole - */ -@Test(groups = "unit") -public class AddTweetsControllerTest { - - Map createServices(String container) throws InterruptedException, - ExecutionException { - Map services = Maps.newHashMap(); - TransientApiMetadata transientApiMetadata = TransientApiMetadata.builder().build(); - for (String name : new String[] { "1", "2" }) { - BlobStoreContext context = ContextBuilder.newBuilder(transientApiMetadata).build(BlobStoreContext.class); - context.getAsyncBlobStore().createContainerInLocation(null, container).get(); - Blob blob = context.getAsyncBlobStore().blobBuilder("1").build(); - blob.getMetadata().getUserMetadata().put(TweetStoreConstants.SENDER_NAME, "frank"); - blob.setPayload("I love beans!"); - context.getAsyncBlobStore().putBlob(container, blob).get(); - services.put(name, context); - } - return services; - } - - public void testStoreTweets() throws IOException, InterruptedException, ExecutionException { - String container = "container"; - Map contexts = createServices(container); - - ServiceToStoredTweetStatuses function = new ServiceToStoredTweetStatuses(contexts, container); - AddTweetsController controller = new AddTweetsController(contexts, function); - List list = controller.apply(ImmutableSet.of("1", "2")); - assertEquals(list.size(), 2); - assertEquals(list, ImmutableList.of(new StoredTweetStatus("1", "localhost", container, "1", - "frank", "I love beans!", null), new StoredTweetStatus("2", "localhost", container, - "1", "frank", "I love beans!", null))); - - } -} diff --git a/demos/tweetstore/cf-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/controller/ClearTweetsControllerTest.java b/demos/tweetstore/cf-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/controller/ClearTweetsControllerTest.java deleted file mode 100644 index 81f0b9f3c7..0000000000 --- a/demos/tweetstore/cf-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/controller/ClearTweetsControllerTest.java +++ /dev/null @@ -1,72 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.controller; - -import static org.testng.Assert.assertEquals; - -import java.io.IOException; -import java.util.Map; -import java.util.concurrent.ExecutionException; - -import org.jclouds.ContextBuilder; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.blobstore.TransientApiMetadata; -import org.jclouds.blobstore.domain.Blob; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.testng.annotations.Test; - -import com.google.common.collect.ImmutableMap; - -/** - * Tests behavior of {@code AddTweetsController} - * - * @author Adrian Cole - */ -@Test(groups = "unit") -public class ClearTweetsControllerTest { - - Map createBlobStores(String container) throws InterruptedException, ExecutionException { - TransientApiMetadata transientApiMetadata = TransientApiMetadata.builder().build(); - Map contexts = ImmutableMap.of( - "test1", ContextBuilder.newBuilder(transientApiMetadata).build(BlobStoreContext.class), - "test2", ContextBuilder.newBuilder(transientApiMetadata).build(BlobStoreContext.class)); - for (BlobStoreContext blobstore : contexts.values()) { - blobstore.getBlobStore().createContainerInLocation(null, container); - Blob blob = blobstore.getAsyncBlobStore().blobBuilder("1").build(); - blob.getMetadata().getUserMetadata().put(TweetStoreConstants.SENDER_NAME, "frank"); - blob.setPayload("I love beans!"); - blobstore.getBlobStore().putBlob(container, blob); - } - return contexts; - } - - public void testClearTweets() throws IOException, InterruptedException, ExecutionException { - String container = ClearTweetsControllerTest.class.getName() + "#container"; - Map contexts = createBlobStores(container); - - ClearTweetsController controller = new ClearTweetsController(contexts, - container); - controller.clearContainer("test1"); - controller.clearContainer("test2"); - - for (BlobStoreContext context : contexts.values()) { - assertEquals(context.getBlobStore().countBlobs(container), 0, context.toString()); - } - } -} diff --git a/demos/tweetstore/cf-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/controller/EnqueueStoresControllerTest.java b/demos/tweetstore/cf-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/controller/EnqueueStoresControllerTest.java deleted file mode 100644 index 3c5e5b1d80..0000000000 --- a/demos/tweetstore/cf-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/controller/EnqueueStoresControllerTest.java +++ /dev/null @@ -1,85 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.controller; - -import static org.easymock.EasyMock.*; - -import java.net.URI; -import java.util.Map; - -import org.jclouds.ContextBuilder; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.blobstore.TransientApiMetadata; -import org.jclouds.demo.paas.RunnableHttpRequest; -import org.jclouds.demo.paas.RunnableHttpRequest.Factory; -import org.jclouds.demo.paas.service.taskqueue.TaskQueue; -import org.jclouds.http.HttpRequest; -import org.testng.annotations.Test; - -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableMultimap; - -/** - * Tests behavior of {@code EnqueueStoresController} - * - * @author Andrew Phillips - */ -@Test(groups = "unit") -public class EnqueueStoresControllerTest { - - Map createBlobStores() { - TransientApiMetadata transientApiMetadata = TransientApiMetadata.builder().build(); - Map contexts = ImmutableMap.of( - "test1", ContextBuilder.newBuilder(transientApiMetadata).build(BlobStoreContext.class), - "test2", ContextBuilder.newBuilder(transientApiMetadata).build(BlobStoreContext.class)); - return contexts; - } - - public void testEnqueueStores() { - Map stores = createBlobStores(); - TaskQueue taskQueue = createMock(TaskQueue.class); - Factory httpRequestFactory = createMock(Factory.class); - EnqueueStoresController function = new EnqueueStoresController(stores, - taskQueue, "http://localhost:8080"); - - expect(taskQueue.getHttpRequestFactory()).andStubReturn(httpRequestFactory); - - HttpRequest storeInTest1Request = HttpRequest.builder().endpoint( - URI.create("http://localhost:8080/store/do")) - .headers(ImmutableMultimap.of("context", "test1")).method("GET").build(); - RunnableHttpRequest storeInTest1Task = null; - expect(httpRequestFactory.create(eq(storeInTest1Request))).andReturn(storeInTest1Task); - - HttpRequest storeInTest2Request = HttpRequest.builder().endpoint( - URI.create("http://localhost:8080/store/do")) - .headers(ImmutableMultimap.of("context", "test2")).method("GET").build(); - RunnableHttpRequest storeInTest2Task = null; - expect(httpRequestFactory.create(eq(storeInTest2Request))).andReturn(storeInTest2Task); - - taskQueue.add(storeInTest1Task); - expectLastCall(); - taskQueue.add(storeInTest2Task); - expectLastCall(); - replay(httpRequestFactory, taskQueue); - - function.enqueueStoreTweetTasks(); - - verify(taskQueue); - } -} \ No newline at end of file diff --git a/demos/tweetstore/cf-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/controller/StoreTweetsControllerTest.java b/demos/tweetstore/cf-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/controller/StoreTweetsControllerTest.java deleted file mode 100644 index 53eb8a9302..0000000000 --- a/demos/tweetstore/cf-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/controller/StoreTweetsControllerTest.java +++ /dev/null @@ -1,120 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.controller; - -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.verify; -import static org.testng.Assert.assertEquals; - -import java.io.IOException; -import java.util.Map; -import java.util.Map.Entry; -import java.util.concurrent.ExecutionException; - -import org.jclouds.ContextBuilder; -import org.jclouds.blobstore.BlobMap; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.blobstore.TransientApiMetadata; -import org.jclouds.blobstore.domain.Blob; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.jclouds.util.Strings2; -import org.testng.annotations.Test; - -import twitter4j.Status; -import twitter4j.Twitter; -import twitter4j.User; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; - -/** - * Tests behavior of {@code StoreTweetsController} - * - * @author Adrian Cole - */ -@Test(groups = "unit") -public class StoreTweetsControllerTest { - - Twitter createTwitter() { - return createMock(Twitter.class); - } - - Map createBlobStores() throws InterruptedException, ExecutionException { - TransientApiMetadata transientApiMetadata = TransientApiMetadata.builder().build(); - Map contexts = ImmutableMap.of( - "test1", ContextBuilder.newBuilder(transientApiMetadata).build(BlobStoreContext.class), - "test2", ContextBuilder.newBuilder(transientApiMetadata).build(BlobStoreContext.class)); - for (BlobStoreContext blobstore : contexts.values()) { - blobstore.getAsyncBlobStore().createContainerInLocation(null, "favo").get(); - } - return contexts; - } - - public void testStoreTweets() throws IOException, InterruptedException, ExecutionException { - Map stores = createBlobStores(); - StoreTweetsController function = new StoreTweetsController(stores, "favo", createTwitter()); - - User frank = createMock(User.class); - expect(frank.getScreenName()).andReturn("frank").atLeastOnce(); - - Status frankStatus = createMock(Status.class); - expect(frankStatus.getId()).andReturn(1l).atLeastOnce(); - expect(frankStatus.getUser()).andReturn(frank).atLeastOnce(); - expect(frankStatus.getText()).andReturn("I love beans!").atLeastOnce(); - - User jimmy = createMock(User.class); - expect(jimmy.getScreenName()).andReturn("jimmy").atLeastOnce(); - - Status jimmyStatus = createMock(Status.class); - expect(jimmyStatus.getId()).andReturn(2l).atLeastOnce(); - expect(jimmyStatus.getUser()).andReturn(jimmy).atLeastOnce(); - expect(jimmyStatus.getText()).andReturn("cloud is king").atLeastOnce(); - - replay(frank); - replay(frankStatus); - replay(jimmy); - replay(jimmyStatus); - - function.addMyTweets("test1", ImmutableList.of(frankStatus, jimmyStatus)); - function.addMyTweets("test2", ImmutableList.of(frankStatus, jimmyStatus)); - - verify(frank); - verify(frankStatus); - verify(jimmy); - verify(jimmyStatus); - - for (Entry entry : stores.entrySet()) { - BlobMap map = entry.getValue().createBlobMap("favo"); - Blob frankBlob = map.get("1"); - assertEquals(frankBlob.getMetadata().getName(), "1"); - assertEquals(frankBlob.getMetadata().getUserMetadata().get(TweetStoreConstants.SENDER_NAME), "frank"); - assertEquals(frankBlob.getMetadata().getContentMetadata().getContentType(), "text/plain"); - assertEquals(Strings2.toString(frankBlob.getPayload()), "I love beans!"); - - Blob jimmyBlob = map.get("2"); - assertEquals(jimmyBlob.getMetadata().getName(), "2"); - assertEquals(jimmyBlob.getMetadata().getUserMetadata().get(TweetStoreConstants.SENDER_NAME), "jimmy"); - assertEquals(jimmyBlob.getMetadata().getContentMetadata().getContentType(), "text/plain"); - assertEquals(Strings2.toString(jimmyBlob.getPayload()), "cloud is king"); - } - - } -} diff --git a/demos/tweetstore/cf-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/functions/KeyToStoredTweetStatusTest.java b/demos/tweetstore/cf-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/functions/KeyToStoredTweetStatusTest.java deleted file mode 100644 index af74b423d5..0000000000 --- a/demos/tweetstore/cf-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/functions/KeyToStoredTweetStatusTest.java +++ /dev/null @@ -1,69 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.functions; - -import static org.testng.Assert.assertEquals; - -import java.io.IOException; -import java.util.concurrent.ExecutionException; - -import org.jclouds.ContextBuilder; -import org.jclouds.blobstore.BlobMap; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.blobstore.TransientApiMetadata; -import org.jclouds.blobstore.domain.Blob; -import org.jclouds.demo.tweetstore.domain.StoredTweetStatus; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.testng.annotations.Test; - -/** - * Tests behavior of {@code KeyToStoredTweetStatus} - * - * @author Adrian Cole - */ -@Test(groups = "unit") -public class KeyToStoredTweetStatusTest { - - BlobMap createMap() throws InterruptedException, ExecutionException { - BlobStoreContext context = - ContextBuilder.newBuilder(TransientApiMetadata.builder().build()).build(BlobStoreContext.class); - context.getBlobStore().createContainerInLocation(null, "test1"); - return context.createBlobMap("test1"); - } - - public void testStoreTweets() throws IOException, InterruptedException, ExecutionException { - BlobMap map = createMap(); - Blob blob = map.blobBuilder().name("1").build(); - blob.getMetadata().getUserMetadata().put(TweetStoreConstants.SENDER_NAME, "frank"); - blob.setPayload("I love beans!"); - map.put("1", blob); - String host = "localhost"; - String service = "stub"; - String container = "tweetstore"; - - KeyToStoredTweetStatus function = new KeyToStoredTweetStatus(map, service, host, container); - StoredTweetStatus result = function.apply("1"); - - StoredTweetStatus expected = new StoredTweetStatus(service, host, container, "1", "frank", - "I love beans!", null); - - assertEquals(result, expected); - - } -} diff --git a/demos/tweetstore/cf-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/functions/ServiceToStoredTweetStatusesTest.java b/demos/tweetstore/cf-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/functions/ServiceToStoredTweetStatusesTest.java deleted file mode 100644 index 5fec52711e..0000000000 --- a/demos/tweetstore/cf-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/functions/ServiceToStoredTweetStatusesTest.java +++ /dev/null @@ -1,75 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.functions; - -import static org.testng.Assert.assertEquals; - -import java.io.IOException; -import java.util.Map; -import java.util.concurrent.ExecutionException; - -import org.jclouds.ContextBuilder; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.blobstore.TransientApiMetadata; -import org.jclouds.blobstore.domain.Blob; -import org.jclouds.demo.tweetstore.domain.StoredTweetStatus; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.testng.annotations.Test; -import org.testng.collections.Maps; - -import com.google.common.collect.Iterables; - -/** - * Tests behavior of {@code ServiceToStoredTweetStatuses} - * - * @author Adrian Cole - */ -@Test(groups = "unit") -public class ServiceToStoredTweetStatusesTest { - - Map createServices(String container) throws InterruptedException, - ExecutionException { - Map services = Maps.newHashMap(); - TransientApiMetadata transientApiMetadata = TransientApiMetadata.builder().build(); - for (String name : new String[] { "1", "2" }) { - BlobStoreContext context = ContextBuilder.newBuilder(transientApiMetadata).build(BlobStoreContext.class); - context.getAsyncBlobStore().createContainerInLocation(null, container).get(); - Blob blob = context.getAsyncBlobStore().blobBuilder("1").build(); - blob.getMetadata().getUserMetadata().put(TweetStoreConstants.SENDER_NAME, "frank"); - blob.setPayload("I love beans!"); - context.getAsyncBlobStore().putBlob(container, blob).get(); - services.put(name, context); - } - return services; - } - - public void testStoreTweets() throws IOException, InterruptedException, ExecutionException { - String container = "container"; - Map contexts = createServices(container); - - ServiceToStoredTweetStatuses function = new ServiceToStoredTweetStatuses(contexts, container); - - assertEquals(Iterables.getLast(function.apply("1")), new StoredTweetStatus("1", "localhost", - container, "1", "frank", "I love beans!", null)); - - assertEquals(Iterables.getLast(function.apply("2")), new StoredTweetStatus("2", "localhost", - container, "1", "frank", "I love beans!", null)); - - } -} diff --git a/demos/tweetstore/cf-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/integration/CloudFoundryServer.java b/demos/tweetstore/cf-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/integration/CloudFoundryServer.java deleted file mode 100644 index 6ecebbdfab..0000000000 --- a/demos/tweetstore/cf-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/integration/CloudFoundryServer.java +++ /dev/null @@ -1,106 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.integration; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkState; -import static com.google.common.io.Closeables.closeQuietly; -import static java.lang.String.format; -import static org.jclouds.demo.tweetstore.integration.util.Zips.zipDir; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Properties; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; - -import org.cloudfoundry.client.lib.CloudApplication.AppState; -import org.cloudfoundry.client.lib.CloudFoundryClient; - -/** - * Basic "server facade" functionality to deploy a WAR to Cloud Foundry. - * - * @author Andrew Phillips - */ -public class CloudFoundryServer { - private static final String CLOUD_FOUNDRY_APPLICATION_URL_SUFFIX = ".cloudfoundry.com"; - - protected CloudFoundryClient client; - protected String appName; - - public void writePropertiesAndStartServer(final String address, final String warfile, - String target, String username, String password, Properties props) throws IOException, InterruptedException, ExecutionException { - String propsfile = String.format("%1$s/WEB-INF/jclouds.properties", warfile); - System.err.println("file: " + propsfile); - storeProperties(propsfile, props); - assert new File(propsfile).exists(); - - client = new CloudFoundryClient(username, password, target); - client.login(); - appName = getAppName(address); - deploy(warfile); - client.logout(); - TimeUnit.SECONDS.sleep(10); - } - - private void deploy(String explodedWar) throws IOException { - File war = zipDir(explodedWar, format("%s-cloudfoundry.war", explodedWar)); - client.uploadApplication(appName, war); - - // adapted from https://github.com/cloudfoundry/vcap-java-client/blob/master/cloudfoundry-maven-plugin/src/main/java/org/cloudfoundry/maven/Update.java - AppState appState = client.getApplication(appName).getState(); - switch (appState) { - case STOPPED: - client.startApplication(appName); - break; - case STARTED: - client.restartApplication(appName); - break; - default: - throw new IllegalStateException(format("Unexpected application state '%s'", appState)); - } - } - - private static void storeProperties(String filename, Properties props) - throws IOException { - FileOutputStream targetFile = new FileOutputStream(filename); - try { - props.store(targetFile, "test"); - } finally { - closeQuietly(targetFile); - } - } - - private static String getAppName(String applicationUrl) { - checkArgument(applicationUrl.endsWith(CLOUD_FOUNDRY_APPLICATION_URL_SUFFIX), - "Application URL '%s' does not end in '%s'", applicationUrl, - CLOUD_FOUNDRY_APPLICATION_URL_SUFFIX); - - return applicationUrl.substring(0, - applicationUrl.length() - CLOUD_FOUNDRY_APPLICATION_URL_SUFFIX.length()); - } - - public void stop() throws Exception { - checkState(client != null, "'stop' called before 'writePropertiesAndStartServer'"); - client.login(); - client.stopApplication(appName); - client.logout(); - } -} \ No newline at end of file diff --git a/demos/tweetstore/cf-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/integration/TweetStoreLiveTest.java b/demos/tweetstore/cf-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/integration/TweetStoreLiveTest.java deleted file mode 100644 index 3723d5f250..0000000000 --- a/demos/tweetstore/cf-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/integration/TweetStoreLiveTest.java +++ /dev/null @@ -1,234 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.integration; - -import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.demo.tweetstore.reference.TweetStoreConstants.PROPERTY_TWEETSTORE_BLOBSTORES; -import static org.jclouds.demo.tweetstore.reference.TweetStoreConstants.PROPERTY_TWEETSTORE_CONTAINER; -import static org.jclouds.demo.tweetstore.reference.TwitterConstants.PROPERTY_TWITTER_ACCESSTOKEN; -import static org.jclouds.demo.tweetstore.reference.TwitterConstants.PROPERTY_TWITTER_ACCESSTOKEN_SECRET; -import static org.jclouds.demo.tweetstore.reference.TwitterConstants.PROPERTY_TWITTER_CONSUMER_KEY; -import static org.jclouds.demo.tweetstore.reference.TwitterConstants.PROPERTY_TWITTER_CONSUMER_SECRET; - -import java.io.IOException; -import java.io.InputStream; -import java.net.HttpURLConnection; -import java.net.URL; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Properties; -import java.util.Set; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeoutException; - -import org.jclouds.Context; -import org.jclouds.ContextBuilder; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.demo.tweetstore.config.SpringServletConfig; -import org.jclouds.demo.tweetstore.controller.StoreTweetsController; -import org.jclouds.logging.log4j.config.Log4JLoggingModule; -import org.jclouds.util.Strings2; -import org.testng.annotations.AfterTest; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.Parameters; -import org.testng.annotations.Test; - -import twitter4j.ResponseList; -import twitter4j.Status; -import twitter4j.Twitter; -import twitter4j.TwitterException; -import twitter4j.TwitterFactory; -import twitter4j.conf.Configuration; -import twitter4j.conf.ConfigurationBuilder; - -import com.google.common.base.Joiner; -import com.google.common.base.Splitter; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Maps; -import com.google.inject.Module; - -/** - * Starts up the Google App Engine for Java Development environment and deploys an application which - * tests accesses twitter and blobstores. - * - * @author Adrian Cole - */ -@Test(groups = "live", singleThreaded = true) -public class TweetStoreLiveTest { - - CloudFoundryServer server; - private URL url; - private Map contexts; - private String container; - - private static final Iterable blobstores = - Splitter.on(',').split(System.getProperty(PROPERTY_TWEETSTORE_BLOBSTORES, - "cloudfiles-us,aws-s3,azureblob")); - private static final Properties props = new Properties(); - - @BeforeTest - void clearAndCreateContainers() throws InterruptedException, ExecutionException, TimeoutException, IOException, - TwitterException { - container = getRequiredSystemProperty(PROPERTY_TWEETSTORE_CONTAINER); - - props.setProperty(PROPERTY_TWEETSTORE_CONTAINER, container); - props.setProperty(SpringServletConfig.PROPERTY_BLOBSTORE_CONTEXTS, Joiner.on(',').join(blobstores)); - - // put all identity/credential pairs into the client - addCredentialsForBlobStores(props); - - // example of an ad-hoc client configuration - addConfigurationForTwitter(props); - - // for testing, capture logs. - final Set wiring = ImmutableSet. of(new Log4JLoggingModule()); - this.contexts = Maps.newConcurrentMap(); - - for (String provider : blobstores) { - contexts.put(provider, ContextBuilder.newBuilder(provider).modules(wiring) - .overrides(props).build(BlobStoreContext.class)); - } - - Configuration conf = new ConfigurationBuilder() - .setOAuthConsumerKey(props.getProperty(PROPERTY_TWITTER_CONSUMER_KEY)) - .setOAuthConsumerSecret(props.getProperty(PROPERTY_TWITTER_CONSUMER_SECRET)) - .setOAuthAccessToken(props.getProperty(PROPERTY_TWITTER_ACCESSTOKEN)) - .setOAuthAccessTokenSecret(props.getProperty(PROPERTY_TWITTER_ACCESSTOKEN_SECRET)) - .build(); - Twitter client = new TwitterFactory(conf).getInstance(); - StoreTweetsController controller = new StoreTweetsController(contexts, container, client); - - ResponseList statuses = client.getMentions(); - - boolean deleted = false; - for (BlobStoreContext context : contexts.values()) { - if (context.getBlobStore().containerExists(container)) { - System.err.printf("deleting container %s at %s%n", container, - context.unwrap(Context.class).getProviderMetadata().getEndpoint()); - context.getBlobStore().deleteContainer(container); - deleted = true; - } - } - if (deleted) { - System.err.println("sleeping 60 seconds to allow containers to clear"); - Thread.sleep(60000); - } - for (BlobStoreContext context : contexts.values()) { - System.err.printf("creating container %s at %s%n", container, - context.unwrap(Context.class).getProviderMetadata().getEndpoint()); - context.getBlobStore().createContainerInLocation(null, container); - } - if (deleted) { - System.err.println("sleeping 5 seconds to allow containers to create"); - Thread.sleep(5000); - } - - for (Entry entry : contexts.entrySet()) { - System.err.printf("filling container %s at %s%n", container, entry.getKey()); - controller.addMyTweets(entry.getKey(), statuses); - } - } - - private static String getRequiredSystemProperty(String key) { - return checkNotNull(System.getProperty(key), key); - } - - private void addConfigurationForTwitter(Properties props) { - props.setProperty(PROPERTY_TWITTER_CONSUMER_KEY, - getRequiredSystemProperty("test." + PROPERTY_TWITTER_CONSUMER_KEY)); - props.setProperty(PROPERTY_TWITTER_CONSUMER_SECRET, - getRequiredSystemProperty("test." + PROPERTY_TWITTER_CONSUMER_SECRET)); - props.setProperty(PROPERTY_TWITTER_ACCESSTOKEN, - getRequiredSystemProperty("test." + PROPERTY_TWITTER_ACCESSTOKEN)); - props.setProperty(PROPERTY_TWITTER_ACCESSTOKEN_SECRET, - getRequiredSystemProperty("test." + PROPERTY_TWITTER_ACCESSTOKEN_SECRET)); - } - - private void addCredentialsForBlobStores(Properties props) { - for (String provider : blobstores) { - props.setProperty(provider + ".identity", - getRequiredSystemProperty("test." + provider + ".identity")); - props.setProperty(provider + ".credential", - getRequiredSystemProperty("test." + provider + ".credential")); - } - } - - @BeforeTest - @Parameters({ "warfile", "cloudfoundry.address", "cloudfoundry.port", "cloudfoundry.target", "cloudfoundry.username", "cloudfoundry.password" }) - public void startDevAppServer(final String warfile, final String address, final String port, - String target, String username, String password) throws Exception { - url = new URL(String.format("http://%s:%s", address, port)); - server = new CloudFoundryServer(); - server.writePropertiesAndStartServer(address, warfile, target, username, password, props); - } - - @Test - public void shouldPass() throws InterruptedException, IOException { - InputStream i = url.openStream(); - String string = Strings2.toStringAndClose(i); - assert string.indexOf("Welcome") >= 0 : string; - } - - @Test(dependsOnMethods = "shouldPass", expectedExceptions = IOException.class) - public void shouldFail() throws InterruptedException, IOException { - new URL(url, "/store/do").openStream(); - } - - @Test(dependsOnMethods = "shouldFail") - public void testPrimeContainers() throws IOException, InterruptedException { - URL gurl = new URL(url, "/store/do"); - for (String context : blobstores) { - System.out.println("storing at context: " + context); - HttpURLConnection connection = (HttpURLConnection) gurl.openConnection(); - connection.addRequestProperty("X-Platform-Originator", "taskqueue-twitter"); - connection.addRequestProperty("context", context); - InputStream i = connection.getInputStream(); - String string = Strings2.toStringAndClose(i); - assert string.indexOf("Done!") >= 0 : string; - connection.disconnect(); - } - - System.err.println("sleeping 20 seconds to allow for eventual consistency delay"); - Thread.sleep(20000); - for (BlobStoreContext context : contexts.values()) { - assert context.createInputStreamMap(container).size() > 0 : context.unwrap(Context.class).getProviderMetadata().getEndpoint(); - } - } - - @Test(invocationCount = 5, dependsOnMethods = "testPrimeContainers") - public void testSerial() throws InterruptedException, IOException { - URL gurl = new URL(url, "/tweets/get"); - InputStream i = gurl.openStream(); - String string = Strings2.toStringAndClose(i); - assert string.indexOf("Tweets in Clouds") >= 0 : string; - } - - @Test(invocationCount = 10, dependsOnMethods = "testPrimeContainers", threadPoolSize = 3) - public void testParallel() throws InterruptedException, IOException { - URL gurl = new URL(url, "/tweets/get"); - InputStream i = gurl.openStream(); - String string = Strings2.toStringAndClose(i); - assert string.indexOf("Tweets in Clouds") >= 0 : string; - } - - @AfterTest - public void stopDevAppServer() throws Exception { - server.stop(); - } -} diff --git a/demos/tweetstore/cf-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/integration/util/Zips.java b/demos/tweetstore/cf-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/integration/util/Zips.java deleted file mode 100644 index 571c9083a3..0000000000 --- a/demos/tweetstore/cf-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/integration/util/Zips.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.integration.util; - -import java.io.File; -import java.io.IOException; - -import org.codehaus.plexus.archiver.zip.ZipArchiver; - -public class Zips { - - public static File zipDir(String dirToZip, String zipFile) throws IOException { - ZipArchiver archiver = new ZipArchiver(); - archiver.addDirectory(new File(dirToZip)); - File zip = new File(zipFile); - archiver.setDestFile(zip); - archiver.createArchive(); - return zip; - } -} \ No newline at end of file diff --git a/demos/tweetstore/cf-tweetstore-spring/src/test/resources/log4j.xml b/demos/tweetstore/cf-tweetstore-spring/src/test/resources/log4j.xml deleted file mode 100644 index 2e5d01fb9e..0000000000 --- a/demos/tweetstore/cf-tweetstore-spring/src/test/resources/log4j.xml +++ /dev/null @@ -1,95 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/demos/tweetstore/gae-tweetstore-spring/README.txt b/demos/tweetstore/gae-tweetstore-spring/README.txt deleted file mode 100644 index 0acc6d2ed5..0000000000 --- a/demos/tweetstore/gae-tweetstore-spring/README.txt +++ /dev/null @@ -1,64 +0,0 @@ -==== - Licensed to jclouds, Inc. (jclouds) under one or more - contributor license agreements. See the NOTICE file - distributed with this work for additional information - regarding copyright ownership. jclouds licenses this file - to you under the Apache License, Version 2.0 (the - "License"); you may not use this file except in compliance - with the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, - software distributed under the License is distributed on an - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - KIND, either express or implied. See the License for the - specific language governing permissions and limitations - under the License. -==== - -This sample is a "port" of jclouds-demo-gae-tweetstore with the initial context setup -and wiring carried out with Spring. It is intended to demonstrate how to integrate -jclouds into your Spring application. - -It should not be regarded as a sample of how to write a web application using Spring, -however! The original jclouds-demo-gae-tweetstore has been modified in as few places as -possible; it has not been rewritten in the style of a Spring MVC application. - -A guide to generating Twitter consumer keys and access tokens is at http://tinyurl.com/2fhebgb - -This sample uses the Google App Engine for Java SDK located at -http://code.google.com/p/googleappengine/downloads/list - -Please unzip the above file and modify your maven settings.xml like below before -attempting to run 'mvn -Plive install' - - - appengine - - true - - - /path/to/appengine-java-sdk-1.4.2 - yourappid - - - - - keys - - true - - - YOUR_ACCESS_KEY_ID - YOUR_SECRET_KEY - YOUR_USER - YOUR_HEX_KEY - YOUR_ACCOUNT - YOUR_BASE64_ENCODED_KEY - YOUR_TWITTER_CONSUMER_KEY - YOUR_TWITTER_CONSUMER_SECRET - YOUR_TWITTER_ACCESSTOKEN - YOUR_TWITTER_ACCESSTOKEN_SECRET - - \ No newline at end of file diff --git a/demos/tweetstore/gae-tweetstore-spring/pom.xml b/demos/tweetstore/gae-tweetstore-spring/pom.xml deleted file mode 100644 index 71d682a544..0000000000 --- a/demos/tweetstore/gae-tweetstore-spring/pom.xml +++ /dev/null @@ -1,156 +0,0 @@ - - - - 4.0.0 - - org.jclouds - jclouds-demos-tweetstore-project - 1.5.0-SNAPSHOT - - jclouds-demo-gae-tweetstore-spring - war - jclouds TweetStore for Google App Engine (Spring) - JClouds TweetStore for Google App Engine using Spring for Dependency Injection - - - - jclouds-tweetstore-spring - 1.6.1 - localhost - 8088 - jclouds-gae-tweetstore-spring - - - - - org.jclouds.driver - jclouds-gae - ${project.version} - - - org.springframework - spring-context - 3.0.5.RELEASE - - - - commons-logging - commons-logging - - - - - org.springframework - spring-webmvc - 3.0.5.RELEASE - - - cglib - cglib-nodep - 2.2 - runtime - - - - - com.google.appengine - appengine-api-1.0-sdk - ${appengine.sdk.version} - - - com.google.appengine - appengine-tools-sdk - ${appengine.sdk.version} - test - - - - - - live - - - - maven-surefire-plugin - - - integration - integration-test - - test - - - - ${test.twitter.gae-tweetstore-spring.consumer.identity} - ${test.twitter.gae-tweetstore-spring.consumer.credential} - ${test.twitter.gae-tweetstore-spring.access.identity} - ${test.twitter.gae-tweetstore-spring.access.credential} - ${test.azureblob.identity} - ${test.azureblob.credential} - ${test.cloudfiles-us.identity} - ${test.cloudfiles-us.credential} - ${test.aws-s3.identity} - ${test.aws-s3.credential} - ${test.cloudonestorage.identity} - ${test.cloudonestorage.credential} - ${test.ninefold-storage.identity} - ${test.ninefold-storage.credential} - ${appengine.sdk.root} - ${devappserver.address} - ${devappserver.port} - ${jclouds.tweetstore.blobstores} - test.${jclouds.tweetstore.container} - ${project.build.directory}/${project.artifactId} - - - - - - - - - - - deploy - - - gae-tweetstore-spring - - - - - net.kindleit - maven-gae-plugin - 0.9.2 - - google-appengine - ${appengine.sdk.root} - - - - - - - diff --git a/demos/tweetstore/gae-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/config/SpringServletConfig.java b/demos/tweetstore/gae-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/config/SpringServletConfig.java deleted file mode 100644 index 9bfba4a8cd..0000000000 --- a/demos/tweetstore/gae-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/config/SpringServletConfig.java +++ /dev/null @@ -1,241 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.config; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Preconditions.checkState; -import static com.google.common.base.Predicates.in; -import static com.google.common.collect.ImmutableSet.copyOf; -import static com.google.common.collect.Sets.filter; -import static org.jclouds.demo.tweetstore.reference.TweetStoreConstants.PROPERTY_TWEETSTORE_BLOBSTORES; -import static org.jclouds.demo.tweetstore.reference.TweetStoreConstants.PROPERTY_TWEETSTORE_CONTAINER; -import static org.jclouds.demo.tweetstore.reference.TwitterConstants.PROPERTY_TWITTER_ACCESSTOKEN; -import static org.jclouds.demo.tweetstore.reference.TwitterConstants.PROPERTY_TWITTER_ACCESSTOKEN_SECRET; -import static org.jclouds.demo.tweetstore.reference.TwitterConstants.PROPERTY_TWITTER_CONSUMER_KEY; -import static org.jclouds.demo.tweetstore.reference.TwitterConstants.PROPERTY_TWITTER_CONSUMER_SECRET; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Map; -import java.util.Properties; -import java.util.Set; - -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; -import javax.servlet.Servlet; -import javax.servlet.ServletConfig; -import javax.servlet.ServletException; - -import org.jclouds.ContextBuilder; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.demo.tweetstore.config.util.CredentialsCollector; -import org.jclouds.demo.tweetstore.controller.AddTweetsController; -import org.jclouds.demo.tweetstore.controller.ClearTweetsController; -import org.jclouds.demo.tweetstore.controller.EnqueueStoresController; -import org.jclouds.demo.tweetstore.controller.StoreTweetsController; -import org.jclouds.demo.tweetstore.functions.ServiceToStoredTweetStatuses; -import org.jclouds.gae.config.GoogleAppEngineConfigurationModule; -import org.jclouds.logging.Logger; -import org.springframework.beans.factory.BeanCreationException; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.context.ServletConfigAware; -import org.springframework.web.servlet.HandlerAdapter; -import org.springframework.web.servlet.HandlerMapping; -import org.springframework.web.servlet.handler.SimpleServletHandlerAdapter; -import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping; - -import twitter4j.Twitter; -import twitter4j.TwitterFactory; -import twitter4j.conf.ConfigurationBuilder; - -import com.google.appengine.api.taskqueue.Queue; -import com.google.appengine.api.taskqueue.QueueFactory; -import com.google.common.base.Splitter; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Maps; -import com.google.common.io.Closeables; -import com.google.inject.Module; - -/** - * Creates servlets (using resources from the {@link SpringAppConfig}) and mappings. - * - * @author Andrew Phillips - * @see SpringAppConfig - */ -@Configuration -public class SpringServletConfig extends LoggingConfig implements ServletConfigAware { - public static final String PROPERTY_BLOBSTORE_CONTEXTS = "blobstore.contexts"; - - private static final Logger LOGGER = LOGGER_FACTORY.getLogger(SpringServletConfig.class.getName()); - - private ServletConfig servletConfig; - - private Map providerTypeToBlobStoreMap; - private Twitter twitterClient; - private String container; - private Queue queue; - - @PostConstruct - public void initialize() throws IOException { - Properties props = loadJCloudsProperties(); - LOGGER.trace("About to initialize members."); - - Module googleModule = new GoogleAppEngineConfigurationModule(); - Set modules = ImmutableSet. of(googleModule); - // shared across all blobstores and used to retrieve tweets - try { - twitter4j.conf.Configuration twitterConf = new ConfigurationBuilder() - .setOAuthConsumerKey(props.getProperty(PROPERTY_TWITTER_CONSUMER_KEY)) - .setOAuthConsumerSecret(props.getProperty(PROPERTY_TWITTER_CONSUMER_SECRET)) - .setOAuthAccessToken(props.getProperty(PROPERTY_TWITTER_ACCESSTOKEN)) - .setOAuthAccessTokenSecret(props.getProperty(PROPERTY_TWITTER_ACCESSTOKEN_SECRET)) - .build(); - twitterClient = new TwitterFactory(twitterConf).getInstance(); - } catch (IllegalArgumentException e) { - throw new IllegalArgumentException("properties for twitter not configured properly in " + props.toString(), e); - } - // common namespace for storing tweets - container = checkNotNull(props.getProperty(PROPERTY_TWEETSTORE_CONTAINER), PROPERTY_TWEETSTORE_CONTAINER); - - // instantiate and store references to all blobstores by provider name - providerTypeToBlobStoreMap = Maps.newHashMap(); - for (String hint : getBlobstoreContexts(props)) { - providerTypeToBlobStoreMap.put(hint, ContextBuilder.newBuilder(hint) - .modules(modules).overrides(props).build(BlobStoreContext.class)); - } - - // get a queue for submitting store tweet requests - queue = QueueFactory.getQueue("twitter"); - - LOGGER.trace("Members initialized. Twitter: '%s', container: '%s', provider types: '%s'", twitterClient, - container, providerTypeToBlobStoreMap.keySet()); - } - - private static Iterable getBlobstoreContexts(Properties props) { - Set contexts = new CredentialsCollector().apply(props).keySet(); - String explicitContexts = props.getProperty(PROPERTY_TWEETSTORE_BLOBSTORES); - if (explicitContexts != null) { - contexts = filter(contexts, in(copyOf(Splitter.on(',').split(explicitContexts)))); - } - checkState(!contexts.isEmpty(), "no credentials available for any requested context"); - return contexts; - } - - private Properties loadJCloudsProperties() { - LOGGER.trace("About to read properties from '%s'", "/WEB-INF/jclouds.properties"); - Properties props = new Properties(); - InputStream input = servletConfig.getServletContext().getResourceAsStream("/WEB-INF/jclouds.properties"); - try { - props.load(input); - } catch (IOException e) { - throw new RuntimeException(e); - } finally { - Closeables.closeQuietly(input); - } - LOGGER.trace("Properties successfully read."); - return props; - } - - @Bean - public StoreTweetsController storeTweetsController() { - StoreTweetsController controller = new StoreTweetsController(providerTypeToBlobStoreMap, container, twitterClient); - injectServletConfig(controller); - return controller; - } - - @Bean - public AddTweetsController addTweetsController() { - AddTweetsController controller = new AddTweetsController(providerTypeToBlobStoreMap, - serviceToStoredTweetStatuses()); - injectServletConfig(controller); - return controller; - } - - @Bean - public EnqueueStoresController enqueueStoresController() { - return new EnqueueStoresController(providerTypeToBlobStoreMap, queue); - } - - @Bean - public ClearTweetsController clearTweetsController() { - return new ClearTweetsController(providerTypeToBlobStoreMap, container); - } - - private void injectServletConfig(Servlet servlet) { - LOGGER.trace("About to inject servlet config '%s'", servletConfig); - try { - servlet.init(checkNotNull(servletConfig)); - } catch (ServletException exception) { - throw new BeanCreationException("Unable to instantiate " + servlet, exception); - } - LOGGER.trace("Successfully injected servlet config."); - } - - @Bean - ServiceToStoredTweetStatuses serviceToStoredTweetStatuses() { - return new ServiceToStoredTweetStatuses(providerTypeToBlobStoreMap, container); - } - - @Bean - public HandlerMapping handlerMapping() { - SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping(); - Map urlMap = Maps.newHashMapWithExpectedSize(2); - urlMap.put("/store/*", storeTweetsController()); - urlMap.put("/tweets/*", addTweetsController()); - urlMap.put("/stores/*", enqueueStoresController()); - urlMap.put("/clear/*", clearTweetsController()); - mapping.setUrlMap(urlMap); - /* - * "/store", "/tweets" and "/stores" are part of the servlet mapping and thus - * stripped by the mapping if using default settings. - */ - mapping.setAlwaysUseFullPath(true); - return mapping; - } - - @Bean - public HandlerAdapter servletHandlerAdapter() { - return new SimpleServletHandlerAdapter(); - } - - @PreDestroy - public void destroy() throws Exception { - LOGGER.trace("About to close contexts."); - for (BlobStoreContext context : providerTypeToBlobStoreMap.values()) { - context.close(); - } - LOGGER.trace("Contexts closed."); - LOGGER.trace("About to purge request queue."); - queue.purge(); - LOGGER.trace("Request queue purged."); - } - - /* - * (non-Javadoc) - * - * @see - * org.springframework.web.context.ServletConfigAware#setServletConfig(javax.servlet.ServletConfig - * ) - */ - @Override - public void setServletConfig(ServletConfig servletConfig) { - this.servletConfig = servletConfig; - } -} \ No newline at end of file diff --git a/demos/tweetstore/gae-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/config/util/CredentialsCollector.java b/demos/tweetstore/gae-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/config/util/CredentialsCollector.java deleted file mode 100644 index ce3943376e..0000000000 --- a/demos/tweetstore/gae-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/config/util/CredentialsCollector.java +++ /dev/null @@ -1,153 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.config.util; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Preconditions.checkState; -import static com.google.common.base.Predicates.notNull; -import static com.google.common.collect.Collections2.filter; -import static com.google.common.collect.Collections2.transform; -import static com.google.common.collect.ImmutableSet.copyOf; -import static com.google.common.collect.Maps.filterValues; -import static org.jclouds.util.Maps2.fromKeys; - -import java.util.Collection; -import java.util.Map; -import java.util.Properties; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.jclouds.demo.tweetstore.config.util.CredentialsCollector.Credential; - -import com.google.common.annotations.GwtIncompatible; -import com.google.common.base.Function; -import com.google.common.base.Predicate; - -/** - * Reads provider credentials from a {@link Properties} bag. - * - * @author Andrew Phillips - * - */ -public class CredentialsCollector implements Function> { - private static final String IDENTITY_PROPERTY_SUFFIX = ".identity"; - private static final String CREDENTIAL_PROPERTY_SUFFIX = ".credential"; - - // using the identity for provider name extraction - private static final Pattern IDENTITY_PROPERTY_PATTERN = - Pattern.compile("([a-zA-Z0-9-]+)" + Pattern.quote(IDENTITY_PROPERTY_SUFFIX)); - - @Override - public Map apply(final Properties properties) { - Collection providerNames = transform( - filter(properties.stringPropertyNames(), MatchesPattern.matches(IDENTITY_PROPERTY_PATTERN)), - new Function() { - @Override - public String apply(String input) { - Matcher matcher = IDENTITY_PROPERTY_PATTERN.matcher(input); - // as a side-effect, sets the matching group! - checkState(matcher.matches(), "'%s' should match '%s'", input, IDENTITY_PROPERTY_PATTERN); - return matcher.group(1); - } - }); - /* - * Providers without a credential property result in null values, which are - * removed from the returned map. - */ - return filterValues(fromKeys(copyOf(providerNames), new Function() { - @Override - public Credential apply(String providerName) { - String identity = properties.getProperty(providerName + IDENTITY_PROPERTY_SUFFIX); - String credential = properties.getProperty(providerName + CREDENTIAL_PROPERTY_SUFFIX); - return (((identity != null) && (credential != null)) - ? new Credential(identity, credential) - : null); - } - }), notNull()); - } - - public static class Credential { - private final String identity; - private final String credential; - - public Credential(String identity, String credential) { - this.identity = checkNotNull(identity, "identity"); - this.credential = checkNotNull(credential, "credential"); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result - + ((credential == null) ? 0 : credential.hashCode()); - result = prime * result - + ((identity == null) ? 0 : identity.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Credential other = (Credential) obj; - if (credential == null) { - if (other.credential != null) - return false; - } else if (!credential.equals(other.credential)) - return false; - if (identity == null) { - if (other.identity != null) - return false; - } else if (!identity.equals(other.identity)) - return false; - return true; - } - - public String getIdentity() { - return identity; - } - - public String getCredential() { - return credential; - } - } - - @GwtIncompatible(value = "java.util.regex.Pattern") - private static class MatchesPattern implements Predicate { - private final Pattern pattern; - - private MatchesPattern(Pattern pattern) { - this.pattern = pattern; - } - - @Override - public boolean apply(String input) { - return pattern.matcher(input).matches(); - } - - private static MatchesPattern matches(Pattern pattern) { - return new MatchesPattern(pattern); - } - } -} diff --git a/demos/tweetstore/gae-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/controller/AddTweetsController.java b/demos/tweetstore/gae-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/controller/AddTweetsController.java deleted file mode 100644 index 918132161e..0000000000 --- a/demos/tweetstore/gae-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/controller/AddTweetsController.java +++ /dev/null @@ -1,96 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.controller; - -import java.io.IOException; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeoutException; - -import javax.annotation.Resource; -import javax.inject.Inject; -import javax.inject.Singleton; -import javax.servlet.RequestDispatcher; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.demo.tweetstore.domain.StoredTweetStatus; -import org.jclouds.demo.tweetstore.functions.ServiceToStoredTweetStatuses; -import org.jclouds.logging.Logger; - -import com.google.appengine.repackaged.com.google.common.collect.Lists; -import com.google.common.base.Function; -import com.google.common.collect.Iterables; - -/** - * Shows an example of how to use @{link BlobStoreContext} injected with Guice. - * - * @author Adrian Cole - */ -@Singleton -public class AddTweetsController extends HttpServlet implements - Function, List> { - - /** The serialVersionUID */ - private static final long serialVersionUID = 3888348023150822683L; - private final Map contexts; - private final ServiceToStoredTweetStatuses blobStoreContextToContainerResult; - - @Resource - protected Logger logger = Logger.NULL; - - @Inject - public AddTweetsController(Map contexts, - ServiceToStoredTweetStatuses blobStoreContextToContainerResult) { - this.contexts = contexts; - this.blobStoreContextToContainerResult = blobStoreContextToContainerResult; - } - - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - try { - addMyTweetsToRequest(request); - RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/tweets.jsp"); - dispatcher.forward(request, response); - } catch (Exception e) { - logger.error(e, "Error listing containers"); - throw new ServletException(e); - } - } - - void addMyTweetsToRequest(HttpServletRequest request) throws InterruptedException, - ExecutionException, TimeoutException { - request.setAttribute("tweets", apply(contexts.keySet())); - } - - public List apply(Set in) { - List statuses = Lists.newArrayList(); - for (Iterable list : Iterables.transform(in, - blobStoreContextToContainerResult)) { - Iterables.addAll(statuses, list); - } - return statuses; - } -} \ No newline at end of file diff --git a/demos/tweetstore/gae-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/controller/ClearTweetsController.java b/demos/tweetstore/gae-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/controller/ClearTweetsController.java deleted file mode 100644 index e08cfbc19e..0000000000 --- a/demos/tweetstore/gae-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/controller/ClearTweetsController.java +++ /dev/null @@ -1,96 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.controller; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Strings.nullToEmpty; - -import java.io.IOException; -import java.util.Map; - -import javax.annotation.Resource; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.core.MediaType; - -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.jclouds.logging.Logger; - -import com.google.common.annotations.VisibleForTesting; - -/** - * Grab tweets related to me and store them into blobstores - * - * @author Adrian Cole - */ -@Singleton -public class ClearTweetsController extends HttpServlet { - /** The serialVersionUID */ - private static final long serialVersionUID = 7215420527854203714L; - - private final Map contexts; - private final String container; - - @Resource - protected Logger logger = Logger.NULL; - - @Inject - @VisibleForTesting - public ClearTweetsController(Map contexts, - @Named(TweetStoreConstants.PROPERTY_TWEETSTORE_CONTAINER) String container) { - this.container = container; - this.contexts = contexts; - } - - @VisibleForTesting - public void clearContainer(String contextName) { - BlobStoreContext context = checkNotNull(contexts.get(contextName), - "no context for %s in %s", contextName, contexts.keySet()); - try { - context.getBlobStore().clearContainer(container); - } catch (Exception e) { - logger.error(e, "Error clearing tweets in %s/%s", container, context); - } - } - - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - if (nullToEmpty(request.getHeader("X-Originator")).equals("admin")) { - try { - String contextName = checkNotNull(request.getHeader("context"), "missing header context"); - logger.info("clearing tweets in %s/%s", container, contextName); - clearContainer(contextName); - logger.debug("done clearing tweets"); - response.setContentType(MediaType.TEXT_PLAIN); - response.getWriter().println("Done!"); - } catch (Exception e) { - logger.error(e, "Error clearing tweets"); - throw new ServletException(e); - } - } else { - response.sendError(401); - } - } -} \ No newline at end of file diff --git a/demos/tweetstore/gae-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/controller/EnqueueStoresController.java b/demos/tweetstore/gae-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/controller/EnqueueStoresController.java deleted file mode 100644 index 94568e4dec..0000000000 --- a/demos/tweetstore/gae-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/controller/EnqueueStoresController.java +++ /dev/null @@ -1,92 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.controller; - -import static com.google.appengine.api.taskqueue.TaskOptions.Builder.withUrl; -import static com.google.appengine.repackaged.com.google.common.base.Strings.nullToEmpty; - -import java.io.IOException; -import java.util.Map; -import java.util.Set; - -import javax.annotation.Resource; -import javax.inject.Inject; -import javax.inject.Singleton; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.core.MediaType; - -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.logging.Logger; - -import com.google.appengine.api.taskqueue.Queue; -import com.google.appengine.api.taskqueue.TaskOptions.Method; -import com.google.common.annotations.VisibleForTesting; - -/** - * Adds tasks to retrieve and store tweets in all registered contexts to an async - * task queue. - * - * @author Andrew Phillips - * @see StoreTweetsController - */ -@Singleton -public class EnqueueStoresController extends HttpServlet { - /** The serialVersionUID */ - private static final long serialVersionUID = 7215420527854203714L; - - private final Set contextNames; - private final Queue taskQueue; - - @Resource - protected Logger logger = Logger.NULL; - - @Inject - public EnqueueStoresController(Map contexts, - Queue taskQueue) { - contextNames = contexts.keySet(); - this.taskQueue = taskQueue; - } - - @VisibleForTesting - void enqueueStoreTweetTasks() { - for (String contextName : contextNames) { - logger.debug("enqueuing task to store tweets in blobstore '%s'", contextName); - taskQueue.add(withUrl("/store/do").header("context", contextName).method(Method.GET)); - } - } - - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - if (!nullToEmpty(request.getHeader("X-AppEngine-Cron")).equals("true")) { - response.sendError(401); - } - - try { - enqueueStoreTweetTasks(); - response.setContentType(MediaType.TEXT_PLAIN); - response.getWriter().println("Done!"); - } catch (Exception e) { - logger.error(e, "Error storing tweets"); - throw new ServletException(e); - } - } -} \ No newline at end of file diff --git a/demos/tweetstore/gae-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/controller/StoreTweetsController.java b/demos/tweetstore/gae-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/controller/StoreTweetsController.java deleted file mode 100644 index ae00c69d20..0000000000 --- a/demos/tweetstore/gae-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/controller/StoreTweetsController.java +++ /dev/null @@ -1,129 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.controller; - -import static com.google.common.base.Preconditions.checkNotNull; - -import java.io.IOException; -import java.util.Map; - -import javax.annotation.Resource; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.core.MediaType; - -import org.jclouds.blobstore.BlobMap; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.blobstore.domain.Blob; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.jclouds.logging.Logger; -import org.jclouds.rest.AuthorizationException; - -import twitter4j.Status; -import twitter4j.Twitter; - -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Function; - -/** - * Grab tweets related to me and store them into blobstores - * - * @author Adrian Cole - */ -@Singleton -public class StoreTweetsController extends HttpServlet { - - private static final class StatusToBlob implements Function { - private final BlobMap map; - - private StatusToBlob(BlobMap map) { - this.map = map; - } - - public Blob apply(Status from) { - Blob to = map.blobBuilder().name(from.getId() + "").build(); - to.setPayload(from.getText()); - to.getPayload().getContentMetadata().setContentType(MediaType.TEXT_PLAIN); - to.getMetadata().getUserMetadata().put(TweetStoreConstants.SENDER_NAME, from.getUser().getScreenName()); - return to; - } - } - - /** The serialVersionUID */ - private static final long serialVersionUID = 7215420527854203714L; - - private final Map contexts; - private final Twitter client; - private final String container; - - @Resource - protected Logger logger = Logger.NULL; - - @Inject - @VisibleForTesting - public StoreTweetsController(Map contexts, - @Named(TweetStoreConstants.PROPERTY_TWEETSTORE_CONTAINER) String container, Twitter client) { - this.container = container; - this.contexts = contexts; - this.client = client; - } - - @VisibleForTesting - public void addMyTweets(String contextName, Iterable responseList) { - BlobStoreContext context = checkNotNull(contexts.get(contextName), "no context for " + contextName + " in " - + contexts.keySet()); - BlobMap map = context.createBlobMap(container); - for (Status status : responseList) { - Blob blob = null; - try { - blob = new StatusToBlob(map).apply(status); - map.put(status.getId() + "", blob); - } catch (AuthorizationException e) { - throw e; - } catch (Exception e) { - logger.error(e, "Error storing tweet %s (blob[%s]) on map %s/%s", status.getId(), blob, context, container); - } - } - } - - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - if (request.getHeader("X-AppEngine-QueueName") != null - && request.getHeader("X-AppEngine-QueueName").equals("twitter")) { - try { - String contextName = checkNotNull(request.getHeader("context"), "missing header context"); - logger.info("retrieving tweets"); - addMyTweets(contextName, client.getMentions()); - logger.debug("done storing tweets"); - response.setContentType(MediaType.TEXT_PLAIN); - response.getWriter().println("Done!"); - } catch (Exception e) { - logger.error(e, "Error storing tweets"); - throw new ServletException(e); - } - } else { - response.sendError(401); - } - } -} \ No newline at end of file diff --git a/demos/tweetstore/gae-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/domain/StoredTweetStatus.java b/demos/tweetstore/gae-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/domain/StoredTweetStatus.java deleted file mode 100644 index 42ad65df01..0000000000 --- a/demos/tweetstore/gae-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/domain/StoredTweetStatus.java +++ /dev/null @@ -1,149 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.domain; - -import java.io.Serializable; - -/** - * - * @author Adrian Cole - */ -public class StoredTweetStatus implements Comparable, Serializable { - - /** The serialVersionUID */ - private static final long serialVersionUID = -3257496189689220018L; - private final String service; - private final String host; - private final String container; - private final String id; - private final String from; - private final String tweet; - private final String status; - - @Override - public String toString() { - return "StoredTweetStatus [container=" + container + ", from=" + from + ", host=" + host - + ", id=" + id + ", service=" + service + ", status=" + status + ", tweet=" + tweet - + "]"; - } - - public StoredTweetStatus(String service, String host, String container, String id, String from, - String tweet, String status) { - this.service = service; - this.host = host; - this.container = container; - this.id = id; - this.from = from; - this.tweet = tweet; - this.status = status; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((container == null) ? 0 : container.hashCode()); - result = prime * result + ((from == null) ? 0 : from.hashCode()); - result = prime * result + ((host == null) ? 0 : host.hashCode()); - result = prime * result + ((id == null) ? 0 : id.hashCode()); - result = prime * result + ((service == null) ? 0 : service.hashCode()); - result = prime * result + ((tweet == null) ? 0 : tweet.hashCode()); - return result; - } - - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - StoredTweetStatus other = (StoredTweetStatus) obj; - if (container == null) { - if (other.container != null) - return false; - } else if (!container.equals(other.container)) - return false; - if (from == null) { - if (other.from != null) - return false; - } else if (!from.equals(other.from)) - return false; - if (host == null) { - if (other.host != null) - return false; - } else if (!host.equals(other.host)) - return false; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - if (service == null) { - if (other.service != null) - return false; - } else if (!service.equals(other.service)) - return false; - if (tweet == null) { - if (other.tweet != null) - return false; - } else if (!tweet.equals(other.tweet)) - return false; - return true; - } - - - public String getService() { - return service; - } - - public String getHost() { - return host; - } - - public String getContainer() { - return container; - } - - public String getFrom() { - return from; - } - - public String getTweet() { - return tweet; - } - - public String getStatus() { - return status; - } - - public int compareTo(StoredTweetStatus o) { - if (id == null) - return -1; - return (int) ((this == o) ? 0 : id.compareTo(o.id)); - } - - - public String getId() { - return id; - } - -} diff --git a/demos/tweetstore/gae-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/functions/KeyToStoredTweetStatus.java b/demos/tweetstore/gae-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/functions/KeyToStoredTweetStatus.java deleted file mode 100644 index f831b9780f..0000000000 --- a/demos/tweetstore/gae-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/functions/KeyToStoredTweetStatus.java +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.functions; - -import javax.annotation.Resource; - -import org.jclouds.blobstore.BlobMap; -import org.jclouds.blobstore.domain.Blob; -import org.jclouds.demo.tweetstore.domain.StoredTweetStatus; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.jclouds.logging.Logger; -import org.jclouds.util.Strings2; - -import com.google.common.base.Function; - -/** - * - * @author Adrian Cole - */ -public class KeyToStoredTweetStatus implements Function { - private final String host; - private final BlobMap map; - private final String service; - private final String container; - - @Resource - protected Logger logger = Logger.NULL; - - KeyToStoredTweetStatus(BlobMap map, String service, String host, String container) { - this.host = host; - this.map = map; - this.service = service; - this.container = container; - } - - public StoredTweetStatus apply(String id) { - String status; - String from; - String tweet; - try { - long start = System.currentTimeMillis(); - Blob blob = map.get(id); - status = ((System.currentTimeMillis() - start) + "ms"); - from = blob.getMetadata().getUserMetadata().get(TweetStoreConstants.SENDER_NAME); - tweet = Strings2.toString(blob.getPayload()); - } catch (Exception e) { - logger.error(e, "Error listing container %s//%s/%s", service, container, id); - status = (e.getMessage()); - tweet = ""; - from = ""; - } - return new StoredTweetStatus(service, host, container, id, from, tweet, status); - } -} diff --git a/demos/tweetstore/gae-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/functions/ServiceToStoredTweetStatuses.java b/demos/tweetstore/gae-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/functions/ServiceToStoredTweetStatuses.java deleted file mode 100644 index b29ec14549..0000000000 --- a/demos/tweetstore/gae-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/functions/ServiceToStoredTweetStatuses.java +++ /dev/null @@ -1,73 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.functions; - -import java.net.URI; -import java.util.Collections; -import java.util.Map; -import java.util.Set; - -import javax.annotation.Resource; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - -import org.jclouds.Context; -import org.jclouds.blobstore.BlobMap; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.demo.tweetstore.domain.StoredTweetStatus; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.jclouds.logging.Logger; - -import com.google.common.base.Function; -import com.google.common.collect.Iterables; - -@Singleton -public class ServiceToStoredTweetStatuses implements Function> { - - private final Map contexts; - private final String container; - - @Inject - public ServiceToStoredTweetStatuses(Map contexts, - @Named(TweetStoreConstants.PROPERTY_TWEETSTORE_CONTAINER) String container) { - this.contexts = contexts; - this.container = container; - } - - @Resource - protected Logger logger = Logger.NULL; - - public Iterable apply(String service) { - BlobStoreContext context = contexts.get(service); - String host = URI.create(context.unwrap(Context.class).getProviderMetadata().getEndpoint()).getHost(); - try { - BlobMap blobMap = context.createBlobMap(container); - Set blobs = blobMap.keySet(); - return Iterables.transform(blobs, new KeyToStoredTweetStatus(blobMap, service, host, - container)); - } catch (Exception e) { - StoredTweetStatus result = new StoredTweetStatus(service, host, container, null, null, - null, e.getMessage()); - logger.error(e, "Error listing service %s", service); - return Collections.singletonList(result); - } - - } -} \ No newline at end of file diff --git a/demos/tweetstore/gae-tweetstore-spring/src/main/platform/appengine-web.xml b/demos/tweetstore/gae-tweetstore-spring/src/main/platform/appengine-web.xml deleted file mode 100644 index 32d6d68a44..0000000000 --- a/demos/tweetstore/gae-tweetstore-spring/src/main/platform/appengine-web.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - ${appengine.applicationid} - 1 - - - - diff --git a/demos/tweetstore/gae-tweetstore-spring/src/main/platform/cron.xml b/demos/tweetstore/gae-tweetstore-spring/src/main/platform/cron.xml deleted file mode 100644 index 193a5402f6..0000000000 --- a/demos/tweetstore/gae-tweetstore-spring/src/main/platform/cron.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - /stores/do - Enqueue 'store tweet' tasks for all contexts - every 10 minutes - - \ No newline at end of file diff --git a/demos/tweetstore/gae-tweetstore-spring/src/main/platform/logging.properties b/demos/tweetstore/gae-tweetstore-spring/src/main/platform/logging.properties deleted file mode 100644 index 0cc0d79437..0000000000 --- a/demos/tweetstore/gae-tweetstore-spring/src/main/platform/logging.properties +++ /dev/null @@ -1,50 +0,0 @@ -# -# Licensed to jclouds, Inc. (jclouds) under one or more -# contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. jclouds licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# - -# A default java.util.logging configuration. -# (All App Engine logging is through java.util.logging by default). -# -# To use this configuration, copy it into your application's WEB-INF -# folder and add the following to your appengine-web.xml: -# -# -# -# -# - -# Set the default logging level for all loggers to INFO -.level = INFO - -org.jclouds.level=INFO -org.jclouds.demo.tweetstore.config.level=FINEST - -# Set the default logging level for ORM, specifically, to WARNING -DataNucleus.JDO.level=WARNING -DataNucleus.Persistence.level=WARNING -DataNucleus.Cache.level=WARNING -DataNucleus.MetaData.level=WARNING -DataNucleus.General.level=WARNING -DataNucleus.Utility.level=WARNING -DataNucleus.Transaction.level=WARNING -DataNucleus.Datastore.level=WARNING -DataNucleus.ClassLoading.level=WARNING -DataNucleus.Plugin.level=WARNING -DataNucleus.ValueGeneration.level=WARNING -DataNucleus.Enhancer.level=WARNING -DataNucleus.SchemaTool.level=WARNING diff --git a/demos/tweetstore/gae-tweetstore-spring/src/main/webapp/WEB-INF/dispatcher-servlet.xml b/demos/tweetstore/gae-tweetstore-spring/src/main/webapp/WEB-INF/dispatcher-servlet.xml deleted file mode 100644 index b568634994..0000000000 --- a/demos/tweetstore/gae-tweetstore-spring/src/main/webapp/WEB-INF/dispatcher-servlet.xml +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - - - - - - - - - \ No newline at end of file diff --git a/demos/tweetstore/gae-tweetstore-spring/src/main/webapp/WEB-INF/queue.xml b/demos/tweetstore/gae-tweetstore-spring/src/main/webapp/WEB-INF/queue.xml deleted file mode 100644 index 1bc53f398d..0000000000 --- a/demos/tweetstore/gae-tweetstore-spring/src/main/webapp/WEB-INF/queue.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - twitter - - 2/m - 1 - - diff --git a/demos/tweetstore/gae-tweetstore-spring/src/main/webapp/WEB-INF/web.xml b/demos/tweetstore/gae-tweetstore-spring/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index 3853142f26..0000000000 --- a/demos/tweetstore/gae-tweetstore-spring/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,66 +0,0 @@ - - - - jclouds-tweetstore-spring - - - - dispatcher - org.springframework.web.servlet.DispatcherServlet - - - - - - dispatcher - /store/* - - - dispatcher - /tweets/* - - - dispatcher - /stores/* - - - dispatcher - /clear/* - - - - - - /stores/* - - - admin - - - - - index.jsp - - \ No newline at end of file diff --git a/demos/tweetstore/gae-tweetstore-spring/src/main/webapp/index.jsp b/demos/tweetstore/gae-tweetstore-spring/src/main/webapp/index.jsp deleted file mode 100644 index fd71a31164..0000000000 --- a/demos/tweetstore/gae-tweetstore-spring/src/main/webapp/index.jsp +++ /dev/null @@ -1,31 +0,0 @@ -<%-- - - Licensed to jclouds, Inc. (jclouds) under one or more - contributor license agreements. See the NOTICE file - distributed with this work for additional information - regarding copyright ownership. jclouds licenses this file - to you under the Apache License, Version 2.0 (the - "License"); you may not use this file except in compliance - with the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, - software distributed under the License is distributed on an - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - KIND, either express or implied. See the License for the - specific language governing permissions and limitations - under the License. - ---%> - - -jclouds: anyweight cloudware for java - - -

Welcome!

-

Click here to see tweets about jclouds.

-

- - diff --git a/demos/tweetstore/gae-tweetstore-spring/src/main/webapp/tweets.jsp b/demos/tweetstore/gae-tweetstore-spring/src/main/webapp/tweets.jsp deleted file mode 100644 index 820278d4ce..0000000000 --- a/demos/tweetstore/gae-tweetstore-spring/src/main/webapp/tweets.jsp +++ /dev/null @@ -1,109 +0,0 @@ -<%-- - - Licensed to jclouds, Inc. (jclouds) under one or more - contributor license agreements. See the NOTICE file - distributed with this work for additional information - regarding copyright ownership. jclouds licenses this file - to you under the Apache License, Version 2.0 (the - "License"); you may not use this file except in compliance - with the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, - software distributed under the License is distributed on an - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - KIND, either express or implied. See the License for the - specific language governing permissions and limitations - under the License. - ---%> -<%@ page buffer="20kb"%> -<%@ taglib uri="http://displaytag.sf.net" prefix="display"%> - - -jclouds: anyweight cloudware for java - - - -

Tweets in Clouds

- - - - - - - -
-
- - - - - - - - -
-
- - diff --git a/demos/tweetstore/gae-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/config/util/CredentialsCollectorTest.java b/demos/tweetstore/gae-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/config/util/CredentialsCollectorTest.java deleted file mode 100644 index 031bb199fc..0000000000 --- a/demos/tweetstore/gae-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/config/util/CredentialsCollectorTest.java +++ /dev/null @@ -1,82 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.config.util; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; - -import java.util.Map; -import java.util.Properties; - -import org.jclouds.demo.tweetstore.config.util.CredentialsCollector; -import org.jclouds.demo.tweetstore.config.util.CredentialsCollector.Credential; -import org.testng.annotations.Test; - -import com.google.common.collect.ImmutableMap; - -/** - * Tests behavior of {@code CredentialsCollector} - * - * @author Andrew Phillips - */ -@Test(groups = "unit") -public class CredentialsCollectorTest { - private CredentialsCollector collector = new CredentialsCollector(); - - public void testEmptyProperties() { - assertTrue(collector.apply(new Properties()).isEmpty(), - "Expected returned map to be empty"); - } - - public void testNoCredentials() { - Properties properties = propertiesOf(ImmutableMap.of("not-an-identity", - "v1", "not-a-credential", "v2")); - assertTrue(collector.apply(properties).isEmpty(), - "Expected returned map to be empty"); - } - - private static Properties propertiesOf(Map entries) { - Properties properties = new Properties(); - properties.putAll(entries); - return properties; - } - - public void testNonMatchingCredentials() { - Properties properties = propertiesOf(ImmutableMap.of("non_matching.identity", "v1", - "non_matching.credential", "v2")); - assertTrue(collector.apply(properties).isEmpty(), - "Expected returned map to be empty"); - } - - public void testIncompleteCredentials() { - Properties properties = propertiesOf(ImmutableMap.of("acme.identity", "v1", - "acme-2.credential", "v2")); - assertTrue(collector.apply(properties).isEmpty(), - "Expected returned map to be empty"); - } - - public void testCredentials() { - Properties properties = propertiesOf(ImmutableMap.of("acme.identity", "v1", - "acme.credential", "v2", "acme-2.identity", "v3", - "acme-2.credential", "v4")); - assertEquals(collector.apply(properties), - ImmutableMap.of("acme", new Credential("v1", "v2"), - "acme-2", new Credential("v3", "v4"))); - } -} \ No newline at end of file diff --git a/demos/tweetstore/gae-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/controller/AddTweetsControllerTest.java b/demos/tweetstore/gae-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/controller/AddTweetsControllerTest.java deleted file mode 100644 index 1c93403650..0000000000 --- a/demos/tweetstore/gae-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/controller/AddTweetsControllerTest.java +++ /dev/null @@ -1,78 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.controller; - -import static org.testng.Assert.assertEquals; - -import java.io.IOException; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ExecutionException; - -import org.jclouds.ContextBuilder; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.blobstore.TransientApiMetadata; -import org.jclouds.blobstore.domain.Blob; -import org.jclouds.demo.tweetstore.domain.StoredTweetStatus; -import org.jclouds.demo.tweetstore.functions.ServiceToStoredTweetStatuses; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.testng.annotations.Test; -import org.testng.collections.Maps; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableSet; - -/** - * Tests behavior of {@code AddTweetsController} - * - * @author Adrian Cole - */ -@Test(groups = "unit") -public class AddTweetsControllerTest { - - Map createServices(String container) throws InterruptedException, - ExecutionException { - Map services = Maps.newHashMap(); - TransientApiMetadata transientApiMetadata = TransientApiMetadata.builder().build(); - for (String name : new String[] { "1", "2" }) { - BlobStoreContext context = ContextBuilder.newBuilder(transientApiMetadata).build(BlobStoreContext.class); - context.getAsyncBlobStore().createContainerInLocation(null, container).get(); - Blob blob = context.getAsyncBlobStore().blobBuilder("1").build(); - blob.getMetadata().getUserMetadata().put(TweetStoreConstants.SENDER_NAME, "frank"); - blob.setPayload("I love beans!"); - context.getAsyncBlobStore().putBlob(container, blob).get(); - services.put(name, context); - } - return services; - } - - public void testStoreTweets() throws IOException, InterruptedException, ExecutionException { - String container = "container"; - Map contexts = createServices(container); - - ServiceToStoredTweetStatuses function = new ServiceToStoredTweetStatuses(contexts, container); - AddTweetsController controller = new AddTweetsController(contexts, function); - List list = controller.apply(ImmutableSet.of("1", "2")); - assertEquals(list.size(), 2); - assertEquals(list, ImmutableList.of(new StoredTweetStatus("1", "localhost", container, "1", - "frank", "I love beans!", null), new StoredTweetStatus("2", "localhost", container, - "1", "frank", "I love beans!", null))); - - } -} diff --git a/demos/tweetstore/gae-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/controller/ClearTweetsControllerTest.java b/demos/tweetstore/gae-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/controller/ClearTweetsControllerTest.java deleted file mode 100644 index 81f0b9f3c7..0000000000 --- a/demos/tweetstore/gae-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/controller/ClearTweetsControllerTest.java +++ /dev/null @@ -1,72 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.controller; - -import static org.testng.Assert.assertEquals; - -import java.io.IOException; -import java.util.Map; -import java.util.concurrent.ExecutionException; - -import org.jclouds.ContextBuilder; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.blobstore.TransientApiMetadata; -import org.jclouds.blobstore.domain.Blob; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.testng.annotations.Test; - -import com.google.common.collect.ImmutableMap; - -/** - * Tests behavior of {@code AddTweetsController} - * - * @author Adrian Cole - */ -@Test(groups = "unit") -public class ClearTweetsControllerTest { - - Map createBlobStores(String container) throws InterruptedException, ExecutionException { - TransientApiMetadata transientApiMetadata = TransientApiMetadata.builder().build(); - Map contexts = ImmutableMap.of( - "test1", ContextBuilder.newBuilder(transientApiMetadata).build(BlobStoreContext.class), - "test2", ContextBuilder.newBuilder(transientApiMetadata).build(BlobStoreContext.class)); - for (BlobStoreContext blobstore : contexts.values()) { - blobstore.getBlobStore().createContainerInLocation(null, container); - Blob blob = blobstore.getAsyncBlobStore().blobBuilder("1").build(); - blob.getMetadata().getUserMetadata().put(TweetStoreConstants.SENDER_NAME, "frank"); - blob.setPayload("I love beans!"); - blobstore.getBlobStore().putBlob(container, blob); - } - return contexts; - } - - public void testClearTweets() throws IOException, InterruptedException, ExecutionException { - String container = ClearTweetsControllerTest.class.getName() + "#container"; - Map contexts = createBlobStores(container); - - ClearTweetsController controller = new ClearTweetsController(contexts, - container); - controller.clearContainer("test1"); - controller.clearContainer("test2"); - - for (BlobStoreContext context : contexts.values()) { - assertEquals(context.getBlobStore().countBlobs(container), 0, context.toString()); - } - } -} diff --git a/demos/tweetstore/gae-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/controller/EnqueueStoresControllerTest.java b/demos/tweetstore/gae-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/controller/EnqueueStoresControllerTest.java deleted file mode 100644 index 5190718e4c..0000000000 --- a/demos/tweetstore/gae-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/controller/EnqueueStoresControllerTest.java +++ /dev/null @@ -1,67 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.controller; - -import static com.google.appengine.api.taskqueue.TaskOptions.Builder.withUrl; -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.verify; - -import java.util.Map; - -import org.jclouds.ContextBuilder; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.blobstore.TransientApiMetadata; -import org.testng.annotations.Test; - -import com.google.appengine.api.taskqueue.Queue; -import com.google.appengine.api.taskqueue.TaskOptions.Method; -import com.google.common.collect.ImmutableMap; - -/** - * Tests behavior of {@link EnqueueStoresController} - * - * @author Andrew Phillips - */ -@Test(groups = "unit") -public class EnqueueStoresControllerTest { - - Map createBlobStores() { - TransientApiMetadata transientApiMetadata = TransientApiMetadata.builder().build(); - Map contexts = ImmutableMap.of( - "test1", ContextBuilder.newBuilder(transientApiMetadata).build(BlobStoreContext.class), - "test2", ContextBuilder.newBuilder(transientApiMetadata).build(BlobStoreContext.class)); - return contexts; - } - - public void testEnqueueStores() { - Map stores = createBlobStores(); - Queue taskQueue = createMock(Queue.class); - EnqueueStoresController function = new EnqueueStoresController(stores, taskQueue); - - expect(taskQueue.add(withUrl("/store/do").header("context", "test1").method(Method.GET))).andReturn(null); - expect(taskQueue.add(withUrl("/store/do").header("context", "test2").method(Method.GET))).andReturn(null); - replay(taskQueue); - - function.enqueueStoreTweetTasks(); - - verify(taskQueue); - } -} diff --git a/demos/tweetstore/gae-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/controller/StoreTweetsControllerTest.java b/demos/tweetstore/gae-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/controller/StoreTweetsControllerTest.java deleted file mode 100644 index 084b18a8c5..0000000000 --- a/demos/tweetstore/gae-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/controller/StoreTweetsControllerTest.java +++ /dev/null @@ -1,120 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.controller; - -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.verify; -import static org.testng.Assert.assertEquals; - -import java.io.IOException; -import java.util.Map; -import java.util.Map.Entry; -import java.util.concurrent.ExecutionException; - -import org.jclouds.ContextBuilder; -import org.jclouds.blobstore.BlobMap; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.blobstore.TransientApiMetadata; -import org.jclouds.blobstore.domain.Blob; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.jclouds.util.Strings2; -import org.testng.annotations.Test; - -import twitter4j.Status; -import twitter4j.Twitter; -import twitter4j.User; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; - -/** - * Tests behavior of {@code StoreTweetsController} - * - * @author Adrian Cole - */ -@Test(groups = "unit") -public class StoreTweetsControllerTest { - - Twitter createTwitter() { - return createMock(Twitter.class); - } - - Map createBlobStores() throws InterruptedException, ExecutionException { - TransientApiMetadata transientApiMetadata = TransientApiMetadata.builder().build(); - Map contexts = ImmutableMap.of( - "test1", ContextBuilder.newBuilder(transientApiMetadata).build(BlobStoreContext.class), - "test2", ContextBuilder.newBuilder(transientApiMetadata).build(BlobStoreContext.class)); - for (BlobStoreContext blobstore : contexts.values()) { - blobstore.getAsyncBlobStore().createContainerInLocation(null, "favo").get(); - } - return contexts; - } - - public void testStoreTweets() throws IOException, InterruptedException, ExecutionException { - Map stores = createBlobStores(); - StoreTweetsController function = new StoreTweetsController(stores, "favo", createTwitter()); - - User frank = createMock(User.class); - expect(frank.getScreenName()).andReturn("frank").atLeastOnce(); - - Status frankStatus = createMock(Status.class); - expect(frankStatus.getId()).andReturn(1l).atLeastOnce(); - expect(frankStatus.getUser()).andReturn(frank).atLeastOnce(); - expect(frankStatus.getText()).andReturn("I love beans!").atLeastOnce(); - - User jimmy = createMock(User.class); - expect(jimmy.getScreenName()).andReturn("jimmy").atLeastOnce(); - - Status jimmyStatus = createMock(Status.class); - expect(jimmyStatus.getId()).andReturn(2l).atLeastOnce(); - expect(jimmyStatus.getUser()).andReturn(jimmy).atLeastOnce(); - expect(jimmyStatus.getText()).andReturn("cloud is king").atLeastOnce(); - - replay(frank); - replay(frankStatus); - replay(jimmy); - replay(jimmyStatus); - - function.addMyTweets("test1", ImmutableList.of(frankStatus, jimmyStatus)); - function.addMyTweets("test2", ImmutableList.of(frankStatus, jimmyStatus)); - - verify(frank); - verify(frankStatus); - verify(jimmy); - verify(jimmyStatus); - - for (Entry entry : stores.entrySet()) { - BlobMap map = entry.getValue().createBlobMap("favo"); - Blob frankBlob = map.get("1"); - assertEquals(frankBlob.getMetadata().getName(), "1"); - assertEquals(frankBlob.getMetadata().getUserMetadata().get(TweetStoreConstants.SENDER_NAME), "frank"); - assertEquals(frankBlob.getMetadata().getContentMetadata().getContentType(), "text/plain"); - assertEquals(Strings2.toString(frankBlob.getPayload()), "I love beans!"); - - Blob jimmyBlob = map.get("2"); - assertEquals(jimmyBlob.getMetadata().getName(), "2"); - assertEquals(jimmyBlob.getMetadata().getUserMetadata().get(TweetStoreConstants.SENDER_NAME), "jimmy"); - assertEquals(jimmyBlob.getMetadata().getContentMetadata().getContentType(), "text/plain"); - assertEquals(Strings2.toString(jimmyBlob.getPayload()), "cloud is king"); - } - - } -} diff --git a/demos/tweetstore/gae-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/functions/KeyToStoredTweetStatusTest.java b/demos/tweetstore/gae-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/functions/KeyToStoredTweetStatusTest.java deleted file mode 100644 index af74b423d5..0000000000 --- a/demos/tweetstore/gae-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/functions/KeyToStoredTweetStatusTest.java +++ /dev/null @@ -1,69 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.functions; - -import static org.testng.Assert.assertEquals; - -import java.io.IOException; -import java.util.concurrent.ExecutionException; - -import org.jclouds.ContextBuilder; -import org.jclouds.blobstore.BlobMap; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.blobstore.TransientApiMetadata; -import org.jclouds.blobstore.domain.Blob; -import org.jclouds.demo.tweetstore.domain.StoredTweetStatus; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.testng.annotations.Test; - -/** - * Tests behavior of {@code KeyToStoredTweetStatus} - * - * @author Adrian Cole - */ -@Test(groups = "unit") -public class KeyToStoredTweetStatusTest { - - BlobMap createMap() throws InterruptedException, ExecutionException { - BlobStoreContext context = - ContextBuilder.newBuilder(TransientApiMetadata.builder().build()).build(BlobStoreContext.class); - context.getBlobStore().createContainerInLocation(null, "test1"); - return context.createBlobMap("test1"); - } - - public void testStoreTweets() throws IOException, InterruptedException, ExecutionException { - BlobMap map = createMap(); - Blob blob = map.blobBuilder().name("1").build(); - blob.getMetadata().getUserMetadata().put(TweetStoreConstants.SENDER_NAME, "frank"); - blob.setPayload("I love beans!"); - map.put("1", blob); - String host = "localhost"; - String service = "stub"; - String container = "tweetstore"; - - KeyToStoredTweetStatus function = new KeyToStoredTweetStatus(map, service, host, container); - StoredTweetStatus result = function.apply("1"); - - StoredTweetStatus expected = new StoredTweetStatus(service, host, container, "1", "frank", - "I love beans!", null); - - assertEquals(result, expected); - - } -} diff --git a/demos/tweetstore/gae-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/functions/ServiceToStoredTweetStatusesTest.java b/demos/tweetstore/gae-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/functions/ServiceToStoredTweetStatusesTest.java deleted file mode 100644 index 5fec52711e..0000000000 --- a/demos/tweetstore/gae-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/functions/ServiceToStoredTweetStatusesTest.java +++ /dev/null @@ -1,75 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.functions; - -import static org.testng.Assert.assertEquals; - -import java.io.IOException; -import java.util.Map; -import java.util.concurrent.ExecutionException; - -import org.jclouds.ContextBuilder; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.blobstore.TransientApiMetadata; -import org.jclouds.blobstore.domain.Blob; -import org.jclouds.demo.tweetstore.domain.StoredTweetStatus; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.testng.annotations.Test; -import org.testng.collections.Maps; - -import com.google.common.collect.Iterables; - -/** - * Tests behavior of {@code ServiceToStoredTweetStatuses} - * - * @author Adrian Cole - */ -@Test(groups = "unit") -public class ServiceToStoredTweetStatusesTest { - - Map createServices(String container) throws InterruptedException, - ExecutionException { - Map services = Maps.newHashMap(); - TransientApiMetadata transientApiMetadata = TransientApiMetadata.builder().build(); - for (String name : new String[] { "1", "2" }) { - BlobStoreContext context = ContextBuilder.newBuilder(transientApiMetadata).build(BlobStoreContext.class); - context.getAsyncBlobStore().createContainerInLocation(null, container).get(); - Blob blob = context.getAsyncBlobStore().blobBuilder("1").build(); - blob.getMetadata().getUserMetadata().put(TweetStoreConstants.SENDER_NAME, "frank"); - blob.setPayload("I love beans!"); - context.getAsyncBlobStore().putBlob(container, blob).get(); - services.put(name, context); - } - return services; - } - - public void testStoreTweets() throws IOException, InterruptedException, ExecutionException { - String container = "container"; - Map contexts = createServices(container); - - ServiceToStoredTweetStatuses function = new ServiceToStoredTweetStatuses(contexts, container); - - assertEquals(Iterables.getLast(function.apply("1")), new StoredTweetStatus("1", "localhost", - container, "1", "frank", "I love beans!", null)); - - assertEquals(Iterables.getLast(function.apply("2")), new StoredTweetStatus("2", "localhost", - container, "1", "frank", "I love beans!", null)); - - } -} diff --git a/demos/tweetstore/gae-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/integration/GoogleDevServer.java b/demos/tweetstore/gae-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/integration/GoogleDevServer.java deleted file mode 100644 index 63223607ac..0000000000 --- a/demos/tweetstore/gae-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/integration/GoogleDevServer.java +++ /dev/null @@ -1,87 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.integration; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.io.Closeables.closeQuietly; -import static java.lang.String.format; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Properties; -import java.util.concurrent.TimeUnit; - -import com.google.appengine.tools.KickStart; -import com.google.appengine.tools.info.SdkInfo; - -/** - * Basic functionality to start a local google app engine instance. - * - * @author Adrian Cole - */ -public class GoogleDevServer { - - Thread server; - - public void writePropertiesAndStartServer(final String address, - final String port, final String warfile, Properties props) - throws IOException, InterruptedException { - String filename = String.format( - "%1$s/WEB-INF/jclouds.properties", warfile); - System.err.println("file: " + filename); - storeProperties(filename, props); - assert new File(filename).exists(); - this.server = new Thread(new Runnable() { - public void run() { - String sdkRoot = checkNotNull(System.getProperty(SdkInfo.SDK_ROOT_PROPERTY), SdkInfo.SDK_ROOT_PROPERTY); - KickStart.main(new String[] { - KickStarter.systemProperty("java.util.logging.config.file", - format("%s/WEB-INF/logging.properties", warfile)), - KickStarter.systemProperty(SdkInfo.SDK_ROOT_PROPERTY, sdkRoot), - "com.google.appengine.tools.development.DevAppServerMain", - "--disable_update_check", - format("--sdk_root=%s", sdkRoot), - "-a", address, "-p", port, warfile }); - } - }); - server.start(); - TimeUnit.SECONDS.sleep(30); - } - - private static void storeProperties(String filename, Properties props) throws IOException { - FileOutputStream targetFile = new FileOutputStream(filename); - try { - props.store(targetFile, "test"); - } finally { - closeQuietly(targetFile); - } - } - - public void stop() throws Exception { - // KickStart.main opens a process and calls process.waitFor(), which is interruptable - server.interrupt(); - } - - private static class KickStarter { - private static String systemProperty(String key, String value) { - return format("--jvm_flag=-D%s=%s", key, value); - } - } -} \ No newline at end of file diff --git a/demos/tweetstore/gae-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/integration/TweetStoreLiveTest.java b/demos/tweetstore/gae-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/integration/TweetStoreLiveTest.java deleted file mode 100644 index 7ed1008bab..0000000000 --- a/demos/tweetstore/gae-tweetstore-spring/src/test/java/org/jclouds/demo/tweetstore/integration/TweetStoreLiveTest.java +++ /dev/null @@ -1,234 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.integration; - -import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.demo.tweetstore.reference.TweetStoreConstants.PROPERTY_TWEETSTORE_BLOBSTORES; -import static org.jclouds.demo.tweetstore.reference.TweetStoreConstants.PROPERTY_TWEETSTORE_CONTAINER; -import static org.jclouds.demo.tweetstore.reference.TwitterConstants.PROPERTY_TWITTER_ACCESSTOKEN; -import static org.jclouds.demo.tweetstore.reference.TwitterConstants.PROPERTY_TWITTER_ACCESSTOKEN_SECRET; -import static org.jclouds.demo.tweetstore.reference.TwitterConstants.PROPERTY_TWITTER_CONSUMER_KEY; -import static org.jclouds.demo.tweetstore.reference.TwitterConstants.PROPERTY_TWITTER_CONSUMER_SECRET; - -import java.io.IOException; -import java.io.InputStream; -import java.net.HttpURLConnection; -import java.net.URL; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Properties; -import java.util.Set; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeoutException; - -import org.jclouds.Context; -import org.jclouds.ContextBuilder; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.demo.tweetstore.config.SpringServletConfig; -import org.jclouds.demo.tweetstore.controller.StoreTweetsController; -import org.jclouds.logging.log4j.config.Log4JLoggingModule; -import org.jclouds.util.Strings2; -import org.testng.annotations.AfterTest; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.Parameters; -import org.testng.annotations.Test; - -import twitter4j.ResponseList; -import twitter4j.Status; -import twitter4j.Twitter; -import twitter4j.TwitterException; -import twitter4j.TwitterFactory; -import twitter4j.conf.Configuration; -import twitter4j.conf.ConfigurationBuilder; - -import com.google.common.base.Joiner; -import com.google.common.base.Splitter; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Maps; -import com.google.inject.Module; - -/** - * Starts up the Google App Engine for Java Development environment and deploys an application which - * tests accesses twitter and blobstores. - * - * @author Adrian Cole - */ -@Test(groups = "live", singleThreaded = true) -public class TweetStoreLiveTest { - - GoogleDevServer server; - private URL url; - private Map contexts; - private String container; - - private static final Iterable blobstores = - Splitter.on(',').split(System.getProperty(PROPERTY_TWEETSTORE_BLOBSTORES, - "cloudfiles-us,aws-s3,azureblob")); - private static final Properties props = new Properties(); - - @BeforeTest - void clearAndCreateContainers() throws InterruptedException, ExecutionException, TimeoutException, IOException, - TwitterException { - container = getRequiredSystemProperty(PROPERTY_TWEETSTORE_CONTAINER); - - props.setProperty(PROPERTY_TWEETSTORE_CONTAINER, container); - props.setProperty(SpringServletConfig.PROPERTY_BLOBSTORE_CONTEXTS, Joiner.on(',').join(blobstores)); - - // put all identity/credential pairs into the client - addCredentialsForBlobStores(props); - - // example of an ad-hoc client configuration - addConfigurationForTwitter(props); - - // for testing, capture logs. - final Set wiring = ImmutableSet. of(new Log4JLoggingModule()); - this.contexts = Maps.newConcurrentMap(); - - for (String provider : blobstores) { - contexts.put(provider, ContextBuilder.newBuilder(provider) - .modules(wiring).overrides(props).build(BlobStoreContext.class)); - } - - Configuration conf = new ConfigurationBuilder() - .setOAuthConsumerKey(props.getProperty(PROPERTY_TWITTER_CONSUMER_KEY)) - .setOAuthConsumerSecret(props.getProperty(PROPERTY_TWITTER_CONSUMER_SECRET)) - .setOAuthAccessToken(props.getProperty(PROPERTY_TWITTER_ACCESSTOKEN)) - .setOAuthAccessTokenSecret(props.getProperty(PROPERTY_TWITTER_ACCESSTOKEN_SECRET)) - .build(); - Twitter client = new TwitterFactory(conf).getInstance(); - StoreTweetsController controller = new StoreTweetsController(contexts, container, client); - - ResponseList statuses = client.getMentions(); - - boolean deleted = false; - for (BlobStoreContext context : contexts.values()) { - if (context.getBlobStore().containerExists(container)) { - System.err.printf("deleting container %s at %s%n", container, - context.unwrap(Context.class).getProviderMetadata().getEndpoint()); - context.getBlobStore().deleteContainer(container); - deleted = true; - } - } - if (deleted) { - System.err.println("sleeping 60 seconds to allow containers to clear"); - Thread.sleep(60000); - } - for (BlobStoreContext context : contexts.values()) { - System.err.printf("creating container %s at %s%n", container, - context.unwrap(Context.class).getProviderMetadata().getEndpoint()); - context.getBlobStore().createContainerInLocation(null, container); - } - if (deleted) { - System.err.println("sleeping 5 seconds to allow containers to create"); - Thread.sleep(5000); - } - - for (Entry entry : contexts.entrySet()) { - System.err.printf("filling container %s at %s%n", container, entry.getKey()); - controller.addMyTweets(entry.getKey(), statuses); - } - } - - private static String getRequiredSystemProperty(String key) { - return checkNotNull(System.getProperty(key), key); - } - - private void addConfigurationForTwitter(Properties props) { - props.setProperty(PROPERTY_TWITTER_CONSUMER_KEY, - getRequiredSystemProperty("test." + PROPERTY_TWITTER_CONSUMER_KEY)); - props.setProperty(PROPERTY_TWITTER_CONSUMER_SECRET, - getRequiredSystemProperty("test." + PROPERTY_TWITTER_CONSUMER_SECRET)); - props.setProperty(PROPERTY_TWITTER_ACCESSTOKEN, - getRequiredSystemProperty("test." + PROPERTY_TWITTER_ACCESSTOKEN)); - props.setProperty(PROPERTY_TWITTER_ACCESSTOKEN_SECRET, - getRequiredSystemProperty("test." + PROPERTY_TWITTER_ACCESSTOKEN_SECRET)); - } - - private void addCredentialsForBlobStores(Properties props) { - for (String provider : blobstores) { - props.setProperty(provider + ".identity", - getRequiredSystemProperty("test." + provider + ".identity")); - props.setProperty(provider + ".credential", - getRequiredSystemProperty("test." + provider + ".credential")); - } - } - - @BeforeTest - @Parameters({ "warfile", "devappserver.address", "devappserver.port" }) - public void startDevAppServer(final String warfile, final String address, final String port) throws Exception { - url = new URL(String.format("http://%s:%s", address, port)); - server = new GoogleDevServer(); - server.writePropertiesAndStartServer(address, port, warfile, props); - } - - @Test - public void shouldPass() throws InterruptedException, IOException { - InputStream i = url.openStream(); - String string = Strings2.toStringAndClose(i); - assert string.indexOf("Welcome") >= 0 : string; - } - - @Test(dependsOnMethods = "shouldPass", expectedExceptions = IOException.class) - public void shouldFail() throws InterruptedException, IOException { - new URL(url, "/store/do").openStream(); - } - - @Test(dependsOnMethods = "shouldFail") - public void testPrimeContainers() throws IOException, InterruptedException { - URL gurl = new URL(url, "/store/do"); - // WATCH THIS, you need to add a context each time - for (String context : blobstores) { - System.out.println("storing at context: " + context); - HttpURLConnection connection = (HttpURLConnection) gurl.openConnection(); - connection.addRequestProperty("X-AppEngine-QueueName", "twitter"); - connection.addRequestProperty("context", context); - InputStream i = connection.getInputStream(); - String string = Strings2.toStringAndClose(i); - assert string.indexOf("Done!") >= 0 : string; - connection.disconnect(); - } - - System.err.println("sleeping 20 seconds to allow for eventual consistency delay"); - Thread.sleep(20000); - for (BlobStoreContext context : contexts.values()) { - assert context.createInputStreamMap(container).size() > 0 : context.unwrap(Context.class).getProviderMetadata().getEndpoint(); - } - } - - @Test(invocationCount = 5, dependsOnMethods = "testPrimeContainers") - public void testSerial() throws InterruptedException, IOException { - URL gurl = new URL(url, "/tweets/get"); - InputStream i = gurl.openStream(); - String string = Strings2.toStringAndClose(i); - assert string.indexOf("Tweets in Clouds") >= 0 : string; - } - - @Test(invocationCount = 10, dependsOnMethods = "testPrimeContainers", threadPoolSize = 3) - public void testParallel() throws InterruptedException, IOException { - URL gurl = new URL(url, "/tweets/get"); - InputStream i = gurl.openStream(); - String string = Strings2.toStringAndClose(i); - assert string.indexOf("Tweets in Clouds") >= 0 : string; - } - - @AfterTest - public void stopDevAppServer() throws Exception { - server.stop(); - } -} diff --git a/demos/tweetstore/gae-tweetstore-spring/src/test/resources/log4j.xml b/demos/tweetstore/gae-tweetstore-spring/src/test/resources/log4j.xml deleted file mode 100644 index 2e5d01fb9e..0000000000 --- a/demos/tweetstore/gae-tweetstore-spring/src/test/resources/log4j.xml +++ /dev/null @@ -1,95 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/demos/tweetstore/gae-tweetstore/README.txt b/demos/tweetstore/gae-tweetstore/README.txt deleted file mode 100644 index d8dddf3a2d..0000000000 --- a/demos/tweetstore/gae-tweetstore/README.txt +++ /dev/null @@ -1,56 +0,0 @@ -==== - Licensed to jclouds, Inc. (jclouds) under one or more - contributor license agreements. See the NOTICE file - distributed with this work for additional information - regarding copyright ownership. jclouds licenses this file - to you under the Apache License, Version 2.0 (the - "License"); you may not use this file except in compliance - with the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, - software distributed under the License is distributed on an - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - KIND, either express or implied. See the License for the - specific language governing permissions and limitations - under the License. -==== - -A guide to generating Twitter consumer keys and access tokens is at http://tinyurl.com/2fhebgb - -This sample uses the Google App Engine for Java SDK located at -http://code.google.com/p/googleappengine/downloads/list - -Please unzip the above file and modify your maven settings.xml like below before -attempting to run 'mvn -Plive install' - - - appengine - - true - - - /path/to/appengine-java-sdk-1.4.2 - yourappid - - - - - keys - - true - - - YOUR_ACCESS_KEY_ID - YOUR_SECRET_KEY - YOUR_USER - YOUR_HEX_KEY - YOUR_ACCOUNT - YOUR_BASE64_ENCODED_KEY - YOUR_TWITTER_CONSUMER_KEY - YOUR_TWITTER_CONSUMER_SECRET - YOUR_TWITTER_ACCESSTOKEN - YOUR_TWITTER_ACCESSTOKEN_SECRET - - \ No newline at end of file diff --git a/demos/tweetstore/gae-tweetstore/pom.xml b/demos/tweetstore/gae-tweetstore/pom.xml deleted file mode 100644 index 99055e4cbc..0000000000 --- a/demos/tweetstore/gae-tweetstore/pom.xml +++ /dev/null @@ -1,138 +0,0 @@ - - - - 4.0.0 - - org.jclouds - jclouds-demos-tweetstore-project - 1.5.0-SNAPSHOT - - jclouds-demo-gae-tweetstore - war - jclouds TweetStore for Google App Engine - jclouds TweetStore for Google App Engine using Guice for Dependency Injection - - - - jclouds-tweetstore - 1.6.1 - localhost - 8088 - jclouds-gae-tweetstore - - - - - org.jclouds.driver - jclouds-gae - ${project.version} - - - com.google.inject.extensions - guice-servlet - 3.0 - - - - - com.google.appengine - appengine-api-1.0-sdk - ${appengine.sdk.version} - - - com.google.appengine - appengine-tools-sdk - ${appengine.sdk.version} - test - - - - - - live - - - - maven-surefire-plugin - - - integration - integration-test - - test - - - - ${test.twitter.gae-tweetstore.consumer.identity} - ${test.twitter.gae-tweetstore.consumer.credential} - ${test.twitter.gae-tweetstore.access.identity} - ${test.twitter.gae-tweetstore.access.credential} - ${test.azureblob.identity} - ${test.azureblob.credential} - ${test.cloudfiles-us.identity} - ${test.cloudfiles-us.credential} - ${test.aws-s3.identity} - ${test.aws-s3.credential} - ${appengine.sdk.root} - ${test.cloudonestorage.identity} - ${test.cloudonestorage.credential} - ${test.ninefold-storage.identity} - ${test.ninefold-storage.credential} - ${devappserver.address} - ${devappserver.port} - ${jclouds.tweetstore.blobstores} - test.${jclouds.tweetstore.container} - ${project.build.directory}/${project.artifactId} - - - - - - - - - - - deploy - - - gae-tweetstore - - - - - net.kindleit - maven-gae-plugin - 0.9.2 - - google-appengine - ${appengine.sdk.root} - - - - - - - diff --git a/demos/tweetstore/gae-tweetstore/src/main/java/org/jclouds/demo/tweetstore/config/GuiceServletConfig.java b/demos/tweetstore/gae-tweetstore/src/main/java/org/jclouds/demo/tweetstore/config/GuiceServletConfig.java deleted file mode 100644 index 4be8fb5d64..0000000000 --- a/demos/tweetstore/gae-tweetstore/src/main/java/org/jclouds/demo/tweetstore/config/GuiceServletConfig.java +++ /dev/null @@ -1,165 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.config; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Preconditions.checkState; -import static com.google.common.base.Predicates.in; -import static com.google.common.collect.ImmutableSet.copyOf; -import static com.google.common.collect.Sets.filter; -import static org.jclouds.demo.tweetstore.reference.TweetStoreConstants.PROPERTY_TWEETSTORE_BLOBSTORES; -import static org.jclouds.demo.tweetstore.reference.TweetStoreConstants.PROPERTY_TWEETSTORE_CONTAINER; -import static org.jclouds.demo.tweetstore.reference.TwitterConstants.PROPERTY_TWITTER_ACCESSTOKEN; -import static org.jclouds.demo.tweetstore.reference.TwitterConstants.PROPERTY_TWITTER_ACCESSTOKEN_SECRET; -import static org.jclouds.demo.tweetstore.reference.TwitterConstants.PROPERTY_TWITTER_CONSUMER_KEY; -import static org.jclouds.demo.tweetstore.reference.TwitterConstants.PROPERTY_TWITTER_CONSUMER_SECRET; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Map; -import java.util.Properties; -import java.util.Set; - -import javax.servlet.ServletContextEvent; - -import org.jclouds.ContextBuilder; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.demo.tweetstore.config.util.CredentialsCollector; -import org.jclouds.demo.tweetstore.controller.AddTweetsController; -import org.jclouds.demo.tweetstore.controller.ClearTweetsController; -import org.jclouds.demo.tweetstore.controller.EnqueueStoresController; -import org.jclouds.demo.tweetstore.controller.StoreTweetsController; -import org.jclouds.gae.config.GoogleAppEngineConfigurationModule; - -import twitter4j.Twitter; -import twitter4j.TwitterFactory; -import twitter4j.conf.Configuration; -import twitter4j.conf.ConfigurationBuilder; - -import com.google.appengine.api.taskqueue.Queue; -import com.google.appengine.api.taskqueue.QueueFactory; -import com.google.appengine.repackaged.com.google.common.base.Splitter; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Maps; -import com.google.common.io.Closeables; -import com.google.inject.Guice; -import com.google.inject.Injector; -import com.google.inject.Module; -import com.google.inject.TypeLiteral; -import com.google.inject.name.Names; -import com.google.inject.servlet.GuiceServletContextListener; -import com.google.inject.servlet.ServletModule; - -/** - * Setup Logging and create Injector for use in testing S3. - * - * @author Adrian Cole - */ -public class GuiceServletConfig extends GuiceServletContextListener { - public static final String PROPERTY_BLOBSTORE_CONTEXTS = "blobstore.contexts"; - - private Map providerTypeToBlobStoreMap; - private Twitter twitterClient; - private String container; - private Queue queue; - - @Override - public void contextInitialized(ServletContextEvent servletContextEvent) { - Properties props = loadJCloudsProperties(servletContextEvent); - - Module googleModule = new GoogleAppEngineConfigurationModule(); - Set modules = ImmutableSet. of(googleModule); - // shared across all blobstores and used to retrieve tweets - try { - Configuration twitterConf = new ConfigurationBuilder() - .setOAuthConsumerKey(props.getProperty(PROPERTY_TWITTER_CONSUMER_KEY)) - .setOAuthConsumerSecret(props.getProperty(PROPERTY_TWITTER_CONSUMER_SECRET)) - .setOAuthAccessToken(props.getProperty(PROPERTY_TWITTER_ACCESSTOKEN)) - .setOAuthAccessTokenSecret(props.getProperty(PROPERTY_TWITTER_ACCESSTOKEN_SECRET)) - .build(); - twitterClient = new TwitterFactory(twitterConf).getInstance(); - } catch (IllegalArgumentException e) { - throw new IllegalArgumentException("properties for twitter not configured properly in " + props.toString(), e); - } - // common namespace for storing tweets - container = checkNotNull(props.getProperty(PROPERTY_TWEETSTORE_CONTAINER), PROPERTY_TWEETSTORE_CONTAINER); - - // instantiate and store references to all blobstores by provider name - providerTypeToBlobStoreMap = Maps.newHashMap(); - for (String hint : getBlobstoreContexts(props)) { - providerTypeToBlobStoreMap.put(hint, ContextBuilder.newBuilder(hint) - .modules(modules).overrides(props).build(BlobStoreContext.class)); - } - - // get a queue for submitting store tweet requests - queue = QueueFactory.getQueue("twitter"); - - super.contextInitialized(servletContextEvent); - } - - private static Iterable getBlobstoreContexts(Properties props) { - Set contexts = new CredentialsCollector().apply(props).keySet(); - String explicitContexts = props.getProperty(PROPERTY_TWEETSTORE_BLOBSTORES); - if (explicitContexts != null) { - contexts = filter(contexts, in(copyOf(Splitter.on(',').split(explicitContexts)))); - } - checkState(!contexts.isEmpty(), "no credentials available for any requested context"); - return contexts; - } - - private Properties loadJCloudsProperties(ServletContextEvent servletContextEvent) { - InputStream input = servletContextEvent.getServletContext().getResourceAsStream("/WEB-INF/jclouds.properties"); - Properties props = new Properties(); - try { - props.load(input); - } catch (IOException e) { - throw new RuntimeException(e); - } finally { - Closeables.closeQuietly(input); - } - return props; - } - - @Override - protected Injector getInjector() { - return Guice.createInjector(new ServletModule() { - @Override - protected void configureServlets() { - bind(new TypeLiteral>() { - }).toInstance(providerTypeToBlobStoreMap); - bind(Twitter.class).toInstance(twitterClient); - bind(Queue.class).toInstance(queue); - bindConstant().annotatedWith(Names.named(PROPERTY_TWEETSTORE_CONTAINER)).to(container); - serve("/store/*").with(StoreTweetsController.class); - serve("/tweets/*").with(AddTweetsController.class); - serve("/stores/*").with(EnqueueStoresController.class); - serve("/clear/*").with(ClearTweetsController.class); - } - }); - } - - @Override - public void contextDestroyed(ServletContextEvent servletContextEvent) { - for (BlobStoreContext context : providerTypeToBlobStoreMap.values()) { - context.close(); - } - queue.purge(); - super.contextDestroyed(servletContextEvent); - } -} \ No newline at end of file diff --git a/demos/tweetstore/gae-tweetstore/src/main/java/org/jclouds/demo/tweetstore/config/util/CredentialsCollector.java b/demos/tweetstore/gae-tweetstore/src/main/java/org/jclouds/demo/tweetstore/config/util/CredentialsCollector.java deleted file mode 100644 index ce3943376e..0000000000 --- a/demos/tweetstore/gae-tweetstore/src/main/java/org/jclouds/demo/tweetstore/config/util/CredentialsCollector.java +++ /dev/null @@ -1,153 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.config.util; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Preconditions.checkState; -import static com.google.common.base.Predicates.notNull; -import static com.google.common.collect.Collections2.filter; -import static com.google.common.collect.Collections2.transform; -import static com.google.common.collect.ImmutableSet.copyOf; -import static com.google.common.collect.Maps.filterValues; -import static org.jclouds.util.Maps2.fromKeys; - -import java.util.Collection; -import java.util.Map; -import java.util.Properties; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.jclouds.demo.tweetstore.config.util.CredentialsCollector.Credential; - -import com.google.common.annotations.GwtIncompatible; -import com.google.common.base.Function; -import com.google.common.base.Predicate; - -/** - * Reads provider credentials from a {@link Properties} bag. - * - * @author Andrew Phillips - * - */ -public class CredentialsCollector implements Function> { - private static final String IDENTITY_PROPERTY_SUFFIX = ".identity"; - private static final String CREDENTIAL_PROPERTY_SUFFIX = ".credential"; - - // using the identity for provider name extraction - private static final Pattern IDENTITY_PROPERTY_PATTERN = - Pattern.compile("([a-zA-Z0-9-]+)" + Pattern.quote(IDENTITY_PROPERTY_SUFFIX)); - - @Override - public Map apply(final Properties properties) { - Collection providerNames = transform( - filter(properties.stringPropertyNames(), MatchesPattern.matches(IDENTITY_PROPERTY_PATTERN)), - new Function() { - @Override - public String apply(String input) { - Matcher matcher = IDENTITY_PROPERTY_PATTERN.matcher(input); - // as a side-effect, sets the matching group! - checkState(matcher.matches(), "'%s' should match '%s'", input, IDENTITY_PROPERTY_PATTERN); - return matcher.group(1); - } - }); - /* - * Providers without a credential property result in null values, which are - * removed from the returned map. - */ - return filterValues(fromKeys(copyOf(providerNames), new Function() { - @Override - public Credential apply(String providerName) { - String identity = properties.getProperty(providerName + IDENTITY_PROPERTY_SUFFIX); - String credential = properties.getProperty(providerName + CREDENTIAL_PROPERTY_SUFFIX); - return (((identity != null) && (credential != null)) - ? new Credential(identity, credential) - : null); - } - }), notNull()); - } - - public static class Credential { - private final String identity; - private final String credential; - - public Credential(String identity, String credential) { - this.identity = checkNotNull(identity, "identity"); - this.credential = checkNotNull(credential, "credential"); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result - + ((credential == null) ? 0 : credential.hashCode()); - result = prime * result - + ((identity == null) ? 0 : identity.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Credential other = (Credential) obj; - if (credential == null) { - if (other.credential != null) - return false; - } else if (!credential.equals(other.credential)) - return false; - if (identity == null) { - if (other.identity != null) - return false; - } else if (!identity.equals(other.identity)) - return false; - return true; - } - - public String getIdentity() { - return identity; - } - - public String getCredential() { - return credential; - } - } - - @GwtIncompatible(value = "java.util.regex.Pattern") - private static class MatchesPattern implements Predicate { - private final Pattern pattern; - - private MatchesPattern(Pattern pattern) { - this.pattern = pattern; - } - - @Override - public boolean apply(String input) { - return pattern.matcher(input).matches(); - } - - private static MatchesPattern matches(Pattern pattern) { - return new MatchesPattern(pattern); - } - } -} diff --git a/demos/tweetstore/gae-tweetstore/src/main/java/org/jclouds/demo/tweetstore/controller/AddTweetsController.java b/demos/tweetstore/gae-tweetstore/src/main/java/org/jclouds/demo/tweetstore/controller/AddTweetsController.java deleted file mode 100644 index b681cfb27d..0000000000 --- a/demos/tweetstore/gae-tweetstore/src/main/java/org/jclouds/demo/tweetstore/controller/AddTweetsController.java +++ /dev/null @@ -1,96 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.controller; - -import java.io.IOException; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeoutException; - -import javax.annotation.Resource; -import javax.inject.Inject; -import javax.inject.Singleton; -import javax.servlet.RequestDispatcher; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.demo.tweetstore.domain.StoredTweetStatus; -import org.jclouds.demo.tweetstore.functions.ServiceToStoredTweetStatuses; -import org.jclouds.logging.Logger; - -import com.google.appengine.repackaged.com.google.common.collect.Lists; -import com.google.common.base.Function; -import com.google.common.collect.Iterables; - -/** - * Shows an example of how to use @{link BlobStoreContext} injected with Guice. - * - * @author Adrian Cole - */ -@Singleton -public class AddTweetsController extends HttpServlet implements - Function, List> { - - /** The serialVersionUID */ - private static final long serialVersionUID = 3888348023150822683L; - private final Map contexts; - private final ServiceToStoredTweetStatuses blobStoreContextToContainerResult; - - @Resource - protected Logger logger = Logger.NULL; - - @Inject - AddTweetsController(Map contexts, - ServiceToStoredTweetStatuses blobStoreContextToContainerResult) { - this.contexts = contexts; - this.blobStoreContextToContainerResult = blobStoreContextToContainerResult; - } - - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - try { - addMyTweetsToRequest(request); - RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/tweets.jsp"); - dispatcher.forward(request, response); - } catch (Exception e) { - logger.error(e, "Error listing containers"); - throw new ServletException(e); - } - } - - void addMyTweetsToRequest(HttpServletRequest request) throws InterruptedException, - ExecutionException, TimeoutException { - request.setAttribute("tweets", apply(contexts.keySet())); - } - - public List apply(Set in) { - List statuses = Lists.newArrayList(); - for (Iterable list : Iterables.transform(in, - blobStoreContextToContainerResult)) { - Iterables.addAll(statuses, list); - } - return statuses; - } -} diff --git a/demos/tweetstore/gae-tweetstore/src/main/java/org/jclouds/demo/tweetstore/controller/ClearTweetsController.java b/demos/tweetstore/gae-tweetstore/src/main/java/org/jclouds/demo/tweetstore/controller/ClearTweetsController.java deleted file mode 100644 index e08cfbc19e..0000000000 --- a/demos/tweetstore/gae-tweetstore/src/main/java/org/jclouds/demo/tweetstore/controller/ClearTweetsController.java +++ /dev/null @@ -1,96 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.controller; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Strings.nullToEmpty; - -import java.io.IOException; -import java.util.Map; - -import javax.annotation.Resource; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.core.MediaType; - -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.jclouds.logging.Logger; - -import com.google.common.annotations.VisibleForTesting; - -/** - * Grab tweets related to me and store them into blobstores - * - * @author Adrian Cole - */ -@Singleton -public class ClearTweetsController extends HttpServlet { - /** The serialVersionUID */ - private static final long serialVersionUID = 7215420527854203714L; - - private final Map contexts; - private final String container; - - @Resource - protected Logger logger = Logger.NULL; - - @Inject - @VisibleForTesting - public ClearTweetsController(Map contexts, - @Named(TweetStoreConstants.PROPERTY_TWEETSTORE_CONTAINER) String container) { - this.container = container; - this.contexts = contexts; - } - - @VisibleForTesting - public void clearContainer(String contextName) { - BlobStoreContext context = checkNotNull(contexts.get(contextName), - "no context for %s in %s", contextName, contexts.keySet()); - try { - context.getBlobStore().clearContainer(container); - } catch (Exception e) { - logger.error(e, "Error clearing tweets in %s/%s", container, context); - } - } - - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - if (nullToEmpty(request.getHeader("X-Originator")).equals("admin")) { - try { - String contextName = checkNotNull(request.getHeader("context"), "missing header context"); - logger.info("clearing tweets in %s/%s", container, contextName); - clearContainer(contextName); - logger.debug("done clearing tweets"); - response.setContentType(MediaType.TEXT_PLAIN); - response.getWriter().println("Done!"); - } catch (Exception e) { - logger.error(e, "Error clearing tweets"); - throw new ServletException(e); - } - } else { - response.sendError(401); - } - } -} \ No newline at end of file diff --git a/demos/tweetstore/gae-tweetstore/src/main/java/org/jclouds/demo/tweetstore/controller/EnqueueStoresController.java b/demos/tweetstore/gae-tweetstore/src/main/java/org/jclouds/demo/tweetstore/controller/EnqueueStoresController.java deleted file mode 100644 index 94568e4dec..0000000000 --- a/demos/tweetstore/gae-tweetstore/src/main/java/org/jclouds/demo/tweetstore/controller/EnqueueStoresController.java +++ /dev/null @@ -1,92 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.controller; - -import static com.google.appengine.api.taskqueue.TaskOptions.Builder.withUrl; -import static com.google.appengine.repackaged.com.google.common.base.Strings.nullToEmpty; - -import java.io.IOException; -import java.util.Map; -import java.util.Set; - -import javax.annotation.Resource; -import javax.inject.Inject; -import javax.inject.Singleton; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.core.MediaType; - -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.logging.Logger; - -import com.google.appengine.api.taskqueue.Queue; -import com.google.appengine.api.taskqueue.TaskOptions.Method; -import com.google.common.annotations.VisibleForTesting; - -/** - * Adds tasks to retrieve and store tweets in all registered contexts to an async - * task queue. - * - * @author Andrew Phillips - * @see StoreTweetsController - */ -@Singleton -public class EnqueueStoresController extends HttpServlet { - /** The serialVersionUID */ - private static final long serialVersionUID = 7215420527854203714L; - - private final Set contextNames; - private final Queue taskQueue; - - @Resource - protected Logger logger = Logger.NULL; - - @Inject - public EnqueueStoresController(Map contexts, - Queue taskQueue) { - contextNames = contexts.keySet(); - this.taskQueue = taskQueue; - } - - @VisibleForTesting - void enqueueStoreTweetTasks() { - for (String contextName : contextNames) { - logger.debug("enqueuing task to store tweets in blobstore '%s'", contextName); - taskQueue.add(withUrl("/store/do").header("context", contextName).method(Method.GET)); - } - } - - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - if (!nullToEmpty(request.getHeader("X-AppEngine-Cron")).equals("true")) { - response.sendError(401); - } - - try { - enqueueStoreTweetTasks(); - response.setContentType(MediaType.TEXT_PLAIN); - response.getWriter().println("Done!"); - } catch (Exception e) { - logger.error(e, "Error storing tweets"); - throw new ServletException(e); - } - } -} \ No newline at end of file diff --git a/demos/tweetstore/gae-tweetstore/src/main/java/org/jclouds/demo/tweetstore/controller/StoreTweetsController.java b/demos/tweetstore/gae-tweetstore/src/main/java/org/jclouds/demo/tweetstore/controller/StoreTweetsController.java deleted file mode 100644 index ae00c69d20..0000000000 --- a/demos/tweetstore/gae-tweetstore/src/main/java/org/jclouds/demo/tweetstore/controller/StoreTweetsController.java +++ /dev/null @@ -1,129 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.controller; - -import static com.google.common.base.Preconditions.checkNotNull; - -import java.io.IOException; -import java.util.Map; - -import javax.annotation.Resource; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.core.MediaType; - -import org.jclouds.blobstore.BlobMap; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.blobstore.domain.Blob; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.jclouds.logging.Logger; -import org.jclouds.rest.AuthorizationException; - -import twitter4j.Status; -import twitter4j.Twitter; - -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Function; - -/** - * Grab tweets related to me and store them into blobstores - * - * @author Adrian Cole - */ -@Singleton -public class StoreTweetsController extends HttpServlet { - - private static final class StatusToBlob implements Function { - private final BlobMap map; - - private StatusToBlob(BlobMap map) { - this.map = map; - } - - public Blob apply(Status from) { - Blob to = map.blobBuilder().name(from.getId() + "").build(); - to.setPayload(from.getText()); - to.getPayload().getContentMetadata().setContentType(MediaType.TEXT_PLAIN); - to.getMetadata().getUserMetadata().put(TweetStoreConstants.SENDER_NAME, from.getUser().getScreenName()); - return to; - } - } - - /** The serialVersionUID */ - private static final long serialVersionUID = 7215420527854203714L; - - private final Map contexts; - private final Twitter client; - private final String container; - - @Resource - protected Logger logger = Logger.NULL; - - @Inject - @VisibleForTesting - public StoreTweetsController(Map contexts, - @Named(TweetStoreConstants.PROPERTY_TWEETSTORE_CONTAINER) String container, Twitter client) { - this.container = container; - this.contexts = contexts; - this.client = client; - } - - @VisibleForTesting - public void addMyTweets(String contextName, Iterable responseList) { - BlobStoreContext context = checkNotNull(contexts.get(contextName), "no context for " + contextName + " in " - + contexts.keySet()); - BlobMap map = context.createBlobMap(container); - for (Status status : responseList) { - Blob blob = null; - try { - blob = new StatusToBlob(map).apply(status); - map.put(status.getId() + "", blob); - } catch (AuthorizationException e) { - throw e; - } catch (Exception e) { - logger.error(e, "Error storing tweet %s (blob[%s]) on map %s/%s", status.getId(), blob, context, container); - } - } - } - - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - if (request.getHeader("X-AppEngine-QueueName") != null - && request.getHeader("X-AppEngine-QueueName").equals("twitter")) { - try { - String contextName = checkNotNull(request.getHeader("context"), "missing header context"); - logger.info("retrieving tweets"); - addMyTweets(contextName, client.getMentions()); - logger.debug("done storing tweets"); - response.setContentType(MediaType.TEXT_PLAIN); - response.getWriter().println("Done!"); - } catch (Exception e) { - logger.error(e, "Error storing tweets"); - throw new ServletException(e); - } - } else { - response.sendError(401); - } - } -} \ No newline at end of file diff --git a/demos/tweetstore/gae-tweetstore/src/main/java/org/jclouds/demo/tweetstore/domain/StoredTweetStatus.java b/demos/tweetstore/gae-tweetstore/src/main/java/org/jclouds/demo/tweetstore/domain/StoredTweetStatus.java deleted file mode 100644 index 42ad65df01..0000000000 --- a/demos/tweetstore/gae-tweetstore/src/main/java/org/jclouds/demo/tweetstore/domain/StoredTweetStatus.java +++ /dev/null @@ -1,149 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.domain; - -import java.io.Serializable; - -/** - * - * @author Adrian Cole - */ -public class StoredTweetStatus implements Comparable, Serializable { - - /** The serialVersionUID */ - private static final long serialVersionUID = -3257496189689220018L; - private final String service; - private final String host; - private final String container; - private final String id; - private final String from; - private final String tweet; - private final String status; - - @Override - public String toString() { - return "StoredTweetStatus [container=" + container + ", from=" + from + ", host=" + host - + ", id=" + id + ", service=" + service + ", status=" + status + ", tweet=" + tweet - + "]"; - } - - public StoredTweetStatus(String service, String host, String container, String id, String from, - String tweet, String status) { - this.service = service; - this.host = host; - this.container = container; - this.id = id; - this.from = from; - this.tweet = tweet; - this.status = status; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((container == null) ? 0 : container.hashCode()); - result = prime * result + ((from == null) ? 0 : from.hashCode()); - result = prime * result + ((host == null) ? 0 : host.hashCode()); - result = prime * result + ((id == null) ? 0 : id.hashCode()); - result = prime * result + ((service == null) ? 0 : service.hashCode()); - result = prime * result + ((tweet == null) ? 0 : tweet.hashCode()); - return result; - } - - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - StoredTweetStatus other = (StoredTweetStatus) obj; - if (container == null) { - if (other.container != null) - return false; - } else if (!container.equals(other.container)) - return false; - if (from == null) { - if (other.from != null) - return false; - } else if (!from.equals(other.from)) - return false; - if (host == null) { - if (other.host != null) - return false; - } else if (!host.equals(other.host)) - return false; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - if (service == null) { - if (other.service != null) - return false; - } else if (!service.equals(other.service)) - return false; - if (tweet == null) { - if (other.tweet != null) - return false; - } else if (!tweet.equals(other.tweet)) - return false; - return true; - } - - - public String getService() { - return service; - } - - public String getHost() { - return host; - } - - public String getContainer() { - return container; - } - - public String getFrom() { - return from; - } - - public String getTweet() { - return tweet; - } - - public String getStatus() { - return status; - } - - public int compareTo(StoredTweetStatus o) { - if (id == null) - return -1; - return (int) ((this == o) ? 0 : id.compareTo(o.id)); - } - - - public String getId() { - return id; - } - -} diff --git a/demos/tweetstore/gae-tweetstore/src/main/java/org/jclouds/demo/tweetstore/functions/KeyToStoredTweetStatus.java b/demos/tweetstore/gae-tweetstore/src/main/java/org/jclouds/demo/tweetstore/functions/KeyToStoredTweetStatus.java deleted file mode 100644 index f831b9780f..0000000000 --- a/demos/tweetstore/gae-tweetstore/src/main/java/org/jclouds/demo/tweetstore/functions/KeyToStoredTweetStatus.java +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.functions; - -import javax.annotation.Resource; - -import org.jclouds.blobstore.BlobMap; -import org.jclouds.blobstore.domain.Blob; -import org.jclouds.demo.tweetstore.domain.StoredTweetStatus; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.jclouds.logging.Logger; -import org.jclouds.util.Strings2; - -import com.google.common.base.Function; - -/** - * - * @author Adrian Cole - */ -public class KeyToStoredTweetStatus implements Function { - private final String host; - private final BlobMap map; - private final String service; - private final String container; - - @Resource - protected Logger logger = Logger.NULL; - - KeyToStoredTweetStatus(BlobMap map, String service, String host, String container) { - this.host = host; - this.map = map; - this.service = service; - this.container = container; - } - - public StoredTweetStatus apply(String id) { - String status; - String from; - String tweet; - try { - long start = System.currentTimeMillis(); - Blob blob = map.get(id); - status = ((System.currentTimeMillis() - start) + "ms"); - from = blob.getMetadata().getUserMetadata().get(TweetStoreConstants.SENDER_NAME); - tweet = Strings2.toString(blob.getPayload()); - } catch (Exception e) { - logger.error(e, "Error listing container %s//%s/%s", service, container, id); - status = (e.getMessage()); - tweet = ""; - from = ""; - } - return new StoredTweetStatus(service, host, container, id, from, tweet, status); - } -} diff --git a/demos/tweetstore/gae-tweetstore/src/main/java/org/jclouds/demo/tweetstore/functions/ServiceToStoredTweetStatuses.java b/demos/tweetstore/gae-tweetstore/src/main/java/org/jclouds/demo/tweetstore/functions/ServiceToStoredTweetStatuses.java deleted file mode 100644 index 165c1fc3e4..0000000000 --- a/demos/tweetstore/gae-tweetstore/src/main/java/org/jclouds/demo/tweetstore/functions/ServiceToStoredTweetStatuses.java +++ /dev/null @@ -1,74 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.functions; - -import java.net.URI; -import java.util.Collections; -import java.util.Map; -import java.util.Set; - -import javax.annotation.Resource; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - -import org.jclouds.Context; -import org.jclouds.blobstore.BlobMap; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.demo.tweetstore.domain.StoredTweetStatus; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.jclouds.logging.Logger; - -import com.google.common.base.Function; -import com.google.common.collect.Iterables; - -@Singleton -public class ServiceToStoredTweetStatuses implements Function> { - - private final Map contexts; - private final String container; - - @Inject - public ServiceToStoredTweetStatuses(Map contexts, - @Named(TweetStoreConstants.PROPERTY_TWEETSTORE_CONTAINER) String container) { - this.contexts = contexts; - this.container = container; - } - - @Resource - protected Logger logger = Logger.NULL; - - public Iterable apply(String service) { - BlobStoreContext context = contexts.get(service); - String host = URI.create(context.unwrap(Context.class).getProviderMetadata() - .getEndpoint()).getHost(); - try { - BlobMap blobMap = context.createBlobMap(container); - Set blobs = blobMap.keySet(); - return Iterables.transform(blobs, new KeyToStoredTweetStatus(blobMap, service, host, - container)); - } catch (Exception e) { - StoredTweetStatus result = new StoredTweetStatus(service, host, container, null, null, - null, e.getMessage()); - logger.error(e, "Error listing service %s", service); - return Collections.singletonList(result); - } - - } -} \ No newline at end of file diff --git a/demos/tweetstore/gae-tweetstore/src/main/java/org/jclouds/demo/tweetstore/reference/TwitterConstants.java b/demos/tweetstore/gae-tweetstore/src/main/java/org/jclouds/demo/tweetstore/reference/TwitterConstants.java deleted file mode 100644 index dc8b97915f..0000000000 --- a/demos/tweetstore/gae-tweetstore/src/main/java/org/jclouds/demo/tweetstore/reference/TwitterConstants.java +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.reference; - -/** - * Configuration properties and constants used in Twitter connections. - * - * @author Andrew Phillips - */ -public interface TwitterConstants { - static final String PROPERTY_TWITTER_CONSUMER_KEY = "twitter.consumer.identity"; - static final String PROPERTY_TWITTER_CONSUMER_SECRET = "twitter.consumer.credential"; - static final String PROPERTY_TWITTER_ACCESSTOKEN = "twitter.access.identity"; - static final String PROPERTY_TWITTER_ACCESSTOKEN_SECRET = "twitter.access.credential"; -} diff --git a/demos/tweetstore/gae-tweetstore/src/main/platform/appengine-web.xml b/demos/tweetstore/gae-tweetstore/src/main/platform/appengine-web.xml deleted file mode 100644 index 32d6d68a44..0000000000 --- a/demos/tweetstore/gae-tweetstore/src/main/platform/appengine-web.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - ${appengine.applicationid} - 1 - - - - diff --git a/demos/tweetstore/gae-tweetstore/src/main/platform/cron.xml b/demos/tweetstore/gae-tweetstore/src/main/platform/cron.xml deleted file mode 100644 index 193a5402f6..0000000000 --- a/demos/tweetstore/gae-tweetstore/src/main/platform/cron.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - /stores/do - Enqueue 'store tweet' tasks for all contexts - every 10 minutes - - \ No newline at end of file diff --git a/demos/tweetstore/gae-tweetstore/src/main/platform/logging.properties b/demos/tweetstore/gae-tweetstore/src/main/platform/logging.properties deleted file mode 100644 index 122734b647..0000000000 --- a/demos/tweetstore/gae-tweetstore/src/main/platform/logging.properties +++ /dev/null @@ -1,37 +0,0 @@ -# -# Licensed to jclouds, Inc. (jclouds) under one or more -# contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. jclouds licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# - -# Set the default logging level for all loggers to WARNING -.level = INFO - -# Set the default logging level for ORM, specifically, to WARNING -org.jclouds.level=INFO -DataNucleus.JDO.level=WARNING -DataNucleus.Persistence.level=WARNING -DataNucleus.Cache.level=WARNING -DataNucleus.MetaData.level=WARNING -DataNucleus.General.level=WARNING -DataNucleus.Utility.level=WARNING -DataNucleus.Transaction.level=WARNING -DataNucleus.Datastore.level=WARNING -DataNucleus.ClassLoading.level=WARNING -DataNucleus.Plugin.level=WARNING -DataNucleus.ValueGeneration.level=WARNING -DataNucleus.Enhancer.level=WARNING -DataNucleus.SchemaTool.level=WARNING diff --git a/demos/tweetstore/gae-tweetstore/src/main/webapp/WEB-INF/queue.xml b/demos/tweetstore/gae-tweetstore/src/main/webapp/WEB-INF/queue.xml deleted file mode 100644 index 1bc53f398d..0000000000 --- a/demos/tweetstore/gae-tweetstore/src/main/webapp/WEB-INF/queue.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - twitter - - 2/m - 1 - - diff --git a/demos/tweetstore/gae-tweetstore/src/main/webapp/WEB-INF/web.xml b/demos/tweetstore/gae-tweetstore/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index d5b17d7512..0000000000 --- a/demos/tweetstore/gae-tweetstore/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,57 +0,0 @@ - - - - jclouds-tweetstore - - - - guiceFilter - com.google.inject.servlet.GuiceFilter - - - - guiceFilter - /* - - - - org.jclouds.demo.tweetstore.config.GuiceServletConfig - - - - - - - /stores/* - - - admin - - - - - index.jsp - - - \ No newline at end of file diff --git a/demos/tweetstore/gae-tweetstore/src/main/webapp/index.jsp b/demos/tweetstore/gae-tweetstore/src/main/webapp/index.jsp deleted file mode 100644 index fd71a31164..0000000000 --- a/demos/tweetstore/gae-tweetstore/src/main/webapp/index.jsp +++ /dev/null @@ -1,31 +0,0 @@ -<%-- - - Licensed to jclouds, Inc. (jclouds) under one or more - contributor license agreements. See the NOTICE file - distributed with this work for additional information - regarding copyright ownership. jclouds licenses this file - to you under the Apache License, Version 2.0 (the - "License"); you may not use this file except in compliance - with the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, - software distributed under the License is distributed on an - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - KIND, either express or implied. See the License for the - specific language governing permissions and limitations - under the License. - ---%> - - -jclouds: anyweight cloudware for java - - -

Welcome!

-

Click here to see tweets about jclouds.

-

- - diff --git a/demos/tweetstore/gae-tweetstore/src/main/webapp/tweets.jsp b/demos/tweetstore/gae-tweetstore/src/main/webapp/tweets.jsp deleted file mode 100644 index cbdabde732..0000000000 --- a/demos/tweetstore/gae-tweetstore/src/main/webapp/tweets.jsp +++ /dev/null @@ -1,109 +0,0 @@ -<%-- - - Licensed to jclouds, Inc. (jclouds) under one or more - contributor license agreements. See the NOTICE file - distributed with this work for additional information - regarding copyright ownership. jclouds licenses this file - to you under the Apache License, Version 2.0 (the - "License"); you may not use this file except in compliance - with the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, - software distributed under the License is distributed on an - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - KIND, either express or implied. See the License for the - specific language governing permissions and limitations - under the License. - ---%> -<%@ page buffer="20kb"%> -<%@ taglib uri="http://displaytag.sf.net" prefix="display"%> - - -jclouds: anyweight cloudware for java - - - -

Tweets in Clouds

- - - - - - - -
-
- - - - - - - - -
-
- - diff --git a/demos/tweetstore/gae-tweetstore/src/test/java/org/jclouds/demo/tweetstore/config/util/CredentialsCollectorTest.java b/demos/tweetstore/gae-tweetstore/src/test/java/org/jclouds/demo/tweetstore/config/util/CredentialsCollectorTest.java deleted file mode 100644 index 031bb199fc..0000000000 --- a/demos/tweetstore/gae-tweetstore/src/test/java/org/jclouds/demo/tweetstore/config/util/CredentialsCollectorTest.java +++ /dev/null @@ -1,82 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.config.util; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; - -import java.util.Map; -import java.util.Properties; - -import org.jclouds.demo.tweetstore.config.util.CredentialsCollector; -import org.jclouds.demo.tweetstore.config.util.CredentialsCollector.Credential; -import org.testng.annotations.Test; - -import com.google.common.collect.ImmutableMap; - -/** - * Tests behavior of {@code CredentialsCollector} - * - * @author Andrew Phillips - */ -@Test(groups = "unit") -public class CredentialsCollectorTest { - private CredentialsCollector collector = new CredentialsCollector(); - - public void testEmptyProperties() { - assertTrue(collector.apply(new Properties()).isEmpty(), - "Expected returned map to be empty"); - } - - public void testNoCredentials() { - Properties properties = propertiesOf(ImmutableMap.of("not-an-identity", - "v1", "not-a-credential", "v2")); - assertTrue(collector.apply(properties).isEmpty(), - "Expected returned map to be empty"); - } - - private static Properties propertiesOf(Map entries) { - Properties properties = new Properties(); - properties.putAll(entries); - return properties; - } - - public void testNonMatchingCredentials() { - Properties properties = propertiesOf(ImmutableMap.of("non_matching.identity", "v1", - "non_matching.credential", "v2")); - assertTrue(collector.apply(properties).isEmpty(), - "Expected returned map to be empty"); - } - - public void testIncompleteCredentials() { - Properties properties = propertiesOf(ImmutableMap.of("acme.identity", "v1", - "acme-2.credential", "v2")); - assertTrue(collector.apply(properties).isEmpty(), - "Expected returned map to be empty"); - } - - public void testCredentials() { - Properties properties = propertiesOf(ImmutableMap.of("acme.identity", "v1", - "acme.credential", "v2", "acme-2.identity", "v3", - "acme-2.credential", "v4")); - assertEquals(collector.apply(properties), - ImmutableMap.of("acme", new Credential("v1", "v2"), - "acme-2", new Credential("v3", "v4"))); - } -} \ No newline at end of file diff --git a/demos/tweetstore/gae-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/AddTweetsControllerTest.java b/demos/tweetstore/gae-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/AddTweetsControllerTest.java deleted file mode 100644 index 1c93403650..0000000000 --- a/demos/tweetstore/gae-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/AddTweetsControllerTest.java +++ /dev/null @@ -1,78 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.controller; - -import static org.testng.Assert.assertEquals; - -import java.io.IOException; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ExecutionException; - -import org.jclouds.ContextBuilder; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.blobstore.TransientApiMetadata; -import org.jclouds.blobstore.domain.Blob; -import org.jclouds.demo.tweetstore.domain.StoredTweetStatus; -import org.jclouds.demo.tweetstore.functions.ServiceToStoredTweetStatuses; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.testng.annotations.Test; -import org.testng.collections.Maps; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableSet; - -/** - * Tests behavior of {@code AddTweetsController} - * - * @author Adrian Cole - */ -@Test(groups = "unit") -public class AddTweetsControllerTest { - - Map createServices(String container) throws InterruptedException, - ExecutionException { - Map services = Maps.newHashMap(); - TransientApiMetadata transientApiMetadata = TransientApiMetadata.builder().build(); - for (String name : new String[] { "1", "2" }) { - BlobStoreContext context = ContextBuilder.newBuilder(transientApiMetadata).build(BlobStoreContext.class); - context.getAsyncBlobStore().createContainerInLocation(null, container).get(); - Blob blob = context.getAsyncBlobStore().blobBuilder("1").build(); - blob.getMetadata().getUserMetadata().put(TweetStoreConstants.SENDER_NAME, "frank"); - blob.setPayload("I love beans!"); - context.getAsyncBlobStore().putBlob(container, blob).get(); - services.put(name, context); - } - return services; - } - - public void testStoreTweets() throws IOException, InterruptedException, ExecutionException { - String container = "container"; - Map contexts = createServices(container); - - ServiceToStoredTweetStatuses function = new ServiceToStoredTweetStatuses(contexts, container); - AddTweetsController controller = new AddTweetsController(contexts, function); - List list = controller.apply(ImmutableSet.of("1", "2")); - assertEquals(list.size(), 2); - assertEquals(list, ImmutableList.of(new StoredTweetStatus("1", "localhost", container, "1", - "frank", "I love beans!", null), new StoredTweetStatus("2", "localhost", container, - "1", "frank", "I love beans!", null))); - - } -} diff --git a/demos/tweetstore/gae-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/ClearTweetsControllerTest.java b/demos/tweetstore/gae-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/ClearTweetsControllerTest.java deleted file mode 100644 index 81f0b9f3c7..0000000000 --- a/demos/tweetstore/gae-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/ClearTweetsControllerTest.java +++ /dev/null @@ -1,72 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.controller; - -import static org.testng.Assert.assertEquals; - -import java.io.IOException; -import java.util.Map; -import java.util.concurrent.ExecutionException; - -import org.jclouds.ContextBuilder; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.blobstore.TransientApiMetadata; -import org.jclouds.blobstore.domain.Blob; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.testng.annotations.Test; - -import com.google.common.collect.ImmutableMap; - -/** - * Tests behavior of {@code AddTweetsController} - * - * @author Adrian Cole - */ -@Test(groups = "unit") -public class ClearTweetsControllerTest { - - Map createBlobStores(String container) throws InterruptedException, ExecutionException { - TransientApiMetadata transientApiMetadata = TransientApiMetadata.builder().build(); - Map contexts = ImmutableMap.of( - "test1", ContextBuilder.newBuilder(transientApiMetadata).build(BlobStoreContext.class), - "test2", ContextBuilder.newBuilder(transientApiMetadata).build(BlobStoreContext.class)); - for (BlobStoreContext blobstore : contexts.values()) { - blobstore.getBlobStore().createContainerInLocation(null, container); - Blob blob = blobstore.getAsyncBlobStore().blobBuilder("1").build(); - blob.getMetadata().getUserMetadata().put(TweetStoreConstants.SENDER_NAME, "frank"); - blob.setPayload("I love beans!"); - blobstore.getBlobStore().putBlob(container, blob); - } - return contexts; - } - - public void testClearTweets() throws IOException, InterruptedException, ExecutionException { - String container = ClearTweetsControllerTest.class.getName() + "#container"; - Map contexts = createBlobStores(container); - - ClearTweetsController controller = new ClearTweetsController(contexts, - container); - controller.clearContainer("test1"); - controller.clearContainer("test2"); - - for (BlobStoreContext context : contexts.values()) { - assertEquals(context.getBlobStore().countBlobs(container), 0, context.toString()); - } - } -} diff --git a/demos/tweetstore/gae-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/EnqueueStoresControllerTest.java b/demos/tweetstore/gae-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/EnqueueStoresControllerTest.java deleted file mode 100644 index 5190718e4c..0000000000 --- a/demos/tweetstore/gae-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/EnqueueStoresControllerTest.java +++ /dev/null @@ -1,67 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.controller; - -import static com.google.appengine.api.taskqueue.TaskOptions.Builder.withUrl; -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.verify; - -import java.util.Map; - -import org.jclouds.ContextBuilder; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.blobstore.TransientApiMetadata; -import org.testng.annotations.Test; - -import com.google.appengine.api.taskqueue.Queue; -import com.google.appengine.api.taskqueue.TaskOptions.Method; -import com.google.common.collect.ImmutableMap; - -/** - * Tests behavior of {@link EnqueueStoresController} - * - * @author Andrew Phillips - */ -@Test(groups = "unit") -public class EnqueueStoresControllerTest { - - Map createBlobStores() { - TransientApiMetadata transientApiMetadata = TransientApiMetadata.builder().build(); - Map contexts = ImmutableMap.of( - "test1", ContextBuilder.newBuilder(transientApiMetadata).build(BlobStoreContext.class), - "test2", ContextBuilder.newBuilder(transientApiMetadata).build(BlobStoreContext.class)); - return contexts; - } - - public void testEnqueueStores() { - Map stores = createBlobStores(); - Queue taskQueue = createMock(Queue.class); - EnqueueStoresController function = new EnqueueStoresController(stores, taskQueue); - - expect(taskQueue.add(withUrl("/store/do").header("context", "test1").method(Method.GET))).andReturn(null); - expect(taskQueue.add(withUrl("/store/do").header("context", "test2").method(Method.GET))).andReturn(null); - replay(taskQueue); - - function.enqueueStoreTweetTasks(); - - verify(taskQueue); - } -} diff --git a/demos/tweetstore/gae-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/StoreTweetsControllerTest.java b/demos/tweetstore/gae-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/StoreTweetsControllerTest.java deleted file mode 100644 index 0976307732..0000000000 --- a/demos/tweetstore/gae-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/StoreTweetsControllerTest.java +++ /dev/null @@ -1,120 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.controller; - -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.verify; -import static org.testng.Assert.assertEquals; - -import java.io.IOException; -import java.util.Map; -import java.util.Map.Entry; -import java.util.concurrent.ExecutionException; - -import org.jclouds.ContextBuilder; -import org.jclouds.blobstore.BlobMap; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.blobstore.TransientApiMetadata; -import org.jclouds.blobstore.domain.Blob; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.jclouds.util.Strings2; -import org.testng.annotations.Test; - -import twitter4j.Status; -import twitter4j.Twitter; -import twitter4j.User; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; - -/** - * Tests behavior of {@code StoreTweetsController} - * - * @author Adrian Cole - */ -@Test(groups = "unit") -public class StoreTweetsControllerTest { - - Twitter createTwitter() { - return createMock(Twitter.class); - } - - Map createBlobStores() throws InterruptedException, ExecutionException { - TransientApiMetadata transientApiMetadata = TransientApiMetadata.builder().build(); - Map contexts = ImmutableMap.of( - "test1", ContextBuilder.newBuilder(transientApiMetadata).build(BlobStoreContext.class), - "test2", ContextBuilder.newBuilder(transientApiMetadata).build(BlobStoreContext.class)); - for (BlobStoreContext blobstore : contexts.values()) { - blobstore.getAsyncBlobStore().createContainerInLocation(null, "favo").get(); - } - return contexts; - } - - public void testStoreTweets() throws IOException, InterruptedException, ExecutionException { - Map stores = createBlobStores(); - StoreTweetsController function = new StoreTweetsController(stores, "favo", createTwitter()); - - User frank = createMock(User.class); - expect(frank.getScreenName()).andReturn("frank").atLeastOnce(); - - Status frankStatus = createMock(Status.class); - expect(frankStatus.getId()).andReturn(1l).atLeastOnce(); - expect(frankStatus.getUser()).andReturn(frank).atLeastOnce(); - expect(frankStatus.getText()).andReturn("I love beans!").atLeastOnce(); - - User jimmy = createMock(User.class); - expect(jimmy.getScreenName()).andReturn("jimmy").atLeastOnce(); - - Status jimmyStatus = createMock(Status.class); - expect(jimmyStatus.getId()).andReturn(2l).atLeastOnce(); - expect(jimmyStatus.getUser()).andReturn(jimmy).atLeastOnce(); - expect(jimmyStatus.getText()).andReturn("cloud is king").atLeastOnce(); - - replay(frank); - replay(frankStatus); - replay(jimmy); - replay(jimmyStatus); - - function.addMyTweets("test1", ImmutableList.of(frankStatus, jimmyStatus)); - function.addMyTweets("test2", ImmutableList.of(frankStatus, jimmyStatus)); - - verify(frank); - verify(frankStatus); - verify(jimmy); - verify(jimmyStatus); - - for (Entry entry : stores.entrySet()) { - BlobMap map = entry.getValue().createBlobMap("favo"); - Blob frankBlob = map.get("1"); - assertEquals(frankBlob.getMetadata().getName(), "1"); - assertEquals(frankBlob.getMetadata().getUserMetadata().get(TweetStoreConstants.SENDER_NAME), "frank"); - assertEquals(frankBlob.getMetadata().getContentMetadata().getContentType(), "text/plain"); - assertEquals(Strings2.toString(frankBlob.getPayload()), "I love beans!"); - - Blob jimmyBlob = map.get("2"); - assertEquals(jimmyBlob.getMetadata().getName(), "2"); - assertEquals(jimmyBlob.getMetadata().getUserMetadata().get(TweetStoreConstants.SENDER_NAME), "jimmy"); - assertEquals(jimmyBlob.getMetadata().getContentMetadata().getContentType(), "text/plain"); - assertEquals(Strings2.toString(jimmyBlob.getPayload()), "cloud is king"); - } - - } -} diff --git a/demos/tweetstore/gae-tweetstore/src/test/java/org/jclouds/demo/tweetstore/functions/KeyToStoredTweetStatusTest.java b/demos/tweetstore/gae-tweetstore/src/test/java/org/jclouds/demo/tweetstore/functions/KeyToStoredTweetStatusTest.java deleted file mode 100644 index 2667a87fd2..0000000000 --- a/demos/tweetstore/gae-tweetstore/src/test/java/org/jclouds/demo/tweetstore/functions/KeyToStoredTweetStatusTest.java +++ /dev/null @@ -1,69 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.functions; - -import static org.testng.Assert.assertEquals; - -import java.io.IOException; -import java.util.concurrent.ExecutionException; - -import org.jclouds.ContextBuilder; -import org.jclouds.blobstore.BlobMap; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.blobstore.TransientApiMetadata; -import org.jclouds.blobstore.domain.Blob; -import org.jclouds.demo.tweetstore.domain.StoredTweetStatus; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.testng.annotations.Test; - -/** - * Tests behavior of {@code KeyToStoredTweetStatus} - * - * @author Adrian Cole - */ -@Test(groups = "unit") -public class KeyToStoredTweetStatusTest { - - BlobMap createMap() throws InterruptedException, ExecutionException { - BlobStoreContext context = - ContextBuilder.newBuilder(TransientApiMetadata.builder().build()).build(BlobStoreContext.class); - context.getBlobStore().createContainerInLocation(null, "test1"); - return context.createBlobMap("test1"); - } - - public void testStoreTweets() throws IOException, InterruptedException, ExecutionException { - BlobMap map = createMap(); - Blob blob = map.blobBuilder().name("1").build(); - blob.getMetadata().getUserMetadata().put(TweetStoreConstants.SENDER_NAME, "frank"); - blob.setPayload("I love beans!"); - map.put("1", blob); - String host = "localhost"; - String service = "stub"; - String container = "tweetstore"; - - KeyToStoredTweetStatus function = new KeyToStoredTweetStatus(map, service, host, container); - StoredTweetStatus result = function.apply("1"); - - StoredTweetStatus expected = new StoredTweetStatus(service, host, container, "1", "frank", - "I love beans!", null); - - assertEquals(result, expected); - - } -} diff --git a/demos/tweetstore/gae-tweetstore/src/test/java/org/jclouds/demo/tweetstore/functions/ServiceToStoredTweetStatusesTest.java b/demos/tweetstore/gae-tweetstore/src/test/java/org/jclouds/demo/tweetstore/functions/ServiceToStoredTweetStatusesTest.java deleted file mode 100644 index 6bce7f8e8e..0000000000 --- a/demos/tweetstore/gae-tweetstore/src/test/java/org/jclouds/demo/tweetstore/functions/ServiceToStoredTweetStatusesTest.java +++ /dev/null @@ -1,76 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.functions; - -import static org.testng.Assert.assertEquals; - -import java.io.IOException; -import java.util.Map; -import java.util.concurrent.ExecutionException; - -import org.jclouds.ContextBuilder; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.blobstore.TransientApiMetadata; -import org.jclouds.blobstore.domain.Blob; -import org.jclouds.demo.tweetstore.domain.StoredTweetStatus; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.testng.annotations.Test; -import org.testng.collections.Maps; - -import com.google.common.collect.Iterables; - -/** - * Tests behavior of {@code ServiceToStoredTweetStatuses} - * - * @author Adrian Cole - */ -@Test(groups = "unit") -public class ServiceToStoredTweetStatusesTest { - - Map createServices(String container) throws InterruptedException, - ExecutionException { - Map services = Maps.newHashMap(); - TransientApiMetadata transientApiMetadata = TransientApiMetadata.builder().build(); - for (String name : new String[] { "1", "2" }) { - BlobStoreContext context = - ContextBuilder.newBuilder(transientApiMetadata).build(BlobStoreContext.class); - context.getAsyncBlobStore().createContainerInLocation(null, container).get(); - Blob blob = context.getAsyncBlobStore().blobBuilder("1").build(); - blob.getMetadata().getUserMetadata().put(TweetStoreConstants.SENDER_NAME, "frank"); - blob.setPayload("I love beans!"); - context.getAsyncBlobStore().putBlob(container, blob).get(); - services.put(name, context); - } - return services; - } - - public void testStoreTweets() throws IOException, InterruptedException, ExecutionException { - String container = "container"; - Map contexts = createServices(container); - - ServiceToStoredTweetStatuses function = new ServiceToStoredTweetStatuses(contexts, container); - - assertEquals(Iterables.getLast(function.apply("1")), new StoredTweetStatus("1", "localhost", - container, "1", "frank", "I love beans!", null)); - - assertEquals(Iterables.getLast(function.apply("2")), new StoredTweetStatus("2", "localhost", - container, "1", "frank", "I love beans!", null)); - - } -} diff --git a/demos/tweetstore/gae-tweetstore/src/test/java/org/jclouds/demo/tweetstore/integration/GoogleDevServer.java b/demos/tweetstore/gae-tweetstore/src/test/java/org/jclouds/demo/tweetstore/integration/GoogleDevServer.java deleted file mode 100644 index 63223607ac..0000000000 --- a/demos/tweetstore/gae-tweetstore/src/test/java/org/jclouds/demo/tweetstore/integration/GoogleDevServer.java +++ /dev/null @@ -1,87 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.integration; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.io.Closeables.closeQuietly; -import static java.lang.String.format; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Properties; -import java.util.concurrent.TimeUnit; - -import com.google.appengine.tools.KickStart; -import com.google.appengine.tools.info.SdkInfo; - -/** - * Basic functionality to start a local google app engine instance. - * - * @author Adrian Cole - */ -public class GoogleDevServer { - - Thread server; - - public void writePropertiesAndStartServer(final String address, - final String port, final String warfile, Properties props) - throws IOException, InterruptedException { - String filename = String.format( - "%1$s/WEB-INF/jclouds.properties", warfile); - System.err.println("file: " + filename); - storeProperties(filename, props); - assert new File(filename).exists(); - this.server = new Thread(new Runnable() { - public void run() { - String sdkRoot = checkNotNull(System.getProperty(SdkInfo.SDK_ROOT_PROPERTY), SdkInfo.SDK_ROOT_PROPERTY); - KickStart.main(new String[] { - KickStarter.systemProperty("java.util.logging.config.file", - format("%s/WEB-INF/logging.properties", warfile)), - KickStarter.systemProperty(SdkInfo.SDK_ROOT_PROPERTY, sdkRoot), - "com.google.appengine.tools.development.DevAppServerMain", - "--disable_update_check", - format("--sdk_root=%s", sdkRoot), - "-a", address, "-p", port, warfile }); - } - }); - server.start(); - TimeUnit.SECONDS.sleep(30); - } - - private static void storeProperties(String filename, Properties props) throws IOException { - FileOutputStream targetFile = new FileOutputStream(filename); - try { - props.store(targetFile, "test"); - } finally { - closeQuietly(targetFile); - } - } - - public void stop() throws Exception { - // KickStart.main opens a process and calls process.waitFor(), which is interruptable - server.interrupt(); - } - - private static class KickStarter { - private static String systemProperty(String key, String value) { - return format("--jvm_flag=-D%s=%s", key, value); - } - } -} \ No newline at end of file diff --git a/demos/tweetstore/gae-tweetstore/src/test/java/org/jclouds/demo/tweetstore/integration/TweetStoreLiveTest.java b/demos/tweetstore/gae-tweetstore/src/test/java/org/jclouds/demo/tweetstore/integration/TweetStoreLiveTest.java deleted file mode 100644 index 3265e752e9..0000000000 --- a/demos/tweetstore/gae-tweetstore/src/test/java/org/jclouds/demo/tweetstore/integration/TweetStoreLiveTest.java +++ /dev/null @@ -1,239 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.integration; - -import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.demo.tweetstore.reference.TweetStoreConstants.PROPERTY_TWEETSTORE_BLOBSTORES; -import static org.jclouds.demo.tweetstore.reference.TweetStoreConstants.PROPERTY_TWEETSTORE_CONTAINER; -import static org.jclouds.demo.tweetstore.reference.TwitterConstants.PROPERTY_TWITTER_ACCESSTOKEN; -import static org.jclouds.demo.tweetstore.reference.TwitterConstants.PROPERTY_TWITTER_ACCESSTOKEN_SECRET; -import static org.jclouds.demo.tweetstore.reference.TwitterConstants.PROPERTY_TWITTER_CONSUMER_KEY; -import static org.jclouds.demo.tweetstore.reference.TwitterConstants.PROPERTY_TWITTER_CONSUMER_SECRET; - -import java.io.IOException; -import java.io.InputStream; -import java.net.HttpURLConnection; -import java.net.URL; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Properties; -import java.util.Set; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeoutException; - -import org.jclouds.Context; -import org.jclouds.ContextBuilder; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.demo.tweetstore.config.GuiceServletConfig; -import org.jclouds.demo.tweetstore.controller.StoreTweetsController; -import org.jclouds.logging.log4j.config.Log4JLoggingModule; -import org.jclouds.rest.AuthorizationException; -import org.jclouds.util.Strings2; -import org.testng.annotations.AfterTest; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.Parameters; -import org.testng.annotations.Test; - -import twitter4j.ResponseList; -import twitter4j.Status; -import twitter4j.Twitter; -import twitter4j.TwitterException; -import twitter4j.TwitterFactory; -import twitter4j.conf.Configuration; -import twitter4j.conf.ConfigurationBuilder; - -import com.google.common.base.Joiner; -import com.google.common.base.Splitter; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Maps; -import com.google.inject.Module; - -/** - * Starts up the Google App Engine for Java Development environment and deploys an application which - * tests accesses twitter and blobstores. - * - * @author Adrian Cole - */ -@Test(groups = "live", singleThreaded = true) -public class TweetStoreLiveTest { - GoogleDevServer server; - private URL url; - private Map contexts; - private String container; - private static final Iterable blobstores = - Splitter.on(',').split(System.getProperty(PROPERTY_TWEETSTORE_BLOBSTORES, - "cloudfiles-us,aws-s3,azureblob")); - private static final Properties props = new Properties(); - - @BeforeTest - void clearAndCreateContainers() throws InterruptedException, ExecutionException, TimeoutException, IOException, - TwitterException { - container = getRequiredSystemProperty(PROPERTY_TWEETSTORE_CONTAINER); - - props.setProperty(PROPERTY_TWEETSTORE_CONTAINER, container); - props.setProperty(GuiceServletConfig.PROPERTY_BLOBSTORE_CONTEXTS, Joiner.on(',').join(blobstores)); - - // put all identity/credential pairs into the client - addCredentialsForBlobStores(props); - - // example of an ad-hoc client configuration - addConfigurationForTwitter(props); - - // for testing, capture logs. - final Set wiring = ImmutableSet. of(new Log4JLoggingModule()); - this.contexts = Maps.newConcurrentMap(); - - for (String provider : blobstores) { - contexts.put(provider, ContextBuilder.newBuilder(provider) - .modules(wiring).overrides(props).build(BlobStoreContext.class)); - } - - Configuration conf = new ConfigurationBuilder() - .setOAuthConsumerKey(props.getProperty(PROPERTY_TWITTER_CONSUMER_KEY)) - .setOAuthConsumerSecret(props.getProperty(PROPERTY_TWITTER_CONSUMER_SECRET)) - .setOAuthAccessToken(props.getProperty(PROPERTY_TWITTER_ACCESSTOKEN)) - .setOAuthAccessTokenSecret(props.getProperty(PROPERTY_TWITTER_ACCESSTOKEN_SECRET)) - .build(); - Twitter client = new TwitterFactory(conf).getInstance(); - StoreTweetsController controller = new StoreTweetsController(contexts, container, client); - - ResponseList statuses = client.getMentions(); - - boolean deleted = false; - for (BlobStoreContext context : contexts.values()) { - try { - if (context.getBlobStore().containerExists(container)) { - System.err.printf("deleting container %s at %s%n", container, - context.unwrap(Context.class).getProviderMetadata().getEndpoint()); - context.getBlobStore().deleteContainer(container); - deleted = true; - } - } catch (AuthorizationException e) { - throw new AuthorizationException("for context: " + context, e); - } - } - if (deleted) { - System.err.println("sleeping 60 seconds to allow containers to clear"); - Thread.sleep(60000); - } - for (BlobStoreContext context : contexts.values()) { - System.err.printf("creating container %s at %s%n", container, - context.unwrap(Context.class).getProviderMetadata().getEndpoint()); - context.getBlobStore().createContainerInLocation(null, container); - } - - if (deleted) { - System.err.println("sleeping 5 seconds to allow containers to create"); - Thread.sleep(5000); - } - - for (Entry entry : contexts.entrySet()) { - System.err.printf("filling container %s at %s%n", container, entry.getKey()); - controller.addMyTweets(entry.getKey(), statuses); - } - } - - private static String getRequiredSystemProperty(String key) { - return checkNotNull(System.getProperty(key), key); - } - - private void addConfigurationForTwitter(Properties props) { - props.setProperty(PROPERTY_TWITTER_CONSUMER_KEY, - getRequiredSystemProperty("test." + PROPERTY_TWITTER_CONSUMER_KEY)); - props.setProperty(PROPERTY_TWITTER_CONSUMER_SECRET, - getRequiredSystemProperty("test." + PROPERTY_TWITTER_CONSUMER_SECRET)); - props.setProperty(PROPERTY_TWITTER_ACCESSTOKEN, - getRequiredSystemProperty("test." + PROPERTY_TWITTER_ACCESSTOKEN)); - props.setProperty(PROPERTY_TWITTER_ACCESSTOKEN_SECRET, - getRequiredSystemProperty("test." + PROPERTY_TWITTER_ACCESSTOKEN_SECRET)); - } - - private void addCredentialsForBlobStores(Properties props) { - for (String provider : blobstores) { - props.setProperty(provider + ".identity", - getRequiredSystemProperty("test." + provider + ".identity")); - props.setProperty(provider + ".credential", - getRequiredSystemProperty("test." + provider + ".credential")); - } - } - - @BeforeTest(dependsOnMethods = "clearAndCreateContainers") - @Parameters({ "warfile", "devappserver.address", "devappserver.port" }) - public void startDevAppServer(final String warfile, final String address, final String port) throws Exception { - url = new URL(String.format("http://%s:%s", address, port)); - - server = new GoogleDevServer(); - server.writePropertiesAndStartServer(address, port, warfile, props); - } - - @Test - public void shouldPass() throws InterruptedException, IOException { - InputStream i = url.openStream(); - String string = Strings2.toStringAndClose(i); - assert string.indexOf("Welcome") >= 0 : string; - } - - @Test(dependsOnMethods = "shouldPass", expectedExceptions = IOException.class) - public void shouldFail() throws InterruptedException, IOException { - new URL(url, "/store/do").openStream(); - } - - @Test(dependsOnMethods = "shouldFail") - public void testPrimeContainers() throws IOException, InterruptedException { - URL gurl = new URL(url, "/store/do"); - - for (String context : blobstores) { - System.out.println("storing at context: " + context); - HttpURLConnection connection = (HttpURLConnection) gurl.openConnection(); - connection.addRequestProperty("X-AppEngine-QueueName", "twitter"); - connection.addRequestProperty("context", context); - InputStream i = connection.getInputStream(); - String string = Strings2.toStringAndClose(i); - assert string.indexOf("Done!") >= 0 : string; - connection.disconnect(); - } - - System.err.println("sleeping 20 seconds to allow for eventual consistency delay"); - Thread.sleep(20000); - for (BlobStoreContext context : contexts.values()) { - assert context.createInputStreamMap(container).size() > 0 : context.unwrap(Context.class).getProviderMetadata().getEndpoint(); - } - } - - @Test(invocationCount = 5, dependsOnMethods = "testPrimeContainers") - public void testSerial() throws InterruptedException, IOException { - URL gurl = new URL(url, "/tweets/get"); - InputStream i = gurl.openStream(); - String string = Strings2.toStringAndClose(i); - assert string.indexOf("Tweets in Clouds") >= 0 : string; - } - - @Test(invocationCount = 10, dependsOnMethods = "testPrimeContainers", threadPoolSize = 3) - public void testParallel() throws InterruptedException, IOException { - URL gurl = new URL(url, "/tweets/get"); - InputStream i = gurl.openStream(); - String string = Strings2.toStringAndClose(i); - assert string.indexOf("Tweets in Clouds") >= 0 : string; - } - - @AfterTest - public void stopDevAppServer() throws Exception { - server.stop(); - } -} diff --git a/demos/tweetstore/gae-tweetstore/src/test/resources/log4j.xml b/demos/tweetstore/gae-tweetstore/src/test/resources/log4j.xml deleted file mode 100644 index 2e5d01fb9e..0000000000 --- a/demos/tweetstore/gae-tweetstore/src/test/resources/log4j.xml +++ /dev/null @@ -1,95 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/demos/tweetstore/heroku-tweetstore/README.txt b/demos/tweetstore/heroku-tweetstore/README.txt deleted file mode 100644 index c6bf77b0dd..0000000000 --- a/demos/tweetstore/heroku-tweetstore/README.txt +++ /dev/null @@ -1,41 +0,0 @@ -==== - Licensed to jclouds, Inc. (jclouds) under one or more - contributor license agreements. See the NOTICE file - distributed with this work for additional information - regarding copyright ownership. jclouds licenses this file - to you under the Apache License, Version 2.0 (the - "License"); you may not use this file except in compliance - with the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, - software distributed under the License is distributed on an - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - KIND, either express or implied. See the License for the - specific language governing permissions and limitations - under the License. -==== - -A guide to generating Twitter consumer keys and access tokens is at http://tinyurl.com/2fhebgb - -Please modify your maven settings.xml like below before attempting to run 'mvn -Plive install' - - - keys - - true - - - YOUR_ACCESS_KEY_ID - YOUR_SECRET_KEY - YOUR_USER - YOUR_HEX_KEY - YOUR_ACCOUNT - YOUR_BASE64_ENCODED_KEY - YOUR_TWITTER_CONSUMER_KEY - YOUR_TWITTER_CONSUMER_SECRET - YOUR_TWITTER_ACCESSTOKEN - YOUR_TWITTER_ACCESSTOKEN_SECRET - - \ No newline at end of file diff --git a/demos/tweetstore/heroku-tweetstore/pom.xml b/demos/tweetstore/heroku-tweetstore/pom.xml deleted file mode 100644 index a99264e73e..0000000000 --- a/demos/tweetstore/heroku-tweetstore/pom.xml +++ /dev/null @@ -1,148 +0,0 @@ - - - - 4.0.0 - - org.jclouds - jclouds-demos-tweetstore-project - 1.5.0-SNAPSHOT - - jclouds-demo-heroku-tweetstore - war - jclouds TweetStore for Heroku - jclouds TweetStore for Heroku's Cedar using Guice for Dependency Injection - - - localhost - 8088 - jclouds-heroku-tweetstore - - - - - com.google.inject.extensions - guice-servlet - 3.0 - - - org.quartz-scheduler - quartz - 2.1.3 - - - org.slf4j - slf4j-api - - - - - - javax.servlet - servlet-api - 2.5 - - - - - org.mortbay.jetty - jetty-runner - 7.5.4.v20111024 - test - - - org.eclipse.jetty - jetty-plus - - - org.eclipse.jetty - jetty-jndi - - - org.mortbay.jetty - jsp-2.1-glassfish - - - javax.transaction - jta - - - - - - - - live - - - - maven-surefire-plugin - - - integration - integration-test - - test - - - - ${test.twitter.runatcloud-tweetstore.consumer.identity} - ${test.twitter.runatcloud-tweetstore.consumer.credential} - ${test.twitter.runatcloud-tweetstore.access.identity} - ${test.twitter.runatcloud-tweetstore.access.credential} - ${test.azureblob.identity} - ${test.azureblob.credential} - ${test.cloudfiles-us.identity} - ${test.cloudfiles-us.credential} - ${test.aws-s3.identity} - ${test.aws-s3.credential} - ${test.cloudonestorage.identity} - ${test.cloudonestorage.credential} - ${test.ninefold-storage.identity} - ${test.ninefold-storage.credential} - ${test.jetty.address} - ${test.jetty.port} - ${project.build.directory}/jetty - ${jclouds.tweetstore.blobstores} - test.${jclouds.tweetstore.container} - ${project.build.directory}/${project.artifactId} - - - ${test.jetty.address} - ${test.jetty.port} - - - - - - - - - - - deploy - - - heroku-tweetstore - - - - diff --git a/demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/paas/PlatformServices.java b/demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/paas/PlatformServices.java deleted file mode 100644 index c768b42611..0000000000 --- a/demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/paas/PlatformServices.java +++ /dev/null @@ -1,57 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.paas; - -import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.demo.paas.config.PlatformServicesInitializer.PLATFORM_SERVICES_ATTRIBUTE_NAME; - -import java.util.Map; - -import javax.servlet.ServletContext; - -import org.jclouds.demo.paas.service.taskqueue.TaskQueue; -import org.jclouds.javax.annotation.Nullable; - -import com.google.common.collect.ImmutableMap; - -/** - * @author Andrew Phillips - */ -public class PlatformServices { - protected final String baseUrl; - private ImmutableMap taskQueues; - - public PlatformServices(String baseUrl, Map taskQueues) { - this.baseUrl = baseUrl; - this.taskQueues = ImmutableMap.copyOf(taskQueues); - } - - public String getBaseUrl() { - return baseUrl; - } - - public @Nullable TaskQueue getTaskQueue(String name) { - return taskQueues.get(name); - } - - public static PlatformServices get(ServletContext context) { - return (PlatformServices) checkNotNull(context.getAttribute( - PLATFORM_SERVICES_ATTRIBUTE_NAME), PLATFORM_SERVICES_ATTRIBUTE_NAME); - } -} diff --git a/demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/paas/RunnableHttpRequest.java b/demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/paas/RunnableHttpRequest.java deleted file mode 100644 index ad72a1a58d..0000000000 --- a/demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/paas/RunnableHttpRequest.java +++ /dev/null @@ -1,126 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.paas; - -import static java.lang.String.format; - -import org.jclouds.http.HttpCommand; -import org.jclouds.http.HttpCommandExecutorService; -import org.jclouds.http.HttpRequest; - -import com.google.common.collect.ImmutableMultimap; -import com.google.common.collect.Multimap; - -public class RunnableHttpRequest implements Runnable { - public static final String PLATFORM_REQUEST_ORIGINATOR_HEADER = "X-Platform-Originator"; - - public static Factory factory(HttpCommandExecutorService httpClient) { - return factory(httpClient, format("%s@%d", Factory.class.getName(), System.currentTimeMillis())); - } - - public static Factory factory(HttpCommandExecutorService httpClient, String originator) { - return new Factory(httpClient, originator); - } - - public static class Factory { - protected final HttpCommandExecutorService httpClient; - protected final String originator; - - private Factory(HttpCommandExecutorService httpClient, String originator) { - this.httpClient = httpClient; - this.originator = originator; - } - - public RunnableHttpRequest create(HttpRequest request) { - HttpRequest requestWithSubmitter = request.toBuilder() - .headers(copyOfWithEntry(request.getHeaders(), - PLATFORM_REQUEST_ORIGINATOR_HEADER, originator)).build(); - return new RunnableHttpRequest(httpClient, requestWithSubmitter); - } - - private static Multimap copyOfWithEntry( - Multimap multimap, K k1, V v1) { - return ImmutableMultimap.builder().putAll(multimap).put(k1, v1).build(); - } - } - - private final HttpCommandExecutorService httpClient; - private final HttpRequest request; - - private RunnableHttpRequest(HttpCommandExecutorService httpClient, HttpRequest request) { - this.httpClient = httpClient; - this.request = request; - } - - @Override - public void run() { - httpClient.submit(new ImmutableHttpCommand(request)); - } - - private class ImmutableHttpCommand implements HttpCommand { - private final HttpRequest request; - - public ImmutableHttpCommand(HttpRequest request) { - this.request = request; - } - - @Override - public void setException(Exception exception) { - } - - @Override - public void setCurrentRequest(HttpRequest request) { - } - - @Override - public boolean isReplayable() { - return false; - } - - @Override - public int incrementRedirectCount() { - return 0; - } - - @Override - public int incrementFailureCount() { - return 0; - } - - @Override - public int getRedirectCount() { - return 0; - } - - @Override - public int getFailureCount() { - return 0; - } - - @Override - public Exception getException() { - return null; - } - - @Override - public HttpRequest getCurrentRequest() { - return request; - } - } -} diff --git a/demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/paas/config/HttpClientModule.java b/demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/paas/config/HttpClientModule.java deleted file mode 100644 index 5aa077b6cd..0000000000 --- a/demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/paas/config/HttpClientModule.java +++ /dev/null @@ -1,65 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.paas.config; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.inject.name.Names.bindProperties; -import static org.jclouds.Constants.*; - -import java.util.Properties; - -import javax.servlet.ServletContext; -import javax.ws.rs.core.UriBuilder; - -import org.jclouds.demo.tweetstore.config.util.PropertiesLoader; - -import com.google.inject.AbstractModule; -import com.sun.jersey.api.uri.UriBuilderImpl; - -/** - * @author Andrew Phillips - */ -public class HttpClientModule extends AbstractModule { - private final ServletContext context; - - HttpClientModule(ServletContext context) { - this.context = context; - } - - @Override - protected void configure() { - // URL connection defaults - Properties toBind = defaultProperties(); - toBind.putAll(checkNotNull(new PropertiesLoader(context).get(), "properties")); - toBind.putAll(System.getProperties()); - bindProperties(binder(), toBind); - bind(UriBuilder.class).to(UriBuilderImpl.class); - } - - private static Properties defaultProperties() { - Properties props = new Properties(); - props.setProperty(PROPERTY_MAX_CONNECTIONS_PER_CONTEXT, 20 + ""); - props.setProperty(PROPERTY_MAX_CONNECTIONS_PER_HOST, 0 + ""); - props.setProperty(PROPERTY_SO_TIMEOUT, 60000 + ""); - props.setProperty(PROPERTY_CONNECTION_TIMEOUT, 60000 + ""); - props.setProperty(PROPERTY_USER_THREADS, 0 + ""); - props.setProperty(PROPERTY_IO_WORKER_THREADS, 20 + ""); - return props; - } -} diff --git a/demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/paas/config/PlatformServicesInitializer.java b/demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/paas/config/PlatformServicesInitializer.java deleted file mode 100644 index e0c3eec312..0000000000 --- a/demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/paas/config/PlatformServicesInitializer.java +++ /dev/null @@ -1,87 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.paas.config; - -import static com.google.common.base.Preconditions.checkNotNull; -import static java.lang.String.format; -import static java.util.concurrent.TimeUnit.SECONDS; - -import javax.servlet.ServletContext; -import javax.servlet.ServletContextEvent; -import javax.servlet.ServletContextListener; - -import org.jclouds.concurrent.config.ExecutorServiceModule; -import org.jclouds.demo.paas.PlatformServices; -import org.jclouds.demo.paas.service.taskqueue.TaskQueue; -import org.jclouds.http.HttpCommandExecutorService; -import org.jclouds.http.config.JavaUrlHttpCommandExecutorServiceModule; - -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableMap.Builder; -import com.google.inject.Guice; - -/** - * @author Andrew Phillips - */ -public class PlatformServicesInitializer implements ServletContextListener { - public static final String PLATFORM_SERVICES_ATTRIBUTE_NAME = PlatformServices.class.getName(); - - protected static final String HOST_VARIABLE = "PUBLIC_HOST"; - protected static final String PORT_VARIABLE = "PUBLIC_PORT"; - - @Override - public void contextInitialized(ServletContextEvent contextEvent) { - ServletContext context = contextEvent.getServletContext(); - context.setAttribute(PLATFORM_SERVICES_ATTRIBUTE_NAME, createServices(context)); - } - - protected static PlatformServices createServices(ServletContext context) { - HttpCommandExecutorService httpClient = createHttpClient(context); - return new PlatformServices(getBaseUrl(context), createTaskQueues(httpClient)); - } - - protected static HttpCommandExecutorService createHttpClient( - final ServletContext context) { - return Guice.createInjector(new ExecutorServiceModule(), - new JavaUrlHttpCommandExecutorServiceModule(), - new HttpClientModule(context)) - .getInstance(HttpCommandExecutorService.class); - } - - protected static String getBaseUrl(ServletContext context) { - // use the public URL while https://support.heroku.com/requests/51088 is open - return format("http://%s:%s/%s", checkNotNull(System.getenv(HOST_VARIABLE), HOST_VARIABLE), - checkNotNull(System.getenv(PORT_VARIABLE), PORT_VARIABLE), context.getContextPath()); - } - - // TODO: make the number and names of queues configurable - protected static ImmutableMap createTaskQueues(HttpCommandExecutorService httpClient) { - Builder taskQueues = ImmutableMap.builder(); - taskQueues.put("twitter", TaskQueue.builder(httpClient) - .name("twitter").period(SECONDS.toMillis(30)) - .build()); - return taskQueues.build(); - } - - @Override - public void contextDestroyed(ServletContextEvent servletContextEvent) { - ServletContext context = servletContextEvent.getServletContext(); - context.removeAttribute(PLATFORM_SERVICES_ATTRIBUTE_NAME); - } -} diff --git a/demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/paas/service/taskqueue/TaskQueue.java b/demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/paas/service/taskqueue/TaskQueue.java deleted file mode 100644 index e317a305cf..0000000000 --- a/demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/paas/service/taskqueue/TaskQueue.java +++ /dev/null @@ -1,107 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.paas.service.taskqueue; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; -import static java.lang.String.format; - -import java.util.Timer; -import java.util.TimerTask; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.TimeUnit; - -import org.jclouds.demo.paas.RunnableHttpRequest; -import org.jclouds.demo.paas.RunnableHttpRequest.Factory; -import org.jclouds.http.HttpCommandExecutorService; - -import com.google.inject.Provider; - -public class TaskQueue { - protected final Factory httpRequestFactory; - private final Timer timer; - private final ConcurrentLinkedQueue tasks = new ConcurrentLinkedQueue(); - - private TaskQueue(String name, long pollingIntervalMillis, Factory httpRequestFactory) { - this.httpRequestFactory = httpRequestFactory; - timer = new Timer(name); - timer.scheduleAtFixedRate(new TimerTask() { - @Override - public void run() { - Runnable task = tasks.poll(); - if (task != null) { - task.run(); - } - } - }, 0, pollingIntervalMillis); - } - - public void add(final Runnable task) { - tasks.add(task); - } - - public Factory getHttpRequestFactory() { - return httpRequestFactory; - } - - public void destroy() { - timer.cancel(); - tasks.clear(); - } - - public static Builder builder(HttpCommandExecutorService httpClient) { - return new Builder(httpClient); - } - - public static class Builder implements Provider { - protected final HttpCommandExecutorService httpClient; - protected String name = "default"; - protected long pollingIntervalMillis = TimeUnit.SECONDS.toMillis(1); - - private Builder(HttpCommandExecutorService httpClient) { - this.httpClient = checkNotNull(httpClient, "httpClient"); - } - - public Builder name(String name) { - this.name = checkNotNull(name, "name"); - return this; - } - - public Builder period(TimeUnit period) { - this.pollingIntervalMillis = checkNotNull(period, "period").toMillis(1); - return this; - } - - public Builder period(long pollingIntervalMillis) { - checkArgument(pollingIntervalMillis > 0, "pollingIntervalMillis"); - this.pollingIntervalMillis = pollingIntervalMillis; - return this; - } - - public TaskQueue build() { - return new TaskQueue(name, pollingIntervalMillis, - RunnableHttpRequest.factory(httpClient, format("taskqueue-%s", name))); - } - - @Override - public TaskQueue get() { - return build(); - } - } -} \ No newline at end of file diff --git a/demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/tweetstore/config/GuiceServletConfig.java b/demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/tweetstore/config/GuiceServletConfig.java deleted file mode 100644 index c03434388a..0000000000 --- a/demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/tweetstore/config/GuiceServletConfig.java +++ /dev/null @@ -1,155 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.config; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Preconditions.checkState; -import static com.google.common.base.Predicates.in; -import static com.google.common.collect.ImmutableSet.copyOf; -import static com.google.common.collect.Sets.filter; -import static org.jclouds.demo.paas.reference.PaasConstants.PROPERTY_PLATFORM_BASE_URL; -import static org.jclouds.demo.tweetstore.reference.TweetStoreConstants.PROPERTY_TWEETSTORE_BLOBSTORES; -import static org.jclouds.demo.tweetstore.reference.TweetStoreConstants.PROPERTY_TWEETSTORE_CONTAINER; -import static org.jclouds.demo.tweetstore.reference.TwitterConstants.PROPERTY_TWITTER_ACCESSTOKEN; -import static org.jclouds.demo.tweetstore.reference.TwitterConstants.PROPERTY_TWITTER_ACCESSTOKEN_SECRET; -import static org.jclouds.demo.tweetstore.reference.TwitterConstants.PROPERTY_TWITTER_CONSUMER_KEY; -import static org.jclouds.demo.tweetstore.reference.TwitterConstants.PROPERTY_TWITTER_CONSUMER_SECRET; - -import java.util.Map; -import java.util.Properties; -import java.util.Set; - -import javax.servlet.ServletContext; -import javax.servlet.ServletContextEvent; - -import org.jclouds.ContextBuilder; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.demo.paas.PlatformServices; -import org.jclouds.demo.paas.service.taskqueue.TaskQueue; -import org.jclouds.demo.tweetstore.config.util.CredentialsCollector; -import org.jclouds.demo.tweetstore.config.util.PropertiesLoader; -import org.jclouds.demo.tweetstore.controller.AddTweetsController; -import org.jclouds.demo.tweetstore.controller.ClearTweetsController; -import org.jclouds.demo.tweetstore.controller.EnqueueStoresController; -import org.jclouds.demo.tweetstore.controller.StoreTweetsController; - -import twitter4j.Twitter; -import twitter4j.TwitterFactory; -import twitter4j.conf.Configuration; -import twitter4j.conf.ConfigurationBuilder; - -import com.google.common.base.Splitter; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Maps; -import com.google.inject.Guice; -import com.google.inject.Injector; -import com.google.inject.Module; -import com.google.inject.TypeLiteral; -import com.google.inject.name.Names; -import com.google.inject.servlet.GuiceServletContextListener; -import com.google.inject.servlet.ServletModule; - -/** - * Setup Logging and create Injector for use in testing S3. - * - * @author Adrian Cole - */ -public class GuiceServletConfig extends GuiceServletContextListener { - private Map providerTypeToBlobStoreMap; - private Twitter twitterClient; - private String container; - private TaskQueue queue; - private String baseUrl; - - @Override - public void contextInitialized(ServletContextEvent servletContextEvent) { - ServletContext servletContext = servletContextEvent.getServletContext(); - - Properties props = new PropertiesLoader(servletContext).get(); - Set modules = ImmutableSet.of(); - // shared across all blobstores and used to retrieve tweets - try { - Configuration twitterConf = new ConfigurationBuilder() - .setOAuthConsumerKey(props.getProperty(PROPERTY_TWITTER_CONSUMER_KEY)) - .setOAuthConsumerSecret(props.getProperty(PROPERTY_TWITTER_CONSUMER_SECRET)) - .setOAuthAccessToken(props.getProperty(PROPERTY_TWITTER_ACCESSTOKEN)) - .setOAuthAccessTokenSecret(props.getProperty(PROPERTY_TWITTER_ACCESSTOKEN_SECRET)) - .build(); - twitterClient = new TwitterFactory(twitterConf).getInstance(); - } catch (IllegalArgumentException e) { - throw new IllegalArgumentException("properties for twitter not configured properly in " + props.toString(), e); - } - // common namespace for storing tweets - container = checkNotNull(props.getProperty(PROPERTY_TWEETSTORE_CONTAINER), PROPERTY_TWEETSTORE_CONTAINER); - - // instantiate and store references to all blobstores by provider name - providerTypeToBlobStoreMap = Maps.newHashMap(); - for (String hint : getBlobstoreContexts(props)) { - providerTypeToBlobStoreMap.put(hint, ContextBuilder.newBuilder(hint) - .modules(modules).overrides(props).build(BlobStoreContext.class)); - } - - // get a queue for submitting store tweet requests and the application's base URL - PlatformServices platform = PlatformServices.get(servletContext); - queue = platform.getTaskQueue("twitter"); - baseUrl = platform.getBaseUrl(); - - super.contextInitialized(servletContextEvent); - } - - private static Iterable getBlobstoreContexts(Properties props) { - Set contexts = new CredentialsCollector().apply(props).keySet(); - String explicitContexts = props.getProperty(PROPERTY_TWEETSTORE_BLOBSTORES); - if (explicitContexts != null) { - contexts = filter(contexts, in(copyOf(Splitter.on(',').split(explicitContexts)))); - } - checkState(!contexts.isEmpty(), "no credentials available for any requested context"); - return contexts; - } - - @Override - protected Injector getInjector() { - return Guice.createInjector(new ServletModule() { - @Override - protected void configureServlets() { - bind(new TypeLiteral>() {}) - .toInstance(providerTypeToBlobStoreMap); - bind(Twitter.class).toInstance(twitterClient); - bind(TaskQueue.class).toInstance(queue); - bindConstant().annotatedWith(Names.named(PROPERTY_PLATFORM_BASE_URL)) - .to(baseUrl); - bindConstant().annotatedWith(Names.named(PROPERTY_TWEETSTORE_CONTAINER)) - .to(container); - serve("/store/*").with(StoreTweetsController.class); - serve("/tweets/*").with(AddTweetsController.class); - serve("/stores/*").with(EnqueueStoresController.class); - serve("/clear/*").with(ClearTweetsController.class); - } - }); - } - - @Override - public void contextDestroyed(ServletContextEvent servletContextEvent) { - for (BlobStoreContext context : providerTypeToBlobStoreMap.values()) { - context.close(); - } - queue.destroy(); - super.contextDestroyed(servletContextEvent); - } -} \ No newline at end of file diff --git a/demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/tweetstore/config/util/CredentialsCollector.java b/demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/tweetstore/config/util/CredentialsCollector.java deleted file mode 100644 index ce3943376e..0000000000 --- a/demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/tweetstore/config/util/CredentialsCollector.java +++ /dev/null @@ -1,153 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.config.util; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Preconditions.checkState; -import static com.google.common.base.Predicates.notNull; -import static com.google.common.collect.Collections2.filter; -import static com.google.common.collect.Collections2.transform; -import static com.google.common.collect.ImmutableSet.copyOf; -import static com.google.common.collect.Maps.filterValues; -import static org.jclouds.util.Maps2.fromKeys; - -import java.util.Collection; -import java.util.Map; -import java.util.Properties; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.jclouds.demo.tweetstore.config.util.CredentialsCollector.Credential; - -import com.google.common.annotations.GwtIncompatible; -import com.google.common.base.Function; -import com.google.common.base.Predicate; - -/** - * Reads provider credentials from a {@link Properties} bag. - * - * @author Andrew Phillips - * - */ -public class CredentialsCollector implements Function> { - private static final String IDENTITY_PROPERTY_SUFFIX = ".identity"; - private static final String CREDENTIAL_PROPERTY_SUFFIX = ".credential"; - - // using the identity for provider name extraction - private static final Pattern IDENTITY_PROPERTY_PATTERN = - Pattern.compile("([a-zA-Z0-9-]+)" + Pattern.quote(IDENTITY_PROPERTY_SUFFIX)); - - @Override - public Map apply(final Properties properties) { - Collection providerNames = transform( - filter(properties.stringPropertyNames(), MatchesPattern.matches(IDENTITY_PROPERTY_PATTERN)), - new Function() { - @Override - public String apply(String input) { - Matcher matcher = IDENTITY_PROPERTY_PATTERN.matcher(input); - // as a side-effect, sets the matching group! - checkState(matcher.matches(), "'%s' should match '%s'", input, IDENTITY_PROPERTY_PATTERN); - return matcher.group(1); - } - }); - /* - * Providers without a credential property result in null values, which are - * removed from the returned map. - */ - return filterValues(fromKeys(copyOf(providerNames), new Function() { - @Override - public Credential apply(String providerName) { - String identity = properties.getProperty(providerName + IDENTITY_PROPERTY_SUFFIX); - String credential = properties.getProperty(providerName + CREDENTIAL_PROPERTY_SUFFIX); - return (((identity != null) && (credential != null)) - ? new Credential(identity, credential) - : null); - } - }), notNull()); - } - - public static class Credential { - private final String identity; - private final String credential; - - public Credential(String identity, String credential) { - this.identity = checkNotNull(identity, "identity"); - this.credential = checkNotNull(credential, "credential"); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result - + ((credential == null) ? 0 : credential.hashCode()); - result = prime * result - + ((identity == null) ? 0 : identity.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Credential other = (Credential) obj; - if (credential == null) { - if (other.credential != null) - return false; - } else if (!credential.equals(other.credential)) - return false; - if (identity == null) { - if (other.identity != null) - return false; - } else if (!identity.equals(other.identity)) - return false; - return true; - } - - public String getIdentity() { - return identity; - } - - public String getCredential() { - return credential; - } - } - - @GwtIncompatible(value = "java.util.regex.Pattern") - private static class MatchesPattern implements Predicate { - private final Pattern pattern; - - private MatchesPattern(Pattern pattern) { - this.pattern = pattern; - } - - @Override - public boolean apply(String input) { - return pattern.matcher(input).matches(); - } - - private static MatchesPattern matches(Pattern pattern) { - return new MatchesPattern(pattern); - } - } -} diff --git a/demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/tweetstore/config/util/PropertiesLoader.java b/demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/tweetstore/config/util/PropertiesLoader.java deleted file mode 100644 index dafa5c311b..0000000000 --- a/demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/tweetstore/config/util/PropertiesLoader.java +++ /dev/null @@ -1,59 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.config.util; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; - -import javax.servlet.ServletContext; - -import com.google.common.io.Closeables; -import com.google.inject.Provider; - -/** - * @author Andrew Phillips - */ -public class PropertiesLoader implements Provider{ - private static final String PROPERTIES_FILE = "/WEB-INF/jclouds.properties"; - - private final Properties properties; - - public PropertiesLoader(ServletContext context) { - properties = loadJcloudsProperties(context); - } - - private static Properties loadJcloudsProperties(ServletContext context) { - InputStream input = context.getResourceAsStream(PROPERTIES_FILE); - Properties props = new Properties(); - try { - props.load(input); - } catch (IOException e) { - throw new RuntimeException(e); - } finally { - Closeables.closeQuietly(input); - } - return props; - } - - @Override - public Properties get() { - return properties; - } -} diff --git a/demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/tweetstore/controller/AddTweetsController.java b/demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/tweetstore/controller/AddTweetsController.java deleted file mode 100644 index 007fbafdef..0000000000 --- a/demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/tweetstore/controller/AddTweetsController.java +++ /dev/null @@ -1,96 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.controller; - -import java.io.IOException; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeoutException; - -import javax.annotation.Resource; -import javax.inject.Inject; -import javax.inject.Singleton; -import javax.servlet.RequestDispatcher; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.demo.tweetstore.domain.StoredTweetStatus; -import org.jclouds.demo.tweetstore.functions.ServiceToStoredTweetStatuses; -import org.jclouds.logging.Logger; - -import com.google.common.base.Function; -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; - -/** - * Shows an example of how to use @{link BlobStoreContext} injected with Guice. - * - * @author Adrian Cole - */ -@Singleton -public class AddTweetsController extends HttpServlet implements - Function, List> { - - /** The serialVersionUID */ - private static final long serialVersionUID = 3888348023150822683L; - private final Map contexts; - private final ServiceToStoredTweetStatuses blobStoreContextToContainerResult; - - @Resource - protected Logger logger = Logger.NULL; - - @Inject - AddTweetsController(Map contexts, - ServiceToStoredTweetStatuses blobStoreContextToContainerResult) { - this.contexts = contexts; - this.blobStoreContextToContainerResult = blobStoreContextToContainerResult; - } - - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - try { - addMyTweetsToRequest(request); - RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/tweets.jsp"); - dispatcher.forward(request, response); - } catch (Exception e) { - logger.error(e, "Error listing containers"); - throw new ServletException(e); - } - } - - void addMyTweetsToRequest(HttpServletRequest request) throws InterruptedException, - ExecutionException, TimeoutException { - request.setAttribute("tweets", apply(contexts.keySet())); - } - - public List apply(Set in) { - List statuses = Lists.newArrayList(); - for (Iterable list : Iterables.transform(in, - blobStoreContextToContainerResult)) { - Iterables.addAll(statuses, list); - } - return statuses; - } -} diff --git a/demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/tweetstore/controller/ClearTweetsController.java b/demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/tweetstore/controller/ClearTweetsController.java deleted file mode 100644 index e08cfbc19e..0000000000 --- a/demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/tweetstore/controller/ClearTweetsController.java +++ /dev/null @@ -1,96 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.controller; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Strings.nullToEmpty; - -import java.io.IOException; -import java.util.Map; - -import javax.annotation.Resource; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.core.MediaType; - -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.jclouds.logging.Logger; - -import com.google.common.annotations.VisibleForTesting; - -/** - * Grab tweets related to me and store them into blobstores - * - * @author Adrian Cole - */ -@Singleton -public class ClearTweetsController extends HttpServlet { - /** The serialVersionUID */ - private static final long serialVersionUID = 7215420527854203714L; - - private final Map contexts; - private final String container; - - @Resource - protected Logger logger = Logger.NULL; - - @Inject - @VisibleForTesting - public ClearTweetsController(Map contexts, - @Named(TweetStoreConstants.PROPERTY_TWEETSTORE_CONTAINER) String container) { - this.container = container; - this.contexts = contexts; - } - - @VisibleForTesting - public void clearContainer(String contextName) { - BlobStoreContext context = checkNotNull(contexts.get(contextName), - "no context for %s in %s", contextName, contexts.keySet()); - try { - context.getBlobStore().clearContainer(container); - } catch (Exception e) { - logger.error(e, "Error clearing tweets in %s/%s", container, context); - } - } - - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - if (nullToEmpty(request.getHeader("X-Originator")).equals("admin")) { - try { - String contextName = checkNotNull(request.getHeader("context"), "missing header context"); - logger.info("clearing tweets in %s/%s", container, contextName); - clearContainer(contextName); - logger.debug("done clearing tweets"); - response.setContentType(MediaType.TEXT_PLAIN); - response.getWriter().println("Done!"); - } catch (Exception e) { - logger.error(e, "Error clearing tweets"); - throw new ServletException(e); - } - } else { - response.sendError(401); - } - } -} \ No newline at end of file diff --git a/demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/tweetstore/controller/EnqueueStoresController.java b/demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/tweetstore/controller/EnqueueStoresController.java deleted file mode 100644 index 552a7fc69a..0000000000 --- a/demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/tweetstore/controller/EnqueueStoresController.java +++ /dev/null @@ -1,100 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.controller; - -import static com.google.common.base.Strings.nullToEmpty; - -import java.io.IOException; -import java.net.URI; -import java.util.Map; -import java.util.Set; - -import javax.annotation.Resource; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.core.MediaType; - -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.demo.paas.reference.PaasConstants; -import org.jclouds.demo.paas.service.taskqueue.TaskQueue; -import org.jclouds.http.HttpRequest; -import org.jclouds.logging.Logger; - -import com.google.common.annotations.VisibleForTesting; -import com.google.common.collect.ImmutableMultimap; - -/** - * Adds tasks to retrieve and store tweets in all registered contexts to an async - * task queue. - * - * @author Andrew Phillips - * @see StoreTweetsController - */ -@Singleton -public class EnqueueStoresController extends HttpServlet { - /** The serialVersionUID */ - private static final long serialVersionUID = 7215420527854203714L; - - private final Set contextNames; - private final TaskQueue taskQueue; - private final String baseUrl; - - @Resource - protected Logger logger = Logger.NULL; - - @Inject - public EnqueueStoresController(Map contexts, TaskQueue taskQueue, - @Named(PaasConstants.PROPERTY_PLATFORM_BASE_URL) String baseUrl) { - contextNames = contexts.keySet(); - this.taskQueue = taskQueue; - this.baseUrl = baseUrl; - } - - @VisibleForTesting - void enqueueStoreTweetTasks() { - for (String contextName : contextNames) { - logger.debug("enqueuing task to store tweets in blobstore '%s'", contextName); - taskQueue.add(taskQueue.getHttpRequestFactory().create(HttpRequest.builder() - .endpoint(URI.create(baseUrl + "/store/do")) - .headers(ImmutableMultimap.of("context", contextName)) - .method("GET").build())); - } - } - - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - if (!nullToEmpty(request.getHeader("X-Heroku-Cron")).equals("true")) { - response.sendError(401); - } - - try { - enqueueStoreTweetTasks(); - response.setContentType(MediaType.TEXT_PLAIN); - response.getWriter().println("Done!"); - } catch (Exception e) { - logger.error(e, "Error storing tweets"); - throw new ServletException(e); - } - } -} \ No newline at end of file diff --git a/demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/tweetstore/controller/StoreTweetsController.java b/demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/tweetstore/controller/StoreTweetsController.java deleted file mode 100644 index 948c9ff4ca..0000000000 --- a/demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/tweetstore/controller/StoreTweetsController.java +++ /dev/null @@ -1,130 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.controller; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Strings.nullToEmpty; -import static org.jclouds.demo.paas.RunnableHttpRequest.PLATFORM_REQUEST_ORIGINATOR_HEADER; - -import java.io.IOException; -import java.util.Map; - -import javax.annotation.Resource; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.core.MediaType; - -import org.jclouds.blobstore.BlobMap; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.blobstore.domain.Blob; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.jclouds.logging.Logger; -import org.jclouds.rest.AuthorizationException; - -import twitter4j.Status; -import twitter4j.Twitter; - -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Function; - -/** - * Grab tweets related to me and store them into blobstores - * - * @author Adrian Cole - */ -@Singleton -public class StoreTweetsController extends HttpServlet { - - private static final class StatusToBlob implements Function { - private final BlobMap map; - - private StatusToBlob(BlobMap map) { - this.map = map; - } - - public Blob apply(Status from) { - Blob to = map.blobBuilder().name(from.getId() + "").build(); - to.setPayload(from.getText()); - to.getPayload().getContentMetadata().setContentType(MediaType.TEXT_PLAIN); - to.getMetadata().getUserMetadata().put(TweetStoreConstants.SENDER_NAME, from.getUser().getScreenName()); - return to; - } - } - - /** The serialVersionUID */ - private static final long serialVersionUID = 7215420527854203714L; - - private final Map contexts; - private final Twitter client; - private final String container; - - @Resource - protected Logger logger = Logger.NULL; - - @Inject - @VisibleForTesting - public StoreTweetsController(Map contexts, - @Named(TweetStoreConstants.PROPERTY_TWEETSTORE_CONTAINER) String container, Twitter client) { - this.container = container; - this.contexts = contexts; - this.client = client; - } - - @VisibleForTesting - public void addMyTweets(String contextName, Iterable responseList) { - BlobStoreContext context = checkNotNull(contexts.get(contextName), "no context for " + contextName + " in " - + contexts.keySet()); - BlobMap map = context.createBlobMap(container); - for (Status status : responseList) { - Blob blob = null; - try { - blob = new StatusToBlob(map).apply(status); - map.put(status.getId() + "", blob); - } catch (AuthorizationException e) { - throw e; - } catch (Exception e) { - logger.error(e, "Error storing tweet %s (blob[%s]) on map %s/%s", status.getId(), blob, context, container); - } - } - } - - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - if (nullToEmpty(request.getHeader(PLATFORM_REQUEST_ORIGINATOR_HEADER)).equals("taskqueue-twitter")) { - try { - String contextName = checkNotNull(request.getHeader("context"), "missing header context"); - logger.info("retrieving tweets"); - addMyTweets(contextName, client.getMentions()); - logger.debug("done storing tweets"); - response.setContentType(MediaType.TEXT_PLAIN); - response.getWriter().println("Done!"); - } catch (Exception e) { - logger.error(e, "Error storing tweets"); - throw new ServletException(e); - } - } else { - response.sendError(401); - } - } -} \ No newline at end of file diff --git a/demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/tweetstore/domain/StoredTweetStatus.java b/demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/tweetstore/domain/StoredTweetStatus.java deleted file mode 100644 index 42ad65df01..0000000000 --- a/demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/tweetstore/domain/StoredTweetStatus.java +++ /dev/null @@ -1,149 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.domain; - -import java.io.Serializable; - -/** - * - * @author Adrian Cole - */ -public class StoredTweetStatus implements Comparable, Serializable { - - /** The serialVersionUID */ - private static final long serialVersionUID = -3257496189689220018L; - private final String service; - private final String host; - private final String container; - private final String id; - private final String from; - private final String tweet; - private final String status; - - @Override - public String toString() { - return "StoredTweetStatus [container=" + container + ", from=" + from + ", host=" + host - + ", id=" + id + ", service=" + service + ", status=" + status + ", tweet=" + tweet - + "]"; - } - - public StoredTweetStatus(String service, String host, String container, String id, String from, - String tweet, String status) { - this.service = service; - this.host = host; - this.container = container; - this.id = id; - this.from = from; - this.tweet = tweet; - this.status = status; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((container == null) ? 0 : container.hashCode()); - result = prime * result + ((from == null) ? 0 : from.hashCode()); - result = prime * result + ((host == null) ? 0 : host.hashCode()); - result = prime * result + ((id == null) ? 0 : id.hashCode()); - result = prime * result + ((service == null) ? 0 : service.hashCode()); - result = prime * result + ((tweet == null) ? 0 : tweet.hashCode()); - return result; - } - - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - StoredTweetStatus other = (StoredTweetStatus) obj; - if (container == null) { - if (other.container != null) - return false; - } else if (!container.equals(other.container)) - return false; - if (from == null) { - if (other.from != null) - return false; - } else if (!from.equals(other.from)) - return false; - if (host == null) { - if (other.host != null) - return false; - } else if (!host.equals(other.host)) - return false; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - if (service == null) { - if (other.service != null) - return false; - } else if (!service.equals(other.service)) - return false; - if (tweet == null) { - if (other.tweet != null) - return false; - } else if (!tweet.equals(other.tweet)) - return false; - return true; - } - - - public String getService() { - return service; - } - - public String getHost() { - return host; - } - - public String getContainer() { - return container; - } - - public String getFrom() { - return from; - } - - public String getTweet() { - return tweet; - } - - public String getStatus() { - return status; - } - - public int compareTo(StoredTweetStatus o) { - if (id == null) - return -1; - return (int) ((this == o) ? 0 : id.compareTo(o.id)); - } - - - public String getId() { - return id; - } - -} diff --git a/demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/tweetstore/functions/KeyToStoredTweetStatus.java b/demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/tweetstore/functions/KeyToStoredTweetStatus.java deleted file mode 100644 index f831b9780f..0000000000 --- a/demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/tweetstore/functions/KeyToStoredTweetStatus.java +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.functions; - -import javax.annotation.Resource; - -import org.jclouds.blobstore.BlobMap; -import org.jclouds.blobstore.domain.Blob; -import org.jclouds.demo.tweetstore.domain.StoredTweetStatus; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.jclouds.logging.Logger; -import org.jclouds.util.Strings2; - -import com.google.common.base.Function; - -/** - * - * @author Adrian Cole - */ -public class KeyToStoredTweetStatus implements Function { - private final String host; - private final BlobMap map; - private final String service; - private final String container; - - @Resource - protected Logger logger = Logger.NULL; - - KeyToStoredTweetStatus(BlobMap map, String service, String host, String container) { - this.host = host; - this.map = map; - this.service = service; - this.container = container; - } - - public StoredTweetStatus apply(String id) { - String status; - String from; - String tweet; - try { - long start = System.currentTimeMillis(); - Blob blob = map.get(id); - status = ((System.currentTimeMillis() - start) + "ms"); - from = blob.getMetadata().getUserMetadata().get(TweetStoreConstants.SENDER_NAME); - tweet = Strings2.toString(blob.getPayload()); - } catch (Exception e) { - logger.error(e, "Error listing container %s//%s/%s", service, container, id); - status = (e.getMessage()); - tweet = ""; - from = ""; - } - return new StoredTweetStatus(service, host, container, id, from, tweet, status); - } -} diff --git a/demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/tweetstore/functions/ServiceToStoredTweetStatuses.java b/demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/tweetstore/functions/ServiceToStoredTweetStatuses.java deleted file mode 100644 index b29ec14549..0000000000 --- a/demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/tweetstore/functions/ServiceToStoredTweetStatuses.java +++ /dev/null @@ -1,73 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.functions; - -import java.net.URI; -import java.util.Collections; -import java.util.Map; -import java.util.Set; - -import javax.annotation.Resource; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - -import org.jclouds.Context; -import org.jclouds.blobstore.BlobMap; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.demo.tweetstore.domain.StoredTweetStatus; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.jclouds.logging.Logger; - -import com.google.common.base.Function; -import com.google.common.collect.Iterables; - -@Singleton -public class ServiceToStoredTweetStatuses implements Function> { - - private final Map contexts; - private final String container; - - @Inject - public ServiceToStoredTweetStatuses(Map contexts, - @Named(TweetStoreConstants.PROPERTY_TWEETSTORE_CONTAINER) String container) { - this.contexts = contexts; - this.container = container; - } - - @Resource - protected Logger logger = Logger.NULL; - - public Iterable apply(String service) { - BlobStoreContext context = contexts.get(service); - String host = URI.create(context.unwrap(Context.class).getProviderMetadata().getEndpoint()).getHost(); - try { - BlobMap blobMap = context.createBlobMap(container); - Set blobs = blobMap.keySet(); - return Iterables.transform(blobs, new KeyToStoredTweetStatus(blobMap, service, host, - container)); - } catch (Exception e) { - StoredTweetStatus result = new StoredTweetStatus(service, host, container, null, null, - null, e.getMessage()); - logger.error(e, "Error listing service %s", service); - return Collections.singletonList(result); - } - - } -} \ No newline at end of file diff --git a/demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/tweetstore/reference/TwitterConstants.java b/demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/tweetstore/reference/TwitterConstants.java deleted file mode 100644 index dc8b97915f..0000000000 --- a/demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/tweetstore/reference/TwitterConstants.java +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.reference; - -/** - * Configuration properties and constants used in Twitter connections. - * - * @author Andrew Phillips - */ -public interface TwitterConstants { - static final String PROPERTY_TWITTER_CONSUMER_KEY = "twitter.consumer.identity"; - static final String PROPERTY_TWITTER_CONSUMER_SECRET = "twitter.consumer.credential"; - static final String PROPERTY_TWITTER_ACCESSTOKEN = "twitter.access.identity"; - static final String PROPERTY_TWITTER_ACCESSTOKEN_SECRET = "twitter.access.credential"; -} diff --git a/demos/tweetstore/heroku-tweetstore/src/main/platform/.gitignore b/demos/tweetstore/heroku-tweetstore/src/main/platform/.gitignore deleted file mode 100644 index 843dfe79c0..0000000000 --- a/demos/tweetstore/heroku-tweetstore/src/main/platform/.gitignore +++ /dev/null @@ -1 +0,0 @@ -# PaaS vendor specific files go in here \ No newline at end of file diff --git a/demos/tweetstore/heroku-tweetstore/src/main/webapp/WEB-INF/web.xml b/demos/tweetstore/heroku-tweetstore/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index 5bf6bdf0bb..0000000000 --- a/demos/tweetstore/heroku-tweetstore/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,51 +0,0 @@ - - - - jclouds-tweetstore - - - - guiceFilter - com.google.inject.servlet.GuiceFilter - - - - guiceFilter - /* - - - - - org.jclouds.demo.paas.config.PlatformServicesInitializer - - - - org.jclouds.demo.tweetstore.config.GuiceServletConfig - - - - index.jsp - - - \ No newline at end of file diff --git a/demos/tweetstore/heroku-tweetstore/src/main/webapp/images/heroku-logo.png b/demos/tweetstore/heroku-tweetstore/src/main/webapp/images/heroku-logo.png deleted file mode 100644 index 1964aeefb4..0000000000 Binary files a/demos/tweetstore/heroku-tweetstore/src/main/webapp/images/heroku-logo.png and /dev/null differ diff --git a/demos/tweetstore/heroku-tweetstore/src/main/webapp/index.jsp b/demos/tweetstore/heroku-tweetstore/src/main/webapp/index.jsp deleted file mode 100644 index 9674294c6e..0000000000 --- a/demos/tweetstore/heroku-tweetstore/src/main/webapp/index.jsp +++ /dev/null @@ -1,30 +0,0 @@ -<%-- - - Licensed to jclouds, Inc. (jclouds) under one or more - contributor license agreements. See the NOTICE file - distributed with this work for additional information - regarding copyright ownership. jclouds licenses this file - to you under the Apache License, Version 2.0 (the - "License"); you may not use this file except in compliance - with the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, - software distributed under the License is distributed on an - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - KIND, either express or implied. See the License for the - specific language governing permissions and limitations - under the License. - ---%> - - -jclouds: anyweight cloudware for java - - -

Welcome!

-

Click here to see tweets about jclouds.

-

Powered by Heroku

- - diff --git a/demos/tweetstore/heroku-tweetstore/src/main/webapp/tweets.jsp b/demos/tweetstore/heroku-tweetstore/src/main/webapp/tweets.jsp deleted file mode 100644 index 469bc9cd09..0000000000 --- a/demos/tweetstore/heroku-tweetstore/src/main/webapp/tweets.jsp +++ /dev/null @@ -1,108 +0,0 @@ -<%-- - - Licensed to jclouds, Inc. (jclouds) under one or more - contributor license agreements. See the NOTICE file - distributed with this work for additional information - regarding copyright ownership. jclouds licenses this file - to you under the Apache License, Version 2.0 (the - "License"); you may not use this file except in compliance - with the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, - software distributed under the License is distributed on an - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - KIND, either express or implied. See the License for the - specific language governing permissions and limitations - under the License. - ---%> -<%@ page buffer="20kb"%> -<%@ taglib uri="http://displaytag.sf.net" prefix="display"%> - - -jclouds: anyweight cloudware for java - - - -

Tweets in Clouds

- - - - - - - -
-
- - - - - - - - -
-
Powered by Heroku
- - diff --git a/demos/tweetstore/heroku-tweetstore/src/test/java/org/jclouds/demo/tweetstore/config/util/CredentialsCollectorTest.java b/demos/tweetstore/heroku-tweetstore/src/test/java/org/jclouds/demo/tweetstore/config/util/CredentialsCollectorTest.java deleted file mode 100644 index 031bb199fc..0000000000 --- a/demos/tweetstore/heroku-tweetstore/src/test/java/org/jclouds/demo/tweetstore/config/util/CredentialsCollectorTest.java +++ /dev/null @@ -1,82 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.config.util; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; - -import java.util.Map; -import java.util.Properties; - -import org.jclouds.demo.tweetstore.config.util.CredentialsCollector; -import org.jclouds.demo.tweetstore.config.util.CredentialsCollector.Credential; -import org.testng.annotations.Test; - -import com.google.common.collect.ImmutableMap; - -/** - * Tests behavior of {@code CredentialsCollector} - * - * @author Andrew Phillips - */ -@Test(groups = "unit") -public class CredentialsCollectorTest { - private CredentialsCollector collector = new CredentialsCollector(); - - public void testEmptyProperties() { - assertTrue(collector.apply(new Properties()).isEmpty(), - "Expected returned map to be empty"); - } - - public void testNoCredentials() { - Properties properties = propertiesOf(ImmutableMap.of("not-an-identity", - "v1", "not-a-credential", "v2")); - assertTrue(collector.apply(properties).isEmpty(), - "Expected returned map to be empty"); - } - - private static Properties propertiesOf(Map entries) { - Properties properties = new Properties(); - properties.putAll(entries); - return properties; - } - - public void testNonMatchingCredentials() { - Properties properties = propertiesOf(ImmutableMap.of("non_matching.identity", "v1", - "non_matching.credential", "v2")); - assertTrue(collector.apply(properties).isEmpty(), - "Expected returned map to be empty"); - } - - public void testIncompleteCredentials() { - Properties properties = propertiesOf(ImmutableMap.of("acme.identity", "v1", - "acme-2.credential", "v2")); - assertTrue(collector.apply(properties).isEmpty(), - "Expected returned map to be empty"); - } - - public void testCredentials() { - Properties properties = propertiesOf(ImmutableMap.of("acme.identity", "v1", - "acme.credential", "v2", "acme-2.identity", "v3", - "acme-2.credential", "v4")); - assertEquals(collector.apply(properties), - ImmutableMap.of("acme", new Credential("v1", "v2"), - "acme-2", new Credential("v3", "v4"))); - } -} \ No newline at end of file diff --git a/demos/tweetstore/heroku-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/AddTweetsControllerTest.java b/demos/tweetstore/heroku-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/AddTweetsControllerTest.java deleted file mode 100644 index ccdb667ef3..0000000000 --- a/demos/tweetstore/heroku-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/AddTweetsControllerTest.java +++ /dev/null @@ -1,78 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.controller; - -import static org.testng.Assert.assertEquals; - -import java.io.IOException; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ExecutionException; - -import org.jclouds.ContextBuilder; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.blobstore.TransientApiMetadata; -import org.jclouds.blobstore.domain.Blob; -import org.jclouds.demo.tweetstore.domain.StoredTweetStatus; -import org.jclouds.demo.tweetstore.functions.ServiceToStoredTweetStatuses; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.testng.annotations.Test; -import org.testng.collections.Maps; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableSet; - -/** - * Tests behavior of {@code AddTweetsController} - * - * @author Adrian Cole - */ -@Test(groups = "unit") -public class AddTweetsControllerTest { - - Map createServices(String container) throws InterruptedException, - ExecutionException { - Map services = Maps.newHashMap(); - TransientApiMetadata transientApiMetadata = TransientApiMetadata.builder().build(); - for (String name : new String[] { "1", "2" }) { - BlobStoreContext context = ContextBuilder.newBuilder(transientApiMetadata).build(BlobStoreContext.class); - context.getAsyncBlobStore().createContainerInLocation(null, container).get(); - Blob blob = context.getAsyncBlobStore().blobBuilder("1").build(); - blob.getMetadata().getUserMetadata().put(TweetStoreConstants.SENDER_NAME, "frank"); - blob.setPayload("I love beans!"); - context.getAsyncBlobStore().putBlob(container, blob).get(); - services.put(name, context); - } - return services; - } - - public void testStoreTweets() throws IOException, InterruptedException, ExecutionException { - String container = AddTweetsControllerTest.class.getName() + "#container"; - Map contexts = createServices(container); - - ServiceToStoredTweetStatuses function = new ServiceToStoredTweetStatuses(contexts, container); - AddTweetsController controller = new AddTweetsController(contexts, function); - List list = controller.apply(ImmutableSet.of("1", "2")); - assertEquals(list.size(), 2); - assertEquals(list, ImmutableList.of(new StoredTweetStatus("1", "localhost", container, "1", - "frank", "I love beans!", null), new StoredTweetStatus("2", "localhost", container, - "1", "frank", "I love beans!", null))); - - } -} diff --git a/demos/tweetstore/heroku-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/ClearTweetsControllerTest.java b/demos/tweetstore/heroku-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/ClearTweetsControllerTest.java deleted file mode 100644 index 81f0b9f3c7..0000000000 --- a/demos/tweetstore/heroku-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/ClearTweetsControllerTest.java +++ /dev/null @@ -1,72 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.controller; - -import static org.testng.Assert.assertEquals; - -import java.io.IOException; -import java.util.Map; -import java.util.concurrent.ExecutionException; - -import org.jclouds.ContextBuilder; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.blobstore.TransientApiMetadata; -import org.jclouds.blobstore.domain.Blob; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.testng.annotations.Test; - -import com.google.common.collect.ImmutableMap; - -/** - * Tests behavior of {@code AddTweetsController} - * - * @author Adrian Cole - */ -@Test(groups = "unit") -public class ClearTweetsControllerTest { - - Map createBlobStores(String container) throws InterruptedException, ExecutionException { - TransientApiMetadata transientApiMetadata = TransientApiMetadata.builder().build(); - Map contexts = ImmutableMap.of( - "test1", ContextBuilder.newBuilder(transientApiMetadata).build(BlobStoreContext.class), - "test2", ContextBuilder.newBuilder(transientApiMetadata).build(BlobStoreContext.class)); - for (BlobStoreContext blobstore : contexts.values()) { - blobstore.getBlobStore().createContainerInLocation(null, container); - Blob blob = blobstore.getAsyncBlobStore().blobBuilder("1").build(); - blob.getMetadata().getUserMetadata().put(TweetStoreConstants.SENDER_NAME, "frank"); - blob.setPayload("I love beans!"); - blobstore.getBlobStore().putBlob(container, blob); - } - return contexts; - } - - public void testClearTweets() throws IOException, InterruptedException, ExecutionException { - String container = ClearTweetsControllerTest.class.getName() + "#container"; - Map contexts = createBlobStores(container); - - ClearTweetsController controller = new ClearTweetsController(contexts, - container); - controller.clearContainer("test1"); - controller.clearContainer("test2"); - - for (BlobStoreContext context : contexts.values()) { - assertEquals(context.getBlobStore().countBlobs(container), 0, context.toString()); - } - } -} diff --git a/demos/tweetstore/heroku-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/EnqueueStoresControllerTest.java b/demos/tweetstore/heroku-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/EnqueueStoresControllerTest.java deleted file mode 100644 index 3c5e5b1d80..0000000000 --- a/demos/tweetstore/heroku-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/EnqueueStoresControllerTest.java +++ /dev/null @@ -1,85 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.controller; - -import static org.easymock.EasyMock.*; - -import java.net.URI; -import java.util.Map; - -import org.jclouds.ContextBuilder; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.blobstore.TransientApiMetadata; -import org.jclouds.demo.paas.RunnableHttpRequest; -import org.jclouds.demo.paas.RunnableHttpRequest.Factory; -import org.jclouds.demo.paas.service.taskqueue.TaskQueue; -import org.jclouds.http.HttpRequest; -import org.testng.annotations.Test; - -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableMultimap; - -/** - * Tests behavior of {@code EnqueueStoresController} - * - * @author Andrew Phillips - */ -@Test(groups = "unit") -public class EnqueueStoresControllerTest { - - Map createBlobStores() { - TransientApiMetadata transientApiMetadata = TransientApiMetadata.builder().build(); - Map contexts = ImmutableMap.of( - "test1", ContextBuilder.newBuilder(transientApiMetadata).build(BlobStoreContext.class), - "test2", ContextBuilder.newBuilder(transientApiMetadata).build(BlobStoreContext.class)); - return contexts; - } - - public void testEnqueueStores() { - Map stores = createBlobStores(); - TaskQueue taskQueue = createMock(TaskQueue.class); - Factory httpRequestFactory = createMock(Factory.class); - EnqueueStoresController function = new EnqueueStoresController(stores, - taskQueue, "http://localhost:8080"); - - expect(taskQueue.getHttpRequestFactory()).andStubReturn(httpRequestFactory); - - HttpRequest storeInTest1Request = HttpRequest.builder().endpoint( - URI.create("http://localhost:8080/store/do")) - .headers(ImmutableMultimap.of("context", "test1")).method("GET").build(); - RunnableHttpRequest storeInTest1Task = null; - expect(httpRequestFactory.create(eq(storeInTest1Request))).andReturn(storeInTest1Task); - - HttpRequest storeInTest2Request = HttpRequest.builder().endpoint( - URI.create("http://localhost:8080/store/do")) - .headers(ImmutableMultimap.of("context", "test2")).method("GET").build(); - RunnableHttpRequest storeInTest2Task = null; - expect(httpRequestFactory.create(eq(storeInTest2Request))).andReturn(storeInTest2Task); - - taskQueue.add(storeInTest1Task); - expectLastCall(); - taskQueue.add(storeInTest2Task); - expectLastCall(); - replay(httpRequestFactory, taskQueue); - - function.enqueueStoreTweetTasks(); - - verify(taskQueue); - } -} \ No newline at end of file diff --git a/demos/tweetstore/heroku-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/StoreTweetsControllerTest.java b/demos/tweetstore/heroku-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/StoreTweetsControllerTest.java deleted file mode 100644 index 66448df0c5..0000000000 --- a/demos/tweetstore/heroku-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/StoreTweetsControllerTest.java +++ /dev/null @@ -1,121 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.controller; - -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.verify; -import static org.testng.Assert.assertEquals; - -import java.io.IOException; -import java.util.Map; -import java.util.Map.Entry; -import java.util.concurrent.ExecutionException; - -import org.jclouds.ContextBuilder; -import org.jclouds.blobstore.BlobMap; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.blobstore.TransientApiMetadata; -import org.jclouds.blobstore.domain.Blob; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.jclouds.util.Strings2; -import org.testng.annotations.Test; - -import twitter4j.Status; -import twitter4j.Twitter; -import twitter4j.User; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; - -/** - * Tests behavior of {@code StoreTweetsController} - * - * @author Adrian Cole - */ -@Test(groups = "unit") -public class StoreTweetsControllerTest { - - Twitter createTwitter() { - return createMock(Twitter.class); - } - - Map createBlobStores(String container) throws InterruptedException, ExecutionException { - TransientApiMetadata transientApiMetadata = TransientApiMetadata.builder().build(); - Map contexts = ImmutableMap.of( - "test1", ContextBuilder.newBuilder(transientApiMetadata).build(BlobStoreContext.class), - "test2", ContextBuilder.newBuilder(transientApiMetadata).build(BlobStoreContext.class)); - for (BlobStoreContext blobstore : contexts.values()) { - blobstore.getAsyncBlobStore().createContainerInLocation(null, container).get(); - } - return contexts; - } - - public void testStoreTweets() throws IOException, InterruptedException, ExecutionException { - String container = StoreTweetsControllerTest.class.getName() + "#container"; - Map stores = createBlobStores(container); - StoreTweetsController function = new StoreTweetsController(stores, container, createTwitter()); - - User frank = createMock(User.class); - expect(frank.getScreenName()).andReturn("frank").atLeastOnce(); - - Status frankStatus = createMock(Status.class); - expect(frankStatus.getId()).andReturn(1l).atLeastOnce(); - expect(frankStatus.getUser()).andReturn(frank).atLeastOnce(); - expect(frankStatus.getText()).andReturn("I love beans!").atLeastOnce(); - - User jimmy = createMock(User.class); - expect(jimmy.getScreenName()).andReturn("jimmy").atLeastOnce(); - - Status jimmyStatus = createMock(Status.class); - expect(jimmyStatus.getId()).andReturn(2l).atLeastOnce(); - expect(jimmyStatus.getUser()).andReturn(jimmy).atLeastOnce(); - expect(jimmyStatus.getText()).andReturn("cloud is king").atLeastOnce(); - - replay(frank); - replay(frankStatus); - replay(jimmy); - replay(jimmyStatus); - - function.addMyTweets("test1", ImmutableList.of(frankStatus, jimmyStatus)); - function.addMyTweets("test2", ImmutableList.of(frankStatus, jimmyStatus)); - - verify(frank); - verify(frankStatus); - verify(jimmy); - verify(jimmyStatus); - - for (Entry entry : stores.entrySet()) { - BlobMap map = entry.getValue().createBlobMap(container); - Blob frankBlob = map.get("1"); - assertEquals(frankBlob.getMetadata().getName(), "1"); - assertEquals(frankBlob.getMetadata().getUserMetadata().get(TweetStoreConstants.SENDER_NAME), "frank"); - assertEquals(frankBlob.getMetadata().getContentMetadata().getContentType(), "text/plain"); - assertEquals(Strings2.toString(frankBlob.getPayload()), "I love beans!"); - - Blob jimmyBlob = map.get("2"); - assertEquals(jimmyBlob.getMetadata().getName(), "2"); - assertEquals(jimmyBlob.getMetadata().getUserMetadata().get(TweetStoreConstants.SENDER_NAME), "jimmy"); - assertEquals(jimmyBlob.getMetadata().getContentMetadata().getContentType(), "text/plain"); - assertEquals(Strings2.toString(jimmyBlob.getPayload()), "cloud is king"); - } - - } -} diff --git a/demos/tweetstore/heroku-tweetstore/src/test/java/org/jclouds/demo/tweetstore/functions/KeyToStoredTweetStatusTest.java b/demos/tweetstore/heroku-tweetstore/src/test/java/org/jclouds/demo/tweetstore/functions/KeyToStoredTweetStatusTest.java deleted file mode 100644 index 36981b398a..0000000000 --- a/demos/tweetstore/heroku-tweetstore/src/test/java/org/jclouds/demo/tweetstore/functions/KeyToStoredTweetStatusTest.java +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.functions; - -import static org.testng.Assert.assertEquals; - -import java.io.IOException; -import java.util.concurrent.ExecutionException; - -import org.jclouds.ContextBuilder; -import org.jclouds.blobstore.BlobMap; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.blobstore.TransientApiMetadata; -import org.jclouds.blobstore.domain.Blob; -import org.jclouds.demo.tweetstore.domain.StoredTweetStatus; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.testng.annotations.Test; - -/** - * Tests behavior of {@code KeyToStoredTweetStatus} - * - * @author Adrian Cole - */ -@Test(groups = "unit") -public class KeyToStoredTweetStatusTest { - - BlobMap createMap() throws InterruptedException, ExecutionException { - BlobStoreContext context = - ContextBuilder.newBuilder(TransientApiMetadata.builder().build()).build(BlobStoreContext.class); - String container = KeyToStoredTweetStatusTest.class.getName() + "#container"; - context.getBlobStore().createContainerInLocation(null, container); - return context.createBlobMap(container); - } - - public void testStoreTweets() throws IOException, InterruptedException, ExecutionException { - BlobMap map = createMap(); - Blob blob = map.blobBuilder().name("1").build(); - blob.getMetadata().getUserMetadata().put(TweetStoreConstants.SENDER_NAME, "frank"); - blob.setPayload("I love beans!"); - map.put("1", blob); - String host = "localhost"; - String service = "stub"; - String container = "tweetstore"; - - KeyToStoredTweetStatus function = new KeyToStoredTweetStatus(map, service, host, container); - StoredTweetStatus result = function.apply("1"); - - StoredTweetStatus expected = new StoredTweetStatus(service, host, container, "1", "frank", - "I love beans!", null); - - assertEquals(result, expected); - - } -} diff --git a/demos/tweetstore/heroku-tweetstore/src/test/java/org/jclouds/demo/tweetstore/functions/ServiceToStoredTweetStatusesTest.java b/demos/tweetstore/heroku-tweetstore/src/test/java/org/jclouds/demo/tweetstore/functions/ServiceToStoredTweetStatusesTest.java deleted file mode 100644 index 70fde3c119..0000000000 --- a/demos/tweetstore/heroku-tweetstore/src/test/java/org/jclouds/demo/tweetstore/functions/ServiceToStoredTweetStatusesTest.java +++ /dev/null @@ -1,75 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.functions; - -import static org.testng.Assert.assertEquals; - -import java.io.IOException; -import java.util.Map; -import java.util.concurrent.ExecutionException; - -import org.jclouds.ContextBuilder; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.blobstore.TransientApiMetadata; -import org.jclouds.blobstore.domain.Blob; -import org.jclouds.demo.tweetstore.domain.StoredTweetStatus; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.testng.annotations.Test; -import org.testng.collections.Maps; - -import com.google.common.collect.Iterables; - -/** - * Tests behavior of {@code ServiceToStoredTweetStatuses} - * - * @author Adrian Cole - */ -@Test(groups = "unit") -public class ServiceToStoredTweetStatusesTest { - - Map createServices(String container) throws InterruptedException, - ExecutionException { - Map services = Maps.newHashMap(); - TransientApiMetadata transientApiMetadata = TransientApiMetadata.builder().build(); - for (String name : new String[] { "1", "2" }) { - BlobStoreContext context = ContextBuilder.newBuilder(transientApiMetadata).build(BlobStoreContext.class); - context.getAsyncBlobStore().createContainerInLocation(null, container).get(); - Blob blob = context.getAsyncBlobStore().blobBuilder("1").build(); - blob.getMetadata().getUserMetadata().put(TweetStoreConstants.SENDER_NAME, "frank"); - blob.setPayload("I love beans!"); - context.getAsyncBlobStore().putBlob(container, blob).get(); - services.put(name, context); - } - return services; - } - - public void testStoreTweets() throws IOException, InterruptedException, ExecutionException { - String container = ServiceToStoredTweetStatusesTest.class.getName() + "#container"; - Map contexts = createServices(container); - - ServiceToStoredTweetStatuses function = new ServiceToStoredTweetStatuses(contexts, container); - - assertEquals(Iterables.getLast(function.apply("1")), new StoredTweetStatus("1", "localhost", - container, "1", "frank", "I love beans!", null)); - - assertEquals(Iterables.getLast(function.apply("2")), new StoredTweetStatus("2", "localhost", - container, "1", "frank", "I love beans!", null)); - - } -} diff --git a/demos/tweetstore/heroku-tweetstore/src/test/java/org/jclouds/demo/tweetstore/integration/JettyServer.java b/demos/tweetstore/heroku-tweetstore/src/test/java/org/jclouds/demo/tweetstore/integration/JettyServer.java deleted file mode 100644 index d358287781..0000000000 --- a/demos/tweetstore/heroku-tweetstore/src/test/java/org/jclouds/demo/tweetstore/integration/JettyServer.java +++ /dev/null @@ -1,68 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.integration; - -import static com.google.common.io.Closeables.closeQuietly; -import static java.lang.String.format; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Properties; -import java.util.concurrent.TimeUnit; - -import javax.servlet.ServletException; - -/** - * Basic functionality to start a local WAR-supporting Jetty instance. - * - * @author Andrew Phillips - */ -public class JettyServer { - protected Runner2 server; - - public void writePropertiesAndStartServer(final String port, final String warfile, - Properties props) throws IOException, InterruptedException, ServletException { - String filename = String.format( - "%1$s/WEB-INF/jclouds.properties", warfile); - System.err.println("file: " + filename); - storeProperties(filename, props); - assert new File(filename).exists(); - // Jetty uses SLF4J by default - System.setProperty("org.eclipse.jetty.util.log.class", "org.eclipse.jetty.util.log.JavaUtilLog"); - System.setProperty("java.util.logging.config.file", - format("%s/WEB-INF/logging.properties", warfile)); - server = Runner2.createRunner(new String[] { "--port", port, warfile }); - server.start(); - TimeUnit.SECONDS.sleep(30); - } - - private static void storeProperties(String filename, Properties props) throws IOException { - FileOutputStream targetFile = new FileOutputStream(filename); - try { - props.store(targetFile, "test"); - } finally { - closeQuietly(targetFile); - } - } - - public void stop() { - server.stop(); - } -} \ No newline at end of file diff --git a/demos/tweetstore/heroku-tweetstore/src/test/java/org/jclouds/demo/tweetstore/integration/Runner2.java b/demos/tweetstore/heroku-tweetstore/src/test/java/org/jclouds/demo/tweetstore/integration/Runner2.java deleted file mode 100644 index feb9e2c408..0000000000 --- a/demos/tweetstore/heroku-tweetstore/src/test/java/org/jclouds/demo/tweetstore/integration/Runner2.java +++ /dev/null @@ -1,72 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.integration; - -import javax.servlet.ServletException; - -import org.mortbay.jetty.runner.Runner; - -/** - * @see Runner - * @author Andrew Phillips - */ -class Runner2 extends Runner { - public static Runner2 createRunner(String[] args) throws ServletException { - Runner2 runner = new Runner2(); - try { - runner.configure(args); - } catch (Exception exception) { - throw new ServletException("Unable to configure runner", exception); - } - return runner; - } - - private final Thread serverThread; - - private Runner2() { - serverThread = new Thread(new Runnable() { - public void run() { - try { - Runner2.this.run(); - } catch (Exception exception) { - System.err.println("exception starting server: " + exception); - } - } - }); - } - - void start() throws ServletException { - Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { - public void run() { - stop(); - } - })); - serverThread.start(); - } - - void stop() { - try { - _server.stop(); - } catch (Exception exception) { - System.err.println("exception stopping server: " + exception); - } - serverThread.interrupt(); - } - -} diff --git a/demos/tweetstore/heroku-tweetstore/src/test/java/org/jclouds/demo/tweetstore/integration/TweetStoreLiveTest.java b/demos/tweetstore/heroku-tweetstore/src/test/java/org/jclouds/demo/tweetstore/integration/TweetStoreLiveTest.java deleted file mode 100644 index 71e483b44b..0000000000 --- a/demos/tweetstore/heroku-tweetstore/src/test/java/org/jclouds/demo/tweetstore/integration/TweetStoreLiveTest.java +++ /dev/null @@ -1,237 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.integration; - -import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.demo.paas.RunnableHttpRequest.PLATFORM_REQUEST_ORIGINATOR_HEADER; -import static org.jclouds.demo.tweetstore.reference.TweetStoreConstants.PROPERTY_TWEETSTORE_BLOBSTORES; -import static org.jclouds.demo.tweetstore.reference.TweetStoreConstants.PROPERTY_TWEETSTORE_CONTAINER; -import static org.jclouds.demo.tweetstore.reference.TwitterConstants.PROPERTY_TWITTER_ACCESSTOKEN; -import static org.jclouds.demo.tweetstore.reference.TwitterConstants.PROPERTY_TWITTER_ACCESSTOKEN_SECRET; -import static org.jclouds.demo.tweetstore.reference.TwitterConstants.PROPERTY_TWITTER_CONSUMER_KEY; -import static org.jclouds.demo.tweetstore.reference.TwitterConstants.PROPERTY_TWITTER_CONSUMER_SECRET; - -import java.io.IOException; -import java.io.InputStream; -import java.net.HttpURLConnection; -import java.net.URL; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Properties; -import java.util.Set; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeoutException; - -import org.jclouds.Context; -import org.jclouds.ContextBuilder; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.demo.tweetstore.controller.StoreTweetsController; -import org.jclouds.logging.log4j.config.Log4JLoggingModule; -import org.jclouds.rest.AuthorizationException; -import org.jclouds.util.Strings2; -import org.testng.annotations.AfterTest; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.Parameters; -import org.testng.annotations.Test; - -import twitter4j.ResponseList; -import twitter4j.Status; -import twitter4j.Twitter; -import twitter4j.TwitterException; -import twitter4j.TwitterFactory; -import twitter4j.conf.Configuration; -import twitter4j.conf.ConfigurationBuilder; - -import com.google.common.base.Splitter; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Maps; -import com.google.inject.Module; - -/** - * Starts up the RUN@cloud for Java Development environment and deploys an application which - * tests accesses twitter and blobstores. - * - * @author Andrew Phillips - */ -@Test(groups = "live", singleThreaded = true) -public class TweetStoreLiveTest { - - JettyServer server; - private URL url; - private Map contexts; - private String container; - private static final Iterable blobstores = - Splitter.on(',').split(getRequiredSystemProperty(PROPERTY_TWEETSTORE_BLOBSTORES)); - private static final Properties props = new Properties(); - - @BeforeTest - void clearAndCreateContainers() throws InterruptedException, ExecutionException, TimeoutException, IOException, - TwitterException { - container = getRequiredSystemProperty(PROPERTY_TWEETSTORE_CONTAINER); - - props.setProperty(PROPERTY_TWEETSTORE_CONTAINER, container); - - // put all identity/credential pairs into the client - addCredentialsForBlobStores(props); - - // example of an ad-hoc client configuration - addConfigurationForTwitter(props); - - // for testing, capture logs. - final Set wiring = ImmutableSet. of(new Log4JLoggingModule()); - this.contexts = Maps.newConcurrentMap(); - - for (String provider : blobstores) { - contexts.put(provider, ContextBuilder.newBuilder(provider) - .modules(wiring).overrides(props).build(BlobStoreContext.class)); - } - - Configuration conf = new ConfigurationBuilder() - .setOAuthConsumerKey(props.getProperty(PROPERTY_TWITTER_CONSUMER_KEY)) - .setOAuthConsumerSecret(props.getProperty(PROPERTY_TWITTER_CONSUMER_SECRET)) - .setOAuthAccessToken(props.getProperty(PROPERTY_TWITTER_ACCESSTOKEN)) - .setOAuthAccessTokenSecret(props.getProperty(PROPERTY_TWITTER_ACCESSTOKEN_SECRET)) - .build(); - Twitter client = new TwitterFactory(conf).getInstance(); - StoreTweetsController controller = new StoreTweetsController(contexts, container, client); - - ResponseList statuses = client.getMentions(); - - boolean deleted = false; - for (BlobStoreContext context : contexts.values()) { - try { - if (context.getBlobStore().containerExists(container)) { - System.err.printf("deleting container %s at %s%n", container, - context.unwrap(Context.class).getProviderMetadata().getEndpoint()); - context.getBlobStore().deleteContainer(container); - deleted = true; - } - } catch (AuthorizationException e) { - throw new AuthorizationException("for context: " + context, e); - } - } - if (deleted) { - System.err.println("sleeping 60 seconds to allow containers to clear"); - Thread.sleep(60000); - } - for (BlobStoreContext context : contexts.values()) { - System.err.printf("creating container %s at %s%n", container, - context.unwrap(Context.class).getProviderMetadata().getEndpoint()); - context.getBlobStore().createContainerInLocation(null, container); - } - - if (deleted) { - System.err.println("sleeping 5 seconds to allow containers to create"); - Thread.sleep(5000); - } - - for (Entry entry : contexts.entrySet()) { - System.err.printf("filling container %s at %s%n", container, entry.getKey()); - controller.addMyTweets(entry.getKey(), statuses); - } - } - - private static String getRequiredSystemProperty(String key) { - return checkNotNull(System.getProperty(key), key); - } - - private void addConfigurationForTwitter(Properties props) { - props.setProperty(PROPERTY_TWITTER_CONSUMER_KEY, - getRequiredSystemProperty("test." + PROPERTY_TWITTER_CONSUMER_KEY)); - props.setProperty(PROPERTY_TWITTER_CONSUMER_SECRET, - getRequiredSystemProperty("test." + PROPERTY_TWITTER_CONSUMER_SECRET)); - props.setProperty(PROPERTY_TWITTER_ACCESSTOKEN, - getRequiredSystemProperty("test." + PROPERTY_TWITTER_ACCESSTOKEN)); - props.setProperty(PROPERTY_TWITTER_ACCESSTOKEN_SECRET, - getRequiredSystemProperty("test." + PROPERTY_TWITTER_ACCESSTOKEN_SECRET)); - } - - private void addCredentialsForBlobStores(Properties props) { - for (String provider : blobstores) { - props.setProperty(provider + ".identity", - getRequiredSystemProperty("test." + provider + ".identity")); - props.setProperty(provider + ".credential", - getRequiredSystemProperty("test." + provider + ".credential")); - } - } - - @BeforeTest(dependsOnMethods = "clearAndCreateContainers") - @Parameters({ "warfile", "jetty.address", "jetty.port" }) - public void startDevAppServer(final String warfile, final String address, final String port) throws Exception { - url = new URL(String.format("http://%s:%s", address, port)); - - server = new JettyServer(); - server.writePropertiesAndStartServer(port, warfile, props); - } - - @Test - public void shouldPass() throws InterruptedException, IOException { - InputStream i = url.openStream(); - String string = Strings2.toStringAndClose(i); - assert string.indexOf("Welcome") >= 0 : string; - } - - @Test(dependsOnMethods = "shouldPass", expectedExceptions = IOException.class) - public void shouldFail() throws InterruptedException, IOException { - new URL(url, "/store/do").openStream(); - } - - @Test(dependsOnMethods = "shouldFail") - public void testPrimeContainers() throws IOException, InterruptedException { - URL gurl = new URL(url, "/store/do"); - - for (String context : blobstores) { - System.out.println("storing at context: " + context); - HttpURLConnection connection = (HttpURLConnection) gurl.openConnection(); - connection.addRequestProperty(PLATFORM_REQUEST_ORIGINATOR_HEADER, "taskqueue-twitter"); - connection.addRequestProperty("context", context); - InputStream i = connection.getInputStream(); - String string = Strings2.toStringAndClose(i); - assert string.indexOf("Done!") >= 0 : string; - connection.disconnect(); - } - - System.err.println("sleeping 20 seconds to allow for eventual consistency delay"); - Thread.sleep(20000); - for (BlobStoreContext context : contexts.values()) { - assert context.createInputStreamMap(container).size() > 0 : context.unwrap(Context.class).getProviderMetadata().getEndpoint(); - } - } - - @Test(invocationCount = 5, dependsOnMethods = "testPrimeContainers") - public void testSerial() throws InterruptedException, IOException { - URL gurl = new URL(url, "/tweets/get"); - InputStream i = gurl.openStream(); - String string = Strings2.toStringAndClose(i); - assert string.indexOf("Tweets in Clouds") >= 0 : string; - } - - @Test(invocationCount = 10, dependsOnMethods = "testPrimeContainers", threadPoolSize = 3) - public void testParallel() throws InterruptedException, IOException { - URL gurl = new URL(url, "/tweets/get"); - InputStream i = gurl.openStream(); - String string = Strings2.toStringAndClose(i); - assert string.indexOf("Tweets in Clouds") >= 0 : string; - } - - @AfterTest - public void stopDevAppServer() throws Exception { - server.stop(); - } -} diff --git a/demos/tweetstore/heroku-tweetstore/src/test/java/org/jclouds/demo/tweetstore/integration/util/ObjectFields.java b/demos/tweetstore/heroku-tweetstore/src/test/java/org/jclouds/demo/tweetstore/integration/util/ObjectFields.java deleted file mode 100644 index cc7c696c55..0000000000 --- a/demos/tweetstore/heroku-tweetstore/src/test/java/org/jclouds/demo/tweetstore/integration/util/ObjectFields.java +++ /dev/null @@ -1,56 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.integration.util; - -import java.lang.reflect.Field; - -public class ObjectFields { - - public static Object valueOf(String fieldName, Object source) { - return valueOf(fieldName, source, source.getClass()); - } - - public static Object valueOf(String fieldName, Object source, - Class fieldDeclaringClass) { - try { - return getAccessibleField(fieldName, fieldDeclaringClass).get(source); - } catch (Exception exception) { - throw new IllegalArgumentException(exception); - } - } - - private static Field getAccessibleField(String name, Class declaringClass) throws SecurityException, NoSuchFieldException { - Field field = declaringClass.getDeclaredField(name); - field.setAccessible(true); - return field; - } - - public static void set(String fieldName, Object target, Object value) { - set(fieldName, target, value, target.getClass()); - } - - public static void set(String fieldName, Object target, Object value, - Class fieldDeclaringClass) { - try { - getAccessibleField(fieldName, fieldDeclaringClass).set(target, value); - } catch (Exception exception) { - throw new IllegalArgumentException(exception); - } - } -} diff --git a/demos/tweetstore/heroku-tweetstore/src/test/resources/log4j.xml b/demos/tweetstore/heroku-tweetstore/src/test/resources/log4j.xml deleted file mode 100644 index 2e5d01fb9e..0000000000 --- a/demos/tweetstore/heroku-tweetstore/src/test/resources/log4j.xml +++ /dev/null @@ -1,95 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/demos/tweetstore/pom.xml b/demos/tweetstore/pom.xml deleted file mode 100644 index 6662f30abf..0000000000 --- a/demos/tweetstore/pom.xml +++ /dev/null @@ -1,422 +0,0 @@ - - - - - jclouds-demos-project - org.jclouds - 1.5.0-SNAPSHOT - - 4.0.0 - jclouds-demos-tweetstore-project - pom - jclouds TweetStore demos project - - cf-tweetstore-spring - heroku-tweetstore - gae-tweetstore - gae-tweetstore-spring - runatcloud-tweetstore - rhcloud-tweetstore - - - - target/maven-shared-archive-resources - cloudonestorage,ninefold-storage - - - - - ${project.groupId} - jclouds-blobstore - ${project.version} - - - org.twitter4j - twitter4j-core - [2.2,) - - - ${project.groupId} - jclouds-blobstore - ${project.version} - test-jar - test - - - org.jclouds.provider - aws-s3 - ${project.version} - runtime - - - org.jclouds.provider - cloudfiles-us - ${project.version} - runtime - - - org.jclouds.provider - azureblob - ${project.version} - runtime - - - org.jclouds.provider - cloudonestorage - ${project.version} - runtime - - - org.jclouds.provider - ninefold-storage - ${project.version} - runtime - - - displaytag - displaytag - 1.2 - runtime - - - org.slf4j - slf4j-log4j12 - - - - - org.slf4j - slf4j-jdk14 - 1.5.6 - runtime - - - jstl - javax.servlet - 1.1.2 - runtime - - - standard - taglibs - 1.1.2 - runtime - - - javax.servlet - servlet-api - 2.5 - provided - - - - - ${project.artifactId} - - - maven-remote-resources-plugin - 1.2 - - - false - - - - maven-war-plugin - 2.1.1 - - - WEB-INF/web.xml - - - src/main/platform - WEB-INF - true - - - .gitignore - - - - ${remoteResourcesDirectory}/META-INF - META-INF - - - - - - com.ning.maven.plugins - maven-duplicate-finder-plugin - 1.0.3 - - - - - - - com.google.appengine - appengine-api-1.0-sdk - 1.6.5 - - - com.google.appengine - appengine-tools-sdk - 1.6.5 - test - - - - com.google - - - - - - - javax.annotation - jsr250-api - 1.0 - runtime - - - org.apache.tomcat - annotations-api - 6.0.32 - test - - - - javax.annotation - - - - - - - commons-beanutils - commons-beanutils - 1.7.0 - runtime - - - commons-collections - commons-collections - 3.1 - runtime - - - - org.apache.commons.collections - - - - - - - javax.servlet - servlet-api - 2.5 - provided - - - com.google.appengine - appengine-tools-sdk - 1.6.5 - test - - - org.apache.tomcat - servlet-api - 6.0.32 - test - - - org.mortbay.jetty - jetty-runner - 7.5.4.v20111024 - test - - - - javax.servlet - - - - javax/servlet/resources/XMLSchema.dtd - javax/servlet/resources/datatypes.dtd - javax/servlet/resources/j2ee_1_4.xsd - javax/servlet/resources/j2ee_web_services_client_1_1.xsd - javax/servlet/resources/javaee_5.xsd - javax/servlet/resources/javaee_web_services_client_1_2.xsd - javax/servlet/resources/jsp_2_0.xsd - javax/servlet/resources/jsp_2_1.xsd - javax/servlet/resources/web-app_2_2.dtd - javax/servlet/resources/web-app_2_3.dtd - javax/servlet/resources/web-app_2_4.xsd - javax/servlet/resources/web-app_2_5.xsd - javax/servlet/resources/xml.xsd - javax/servlet/LocalStrings.properties - javax/servlet/LocalStrings_fr.properties - javax/servlet/LocalStrings_ja.properties - javax/servlet/http/LocalStrings.properties - javax/servlet/http/LocalStrings_es.properties - javax/servlet/http/LocalStrings_fr.properties - javax/servlet/http/LocalStrings_ja.properties - - - - - - - org.apache.tomcat - catalina - 6.0.32 - test - - - org.apache.tomcat - jasper - 6.0.32 - test - - - - org.apache.AnnotationProcessor - org.apache.PeriodicEventListener - - - - - - - javax.servlet - jstl - 1.1.2 - runtime - - - taglibs - standard - 1.1.2 - runtime - - - org.mortbay.jetty - jetty-runner - 7.5.4.v20111024 - test - - - - javax.servlet.jsp.jstl - org.apache.taglibs - - - META-INF/c-1_0-rt.tld - META-INF/c-1_0.tld - META-INF/c.tld - META-INF/fmt-1_0-rt.tld - META-INF/fmt-1_0.tld - META-INF/fmt.tld - META-INF/fn.tld - META-INF/permittedTaglibs.tld - META-INF/scriptfree.tld - META-INF/sql-1_0-rt.tld - META-INF/sql-1_0.tld - META-INF/sql.tld - META-INF/x-1_0-rt.tld - META-INF/x-1_0.tld - META-INF/x.tld - org/apache/taglibs/standard/lang/jstl/Resources.properties - org/apache/taglibs/standard/lang/jstl/Resources_ja.properties - org/apache/taglibs/standard/resources/Resources.properties - org/apache/taglibs/standard/resources/Resources_ja.properties - - - - - - - - - - - deploy - - - - maven-remote-resources-plugin - 1.2 - - - false - - - - include-jclouds-properties - - process - - - - - ${project.groupId}:jclouds-demos-tweetstore-jclouds-properties:2-${tweetstore.instance} - - - - - - - maven-war-plugin - - - WEB-INF/web.xml - - - src/main/platform - WEB-INF - true - - - .gitignore - - - - ${remoteResourcesDirectory}/META-INF - META-INF - - - ${remoteResourcesDirectory} - WEB-INF - true - - jclouds.properties - - - - - - - - - - diff --git a/demos/tweetstore/rhcloud-tweetstore/README.txt b/demos/tweetstore/rhcloud-tweetstore/README.txt deleted file mode 100644 index 559859f1cb..0000000000 --- a/demos/tweetstore/rhcloud-tweetstore/README.txt +++ /dev/null @@ -1,41 +0,0 @@ -==== - Licensed to jclouds, Inc. (jclouds) under one or more - contributor license agreements. See the NOTICE file - distributed with this work for additional information - regarding copyright ownership. jclouds licenses this file - to you under the Apache License, Version 2.0 (the - "License"); you may not use this file except in compliance - with the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, - software distributed under the License is distributed on an - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - KIND, either express or implied. See the License for the - specific language governing permissions and limitations - under the License. -==== - -A guide to generating Twitter consumer keys and access tokens is at http://tinyurl.com/2fhebgb - -Please modify your maven settings.xml like below before attempting to run 'mvn -Plive install' - - - keys - - true - - - YOUR_ACCESS_KEY_ID - YOUR_SECRET_KEY - YOUR_USER - YOUR_HEX_KEY - YOUR_ACCOUNT - YOUR_BASE64_ENCODED_KEY - YOUR_TWITTER_CONSUMER_KEY - YOUR_TWITTER_CONSUMER_SECRET - YOUR_TWITTER_ACCESSTOKEN - YOUR_TWITTER_ACCESSTOKEN_SECRET - - \ No newline at end of file diff --git a/demos/tweetstore/rhcloud-tweetstore/pom.xml b/demos/tweetstore/rhcloud-tweetstore/pom.xml deleted file mode 100644 index 9bf5061fc5..0000000000 --- a/demos/tweetstore/rhcloud-tweetstore/pom.xml +++ /dev/null @@ -1,130 +0,0 @@ - - - - 4.0.0 - - org.jclouds - jclouds-demos-tweetstore-project - 1.5.0-SNAPSHOT - - jclouds-demo-rhcloud-tweetstore - war - jclouds TweetStore for OpenShift Express - jclouds TweetStore for RedHat's OpenShift Express using Guice for Dependency Injection - - - 7.0.2.Final - localhost - 8088 - jclouds-rhcloud-tweetstore - - - - - com.google.inject.extensions - guice-servlet - 3.0 - - - - - org.jboss.as - jboss-as-embedded - ${rhcloud.jboss.version} - test - - - - jboss-logmanager - org.jboss.logmanager - - - - - org.codehaus.plexus - plexus-archiver - 2.1.1 - test - - - - - - live - - - - maven-surefire-plugin - - - integration - integration-test - - test - - - - ${test.twitter.runatcloud-tweetstore.consumer.identity} - ${test.twitter.runatcloud-tweetstore.consumer.credential} - ${test.twitter.runatcloud-tweetstore.access.identity} - ${test.twitter.runatcloud-tweetstore.access.credential} - ${test.azureblob.identity} - ${test.azureblob.credential} - ${test.cloudfiles-us.identity} - ${test.cloudfiles-us.credential} - ${test.aws-s3.identity} - ${test.aws-s3.credential} - ${test.cloudonestorage.identity} - ${test.cloudonestorage.credential} - ${test.ninefold-storage.identity} - ${test.ninefold-storage.credential} - ${rhcloud.jboss.home} - ${test.jboss.address} - ${test.jboss.port} - ${jclouds.tweetstore.blobstores} - test.${jclouds.tweetstore.container} - ${project.build.directory}/rhcloud-jboss - ${project.basedir}/src/test/resources/jbossas7/configuration - ${project.build.directory}/${project.build.finalName} - - - ${test.jboss.address} - ${test.jboss.port} - - - - - - - - - - - deploy - - - rhcloud-tweetstore - - - - diff --git a/demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/paas/PlatformServices.java b/demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/paas/PlatformServices.java deleted file mode 100644 index c768b42611..0000000000 --- a/demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/paas/PlatformServices.java +++ /dev/null @@ -1,57 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.paas; - -import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.demo.paas.config.PlatformServicesInitializer.PLATFORM_SERVICES_ATTRIBUTE_NAME; - -import java.util.Map; - -import javax.servlet.ServletContext; - -import org.jclouds.demo.paas.service.taskqueue.TaskQueue; -import org.jclouds.javax.annotation.Nullable; - -import com.google.common.collect.ImmutableMap; - -/** - * @author Andrew Phillips - */ -public class PlatformServices { - protected final String baseUrl; - private ImmutableMap taskQueues; - - public PlatformServices(String baseUrl, Map taskQueues) { - this.baseUrl = baseUrl; - this.taskQueues = ImmutableMap.copyOf(taskQueues); - } - - public String getBaseUrl() { - return baseUrl; - } - - public @Nullable TaskQueue getTaskQueue(String name) { - return taskQueues.get(name); - } - - public static PlatformServices get(ServletContext context) { - return (PlatformServices) checkNotNull(context.getAttribute( - PLATFORM_SERVICES_ATTRIBUTE_NAME), PLATFORM_SERVICES_ATTRIBUTE_NAME); - } -} diff --git a/demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/paas/RunnableHttpRequest.java b/demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/paas/RunnableHttpRequest.java deleted file mode 100644 index ad72a1a58d..0000000000 --- a/demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/paas/RunnableHttpRequest.java +++ /dev/null @@ -1,126 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.paas; - -import static java.lang.String.format; - -import org.jclouds.http.HttpCommand; -import org.jclouds.http.HttpCommandExecutorService; -import org.jclouds.http.HttpRequest; - -import com.google.common.collect.ImmutableMultimap; -import com.google.common.collect.Multimap; - -public class RunnableHttpRequest implements Runnable { - public static final String PLATFORM_REQUEST_ORIGINATOR_HEADER = "X-Platform-Originator"; - - public static Factory factory(HttpCommandExecutorService httpClient) { - return factory(httpClient, format("%s@%d", Factory.class.getName(), System.currentTimeMillis())); - } - - public static Factory factory(HttpCommandExecutorService httpClient, String originator) { - return new Factory(httpClient, originator); - } - - public static class Factory { - protected final HttpCommandExecutorService httpClient; - protected final String originator; - - private Factory(HttpCommandExecutorService httpClient, String originator) { - this.httpClient = httpClient; - this.originator = originator; - } - - public RunnableHttpRequest create(HttpRequest request) { - HttpRequest requestWithSubmitter = request.toBuilder() - .headers(copyOfWithEntry(request.getHeaders(), - PLATFORM_REQUEST_ORIGINATOR_HEADER, originator)).build(); - return new RunnableHttpRequest(httpClient, requestWithSubmitter); - } - - private static Multimap copyOfWithEntry( - Multimap multimap, K k1, V v1) { - return ImmutableMultimap.builder().putAll(multimap).put(k1, v1).build(); - } - } - - private final HttpCommandExecutorService httpClient; - private final HttpRequest request; - - private RunnableHttpRequest(HttpCommandExecutorService httpClient, HttpRequest request) { - this.httpClient = httpClient; - this.request = request; - } - - @Override - public void run() { - httpClient.submit(new ImmutableHttpCommand(request)); - } - - private class ImmutableHttpCommand implements HttpCommand { - private final HttpRequest request; - - public ImmutableHttpCommand(HttpRequest request) { - this.request = request; - } - - @Override - public void setException(Exception exception) { - } - - @Override - public void setCurrentRequest(HttpRequest request) { - } - - @Override - public boolean isReplayable() { - return false; - } - - @Override - public int incrementRedirectCount() { - return 0; - } - - @Override - public int incrementFailureCount() { - return 0; - } - - @Override - public int getRedirectCount() { - return 0; - } - - @Override - public int getFailureCount() { - return 0; - } - - @Override - public Exception getException() { - return null; - } - - @Override - public HttpRequest getCurrentRequest() { - return request; - } - } -} diff --git a/demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/paas/config/HttpClientModule.java b/demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/paas/config/HttpClientModule.java deleted file mode 100644 index 5aa077b6cd..0000000000 --- a/demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/paas/config/HttpClientModule.java +++ /dev/null @@ -1,65 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.paas.config; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.inject.name.Names.bindProperties; -import static org.jclouds.Constants.*; - -import java.util.Properties; - -import javax.servlet.ServletContext; -import javax.ws.rs.core.UriBuilder; - -import org.jclouds.demo.tweetstore.config.util.PropertiesLoader; - -import com.google.inject.AbstractModule; -import com.sun.jersey.api.uri.UriBuilderImpl; - -/** - * @author Andrew Phillips - */ -public class HttpClientModule extends AbstractModule { - private final ServletContext context; - - HttpClientModule(ServletContext context) { - this.context = context; - } - - @Override - protected void configure() { - // URL connection defaults - Properties toBind = defaultProperties(); - toBind.putAll(checkNotNull(new PropertiesLoader(context).get(), "properties")); - toBind.putAll(System.getProperties()); - bindProperties(binder(), toBind); - bind(UriBuilder.class).to(UriBuilderImpl.class); - } - - private static Properties defaultProperties() { - Properties props = new Properties(); - props.setProperty(PROPERTY_MAX_CONNECTIONS_PER_CONTEXT, 20 + ""); - props.setProperty(PROPERTY_MAX_CONNECTIONS_PER_HOST, 0 + ""); - props.setProperty(PROPERTY_SO_TIMEOUT, 60000 + ""); - props.setProperty(PROPERTY_CONNECTION_TIMEOUT, 60000 + ""); - props.setProperty(PROPERTY_USER_THREADS, 0 + ""); - props.setProperty(PROPERTY_IO_WORKER_THREADS, 20 + ""); - return props; - } -} diff --git a/demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/paas/config/PlatformServicesInitializer.java b/demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/paas/config/PlatformServicesInitializer.java deleted file mode 100644 index fd70aaa688..0000000000 --- a/demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/paas/config/PlatformServicesInitializer.java +++ /dev/null @@ -1,87 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.paas.config; - -import static com.google.common.base.Preconditions.checkNotNull; -import static java.lang.String.format; -import static java.util.concurrent.TimeUnit.SECONDS; - -import javax.servlet.ServletContext; -import javax.servlet.ServletContextEvent; -import javax.servlet.ServletContextListener; - -import org.jclouds.concurrent.config.ExecutorServiceModule; -import org.jclouds.demo.paas.PlatformServices; -import org.jclouds.demo.paas.service.taskqueue.TaskQueue; -import org.jclouds.http.HttpCommandExecutorService; -import org.jclouds.http.config.JavaUrlHttpCommandExecutorServiceModule; - -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableMap.Builder; -import com.google.inject.Guice; - -/** - * @author Andrew Phillips - */ -public class PlatformServicesInitializer implements ServletContextListener { - public static final String PLATFORM_SERVICES_ATTRIBUTE_NAME = PlatformServices.class.getName(); - - // from .openshift/config/standalone.xml - protected static final String HOST_VARIABLE = "OPENSHIFT_INTERNAL_IP"; - protected static final String PORT_VARIABLE = "OPENSHIFT_INTERNAL_PORT"; - - @Override - public void contextInitialized(ServletContextEvent contextEvent) { - ServletContext context = contextEvent.getServletContext(); - context.setAttribute(PLATFORM_SERVICES_ATTRIBUTE_NAME, createServices(context)); - } - - protected static PlatformServices createServices(ServletContext context) { - HttpCommandExecutorService httpClient = createHttpClient(context); - return new PlatformServices(getBaseUrl(context), createTaskQueues(httpClient)); - } - - protected static HttpCommandExecutorService createHttpClient( - final ServletContext context) { - return Guice.createInjector(new ExecutorServiceModule(), - new JavaUrlHttpCommandExecutorServiceModule(), - new HttpClientModule(context)) - .getInstance(HttpCommandExecutorService.class); - } - - protected static String getBaseUrl(ServletContext context) { - return format("http://%s:%s%s", checkNotNull(System.getenv(HOST_VARIABLE), HOST_VARIABLE), - checkNotNull(System.getenv(PORT_VARIABLE), PORT_VARIABLE), context.getContextPath()); - } - - // TODO: make the number and names of queues configurable - protected static ImmutableMap createTaskQueues(HttpCommandExecutorService httpClient) { - Builder taskQueues = ImmutableMap.builder(); - taskQueues.put("twitter", TaskQueue.builder(httpClient) - .name("twitter").period(SECONDS.toMillis(30)) - .build()); - return taskQueues.build(); - } - - @Override - public void contextDestroyed(ServletContextEvent servletContextEvent) { - ServletContext context = servletContextEvent.getServletContext(); - context.removeAttribute(PLATFORM_SERVICES_ATTRIBUTE_NAME); - } -} diff --git a/demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/paas/service/taskqueue/TaskQueue.java b/demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/paas/service/taskqueue/TaskQueue.java deleted file mode 100644 index e317a305cf..0000000000 --- a/demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/paas/service/taskqueue/TaskQueue.java +++ /dev/null @@ -1,107 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.paas.service.taskqueue; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; -import static java.lang.String.format; - -import java.util.Timer; -import java.util.TimerTask; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.TimeUnit; - -import org.jclouds.demo.paas.RunnableHttpRequest; -import org.jclouds.demo.paas.RunnableHttpRequest.Factory; -import org.jclouds.http.HttpCommandExecutorService; - -import com.google.inject.Provider; - -public class TaskQueue { - protected final Factory httpRequestFactory; - private final Timer timer; - private final ConcurrentLinkedQueue tasks = new ConcurrentLinkedQueue(); - - private TaskQueue(String name, long pollingIntervalMillis, Factory httpRequestFactory) { - this.httpRequestFactory = httpRequestFactory; - timer = new Timer(name); - timer.scheduleAtFixedRate(new TimerTask() { - @Override - public void run() { - Runnable task = tasks.poll(); - if (task != null) { - task.run(); - } - } - }, 0, pollingIntervalMillis); - } - - public void add(final Runnable task) { - tasks.add(task); - } - - public Factory getHttpRequestFactory() { - return httpRequestFactory; - } - - public void destroy() { - timer.cancel(); - tasks.clear(); - } - - public static Builder builder(HttpCommandExecutorService httpClient) { - return new Builder(httpClient); - } - - public static class Builder implements Provider { - protected final HttpCommandExecutorService httpClient; - protected String name = "default"; - protected long pollingIntervalMillis = TimeUnit.SECONDS.toMillis(1); - - private Builder(HttpCommandExecutorService httpClient) { - this.httpClient = checkNotNull(httpClient, "httpClient"); - } - - public Builder name(String name) { - this.name = checkNotNull(name, "name"); - return this; - } - - public Builder period(TimeUnit period) { - this.pollingIntervalMillis = checkNotNull(period, "period").toMillis(1); - return this; - } - - public Builder period(long pollingIntervalMillis) { - checkArgument(pollingIntervalMillis > 0, "pollingIntervalMillis"); - this.pollingIntervalMillis = pollingIntervalMillis; - return this; - } - - public TaskQueue build() { - return new TaskQueue(name, pollingIntervalMillis, - RunnableHttpRequest.factory(httpClient, format("taskqueue-%s", name))); - } - - @Override - public TaskQueue get() { - return build(); - } - } -} \ No newline at end of file diff --git a/demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/config/GuiceServletConfig.java b/demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/config/GuiceServletConfig.java deleted file mode 100644 index c03434388a..0000000000 --- a/demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/config/GuiceServletConfig.java +++ /dev/null @@ -1,155 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.config; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Preconditions.checkState; -import static com.google.common.base.Predicates.in; -import static com.google.common.collect.ImmutableSet.copyOf; -import static com.google.common.collect.Sets.filter; -import static org.jclouds.demo.paas.reference.PaasConstants.PROPERTY_PLATFORM_BASE_URL; -import static org.jclouds.demo.tweetstore.reference.TweetStoreConstants.PROPERTY_TWEETSTORE_BLOBSTORES; -import static org.jclouds.demo.tweetstore.reference.TweetStoreConstants.PROPERTY_TWEETSTORE_CONTAINER; -import static org.jclouds.demo.tweetstore.reference.TwitterConstants.PROPERTY_TWITTER_ACCESSTOKEN; -import static org.jclouds.demo.tweetstore.reference.TwitterConstants.PROPERTY_TWITTER_ACCESSTOKEN_SECRET; -import static org.jclouds.demo.tweetstore.reference.TwitterConstants.PROPERTY_TWITTER_CONSUMER_KEY; -import static org.jclouds.demo.tweetstore.reference.TwitterConstants.PROPERTY_TWITTER_CONSUMER_SECRET; - -import java.util.Map; -import java.util.Properties; -import java.util.Set; - -import javax.servlet.ServletContext; -import javax.servlet.ServletContextEvent; - -import org.jclouds.ContextBuilder; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.demo.paas.PlatformServices; -import org.jclouds.demo.paas.service.taskqueue.TaskQueue; -import org.jclouds.demo.tweetstore.config.util.CredentialsCollector; -import org.jclouds.demo.tweetstore.config.util.PropertiesLoader; -import org.jclouds.demo.tweetstore.controller.AddTweetsController; -import org.jclouds.demo.tweetstore.controller.ClearTweetsController; -import org.jclouds.demo.tweetstore.controller.EnqueueStoresController; -import org.jclouds.demo.tweetstore.controller.StoreTweetsController; - -import twitter4j.Twitter; -import twitter4j.TwitterFactory; -import twitter4j.conf.Configuration; -import twitter4j.conf.ConfigurationBuilder; - -import com.google.common.base.Splitter; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Maps; -import com.google.inject.Guice; -import com.google.inject.Injector; -import com.google.inject.Module; -import com.google.inject.TypeLiteral; -import com.google.inject.name.Names; -import com.google.inject.servlet.GuiceServletContextListener; -import com.google.inject.servlet.ServletModule; - -/** - * Setup Logging and create Injector for use in testing S3. - * - * @author Adrian Cole - */ -public class GuiceServletConfig extends GuiceServletContextListener { - private Map providerTypeToBlobStoreMap; - private Twitter twitterClient; - private String container; - private TaskQueue queue; - private String baseUrl; - - @Override - public void contextInitialized(ServletContextEvent servletContextEvent) { - ServletContext servletContext = servletContextEvent.getServletContext(); - - Properties props = new PropertiesLoader(servletContext).get(); - Set modules = ImmutableSet.of(); - // shared across all blobstores and used to retrieve tweets - try { - Configuration twitterConf = new ConfigurationBuilder() - .setOAuthConsumerKey(props.getProperty(PROPERTY_TWITTER_CONSUMER_KEY)) - .setOAuthConsumerSecret(props.getProperty(PROPERTY_TWITTER_CONSUMER_SECRET)) - .setOAuthAccessToken(props.getProperty(PROPERTY_TWITTER_ACCESSTOKEN)) - .setOAuthAccessTokenSecret(props.getProperty(PROPERTY_TWITTER_ACCESSTOKEN_SECRET)) - .build(); - twitterClient = new TwitterFactory(twitterConf).getInstance(); - } catch (IllegalArgumentException e) { - throw new IllegalArgumentException("properties for twitter not configured properly in " + props.toString(), e); - } - // common namespace for storing tweets - container = checkNotNull(props.getProperty(PROPERTY_TWEETSTORE_CONTAINER), PROPERTY_TWEETSTORE_CONTAINER); - - // instantiate and store references to all blobstores by provider name - providerTypeToBlobStoreMap = Maps.newHashMap(); - for (String hint : getBlobstoreContexts(props)) { - providerTypeToBlobStoreMap.put(hint, ContextBuilder.newBuilder(hint) - .modules(modules).overrides(props).build(BlobStoreContext.class)); - } - - // get a queue for submitting store tweet requests and the application's base URL - PlatformServices platform = PlatformServices.get(servletContext); - queue = platform.getTaskQueue("twitter"); - baseUrl = platform.getBaseUrl(); - - super.contextInitialized(servletContextEvent); - } - - private static Iterable getBlobstoreContexts(Properties props) { - Set contexts = new CredentialsCollector().apply(props).keySet(); - String explicitContexts = props.getProperty(PROPERTY_TWEETSTORE_BLOBSTORES); - if (explicitContexts != null) { - contexts = filter(contexts, in(copyOf(Splitter.on(',').split(explicitContexts)))); - } - checkState(!contexts.isEmpty(), "no credentials available for any requested context"); - return contexts; - } - - @Override - protected Injector getInjector() { - return Guice.createInjector(new ServletModule() { - @Override - protected void configureServlets() { - bind(new TypeLiteral>() {}) - .toInstance(providerTypeToBlobStoreMap); - bind(Twitter.class).toInstance(twitterClient); - bind(TaskQueue.class).toInstance(queue); - bindConstant().annotatedWith(Names.named(PROPERTY_PLATFORM_BASE_URL)) - .to(baseUrl); - bindConstant().annotatedWith(Names.named(PROPERTY_TWEETSTORE_CONTAINER)) - .to(container); - serve("/store/*").with(StoreTweetsController.class); - serve("/tweets/*").with(AddTweetsController.class); - serve("/stores/*").with(EnqueueStoresController.class); - serve("/clear/*").with(ClearTweetsController.class); - } - }); - } - - @Override - public void contextDestroyed(ServletContextEvent servletContextEvent) { - for (BlobStoreContext context : providerTypeToBlobStoreMap.values()) { - context.close(); - } - queue.destroy(); - super.contextDestroyed(servletContextEvent); - } -} \ No newline at end of file diff --git a/demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/config/util/CredentialsCollector.java b/demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/config/util/CredentialsCollector.java deleted file mode 100644 index ce3943376e..0000000000 --- a/demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/config/util/CredentialsCollector.java +++ /dev/null @@ -1,153 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.config.util; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Preconditions.checkState; -import static com.google.common.base.Predicates.notNull; -import static com.google.common.collect.Collections2.filter; -import static com.google.common.collect.Collections2.transform; -import static com.google.common.collect.ImmutableSet.copyOf; -import static com.google.common.collect.Maps.filterValues; -import static org.jclouds.util.Maps2.fromKeys; - -import java.util.Collection; -import java.util.Map; -import java.util.Properties; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.jclouds.demo.tweetstore.config.util.CredentialsCollector.Credential; - -import com.google.common.annotations.GwtIncompatible; -import com.google.common.base.Function; -import com.google.common.base.Predicate; - -/** - * Reads provider credentials from a {@link Properties} bag. - * - * @author Andrew Phillips - * - */ -public class CredentialsCollector implements Function> { - private static final String IDENTITY_PROPERTY_SUFFIX = ".identity"; - private static final String CREDENTIAL_PROPERTY_SUFFIX = ".credential"; - - // using the identity for provider name extraction - private static final Pattern IDENTITY_PROPERTY_PATTERN = - Pattern.compile("([a-zA-Z0-9-]+)" + Pattern.quote(IDENTITY_PROPERTY_SUFFIX)); - - @Override - public Map apply(final Properties properties) { - Collection providerNames = transform( - filter(properties.stringPropertyNames(), MatchesPattern.matches(IDENTITY_PROPERTY_PATTERN)), - new Function() { - @Override - public String apply(String input) { - Matcher matcher = IDENTITY_PROPERTY_PATTERN.matcher(input); - // as a side-effect, sets the matching group! - checkState(matcher.matches(), "'%s' should match '%s'", input, IDENTITY_PROPERTY_PATTERN); - return matcher.group(1); - } - }); - /* - * Providers without a credential property result in null values, which are - * removed from the returned map. - */ - return filterValues(fromKeys(copyOf(providerNames), new Function() { - @Override - public Credential apply(String providerName) { - String identity = properties.getProperty(providerName + IDENTITY_PROPERTY_SUFFIX); - String credential = properties.getProperty(providerName + CREDENTIAL_PROPERTY_SUFFIX); - return (((identity != null) && (credential != null)) - ? new Credential(identity, credential) - : null); - } - }), notNull()); - } - - public static class Credential { - private final String identity; - private final String credential; - - public Credential(String identity, String credential) { - this.identity = checkNotNull(identity, "identity"); - this.credential = checkNotNull(credential, "credential"); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result - + ((credential == null) ? 0 : credential.hashCode()); - result = prime * result - + ((identity == null) ? 0 : identity.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Credential other = (Credential) obj; - if (credential == null) { - if (other.credential != null) - return false; - } else if (!credential.equals(other.credential)) - return false; - if (identity == null) { - if (other.identity != null) - return false; - } else if (!identity.equals(other.identity)) - return false; - return true; - } - - public String getIdentity() { - return identity; - } - - public String getCredential() { - return credential; - } - } - - @GwtIncompatible(value = "java.util.regex.Pattern") - private static class MatchesPattern implements Predicate { - private final Pattern pattern; - - private MatchesPattern(Pattern pattern) { - this.pattern = pattern; - } - - @Override - public boolean apply(String input) { - return pattern.matcher(input).matches(); - } - - private static MatchesPattern matches(Pattern pattern) { - return new MatchesPattern(pattern); - } - } -} diff --git a/demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/config/util/PropertiesLoader.java b/demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/config/util/PropertiesLoader.java deleted file mode 100644 index dafa5c311b..0000000000 --- a/demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/config/util/PropertiesLoader.java +++ /dev/null @@ -1,59 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.config.util; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; - -import javax.servlet.ServletContext; - -import com.google.common.io.Closeables; -import com.google.inject.Provider; - -/** - * @author Andrew Phillips - */ -public class PropertiesLoader implements Provider{ - private static final String PROPERTIES_FILE = "/WEB-INF/jclouds.properties"; - - private final Properties properties; - - public PropertiesLoader(ServletContext context) { - properties = loadJcloudsProperties(context); - } - - private static Properties loadJcloudsProperties(ServletContext context) { - InputStream input = context.getResourceAsStream(PROPERTIES_FILE); - Properties props = new Properties(); - try { - props.load(input); - } catch (IOException e) { - throw new RuntimeException(e); - } finally { - Closeables.closeQuietly(input); - } - return props; - } - - @Override - public Properties get() { - return properties; - } -} diff --git a/demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/controller/AddTweetsController.java b/demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/controller/AddTweetsController.java deleted file mode 100644 index 007fbafdef..0000000000 --- a/demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/controller/AddTweetsController.java +++ /dev/null @@ -1,96 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.controller; - -import java.io.IOException; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeoutException; - -import javax.annotation.Resource; -import javax.inject.Inject; -import javax.inject.Singleton; -import javax.servlet.RequestDispatcher; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.demo.tweetstore.domain.StoredTweetStatus; -import org.jclouds.demo.tweetstore.functions.ServiceToStoredTweetStatuses; -import org.jclouds.logging.Logger; - -import com.google.common.base.Function; -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; - -/** - * Shows an example of how to use @{link BlobStoreContext} injected with Guice. - * - * @author Adrian Cole - */ -@Singleton -public class AddTweetsController extends HttpServlet implements - Function, List> { - - /** The serialVersionUID */ - private static final long serialVersionUID = 3888348023150822683L; - private final Map contexts; - private final ServiceToStoredTweetStatuses blobStoreContextToContainerResult; - - @Resource - protected Logger logger = Logger.NULL; - - @Inject - AddTweetsController(Map contexts, - ServiceToStoredTweetStatuses blobStoreContextToContainerResult) { - this.contexts = contexts; - this.blobStoreContextToContainerResult = blobStoreContextToContainerResult; - } - - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - try { - addMyTweetsToRequest(request); - RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/tweets.jsp"); - dispatcher.forward(request, response); - } catch (Exception e) { - logger.error(e, "Error listing containers"); - throw new ServletException(e); - } - } - - void addMyTweetsToRequest(HttpServletRequest request) throws InterruptedException, - ExecutionException, TimeoutException { - request.setAttribute("tweets", apply(contexts.keySet())); - } - - public List apply(Set in) { - List statuses = Lists.newArrayList(); - for (Iterable list : Iterables.transform(in, - blobStoreContextToContainerResult)) { - Iterables.addAll(statuses, list); - } - return statuses; - } -} diff --git a/demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/controller/ClearTweetsController.java b/demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/controller/ClearTweetsController.java deleted file mode 100644 index e08cfbc19e..0000000000 --- a/demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/controller/ClearTweetsController.java +++ /dev/null @@ -1,96 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.controller; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Strings.nullToEmpty; - -import java.io.IOException; -import java.util.Map; - -import javax.annotation.Resource; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.core.MediaType; - -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.jclouds.logging.Logger; - -import com.google.common.annotations.VisibleForTesting; - -/** - * Grab tweets related to me and store them into blobstores - * - * @author Adrian Cole - */ -@Singleton -public class ClearTweetsController extends HttpServlet { - /** The serialVersionUID */ - private static final long serialVersionUID = 7215420527854203714L; - - private final Map contexts; - private final String container; - - @Resource - protected Logger logger = Logger.NULL; - - @Inject - @VisibleForTesting - public ClearTweetsController(Map contexts, - @Named(TweetStoreConstants.PROPERTY_TWEETSTORE_CONTAINER) String container) { - this.container = container; - this.contexts = contexts; - } - - @VisibleForTesting - public void clearContainer(String contextName) { - BlobStoreContext context = checkNotNull(contexts.get(contextName), - "no context for %s in %s", contextName, contexts.keySet()); - try { - context.getBlobStore().clearContainer(container); - } catch (Exception e) { - logger.error(e, "Error clearing tweets in %s/%s", container, context); - } - } - - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - if (nullToEmpty(request.getHeader("X-Originator")).equals("admin")) { - try { - String contextName = checkNotNull(request.getHeader("context"), "missing header context"); - logger.info("clearing tweets in %s/%s", container, contextName); - clearContainer(contextName); - logger.debug("done clearing tweets"); - response.setContentType(MediaType.TEXT_PLAIN); - response.getWriter().println("Done!"); - } catch (Exception e) { - logger.error(e, "Error clearing tweets"); - throw new ServletException(e); - } - } else { - response.sendError(401); - } - } -} \ No newline at end of file diff --git a/demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/controller/EnqueueStoresController.java b/demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/controller/EnqueueStoresController.java deleted file mode 100644 index 937766c460..0000000000 --- a/demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/controller/EnqueueStoresController.java +++ /dev/null @@ -1,100 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.controller; - -import static com.google.common.base.Strings.nullToEmpty; - -import java.io.IOException; -import java.net.URI; -import java.util.Map; -import java.util.Set; - -import javax.annotation.Resource; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.core.MediaType; - -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.demo.paas.reference.PaasConstants; -import org.jclouds.demo.paas.service.taskqueue.TaskQueue; -import org.jclouds.http.HttpRequest; -import org.jclouds.logging.Logger; - -import com.google.common.annotations.VisibleForTesting; -import com.google.common.collect.ImmutableMultimap; - -/** - * Adds tasks to retrieve and store tweets in all registered contexts to an async - * task queue. - * - * @author Andrew Phillips - * @see StoreTweetsController - */ -@Singleton -public class EnqueueStoresController extends HttpServlet { - /** The serialVersionUID */ - private static final long serialVersionUID = 7215420527854203714L; - - private final Set contextNames; - private final TaskQueue taskQueue; - private final String baseUrl; - - @Resource - protected Logger logger = Logger.NULL; - - @Inject - public EnqueueStoresController(Map contexts, TaskQueue taskQueue, - @Named(PaasConstants.PROPERTY_PLATFORM_BASE_URL) String baseUrl) { - contextNames = contexts.keySet(); - this.taskQueue = taskQueue; - this.baseUrl = baseUrl; - } - - @VisibleForTesting - void enqueueStoreTweetTasks() { - for (String contextName : contextNames) { - logger.debug("enqueuing task to store tweets in blobstore '%s'", contextName); - taskQueue.add(taskQueue.getHttpRequestFactory().create(HttpRequest.builder() - .endpoint(URI.create(baseUrl + "/store/do")) - .headers(ImmutableMultimap.of("context", contextName)) - .method("GET").build())); - } - } - - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - if (!nullToEmpty(request.getHeader("X-Rhcloud-Cron")).equals("true")) { - response.sendError(401); - } - - try { - enqueueStoreTweetTasks(); - response.setContentType(MediaType.TEXT_PLAIN); - response.getWriter().println("Done!"); - } catch (Exception e) { - logger.error(e, "Error storing tweets"); - throw new ServletException(e); - } - } -} \ No newline at end of file diff --git a/demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/controller/StoreTweetsController.java b/demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/controller/StoreTweetsController.java deleted file mode 100644 index 948c9ff4ca..0000000000 --- a/demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/controller/StoreTweetsController.java +++ /dev/null @@ -1,130 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.controller; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Strings.nullToEmpty; -import static org.jclouds.demo.paas.RunnableHttpRequest.PLATFORM_REQUEST_ORIGINATOR_HEADER; - -import java.io.IOException; -import java.util.Map; - -import javax.annotation.Resource; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.core.MediaType; - -import org.jclouds.blobstore.BlobMap; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.blobstore.domain.Blob; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.jclouds.logging.Logger; -import org.jclouds.rest.AuthorizationException; - -import twitter4j.Status; -import twitter4j.Twitter; - -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Function; - -/** - * Grab tweets related to me and store them into blobstores - * - * @author Adrian Cole - */ -@Singleton -public class StoreTweetsController extends HttpServlet { - - private static final class StatusToBlob implements Function { - private final BlobMap map; - - private StatusToBlob(BlobMap map) { - this.map = map; - } - - public Blob apply(Status from) { - Blob to = map.blobBuilder().name(from.getId() + "").build(); - to.setPayload(from.getText()); - to.getPayload().getContentMetadata().setContentType(MediaType.TEXT_PLAIN); - to.getMetadata().getUserMetadata().put(TweetStoreConstants.SENDER_NAME, from.getUser().getScreenName()); - return to; - } - } - - /** The serialVersionUID */ - private static final long serialVersionUID = 7215420527854203714L; - - private final Map contexts; - private final Twitter client; - private final String container; - - @Resource - protected Logger logger = Logger.NULL; - - @Inject - @VisibleForTesting - public StoreTweetsController(Map contexts, - @Named(TweetStoreConstants.PROPERTY_TWEETSTORE_CONTAINER) String container, Twitter client) { - this.container = container; - this.contexts = contexts; - this.client = client; - } - - @VisibleForTesting - public void addMyTweets(String contextName, Iterable responseList) { - BlobStoreContext context = checkNotNull(contexts.get(contextName), "no context for " + contextName + " in " - + contexts.keySet()); - BlobMap map = context.createBlobMap(container); - for (Status status : responseList) { - Blob blob = null; - try { - blob = new StatusToBlob(map).apply(status); - map.put(status.getId() + "", blob); - } catch (AuthorizationException e) { - throw e; - } catch (Exception e) { - logger.error(e, "Error storing tweet %s (blob[%s]) on map %s/%s", status.getId(), blob, context, container); - } - } - } - - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - if (nullToEmpty(request.getHeader(PLATFORM_REQUEST_ORIGINATOR_HEADER)).equals("taskqueue-twitter")) { - try { - String contextName = checkNotNull(request.getHeader("context"), "missing header context"); - logger.info("retrieving tweets"); - addMyTweets(contextName, client.getMentions()); - logger.debug("done storing tweets"); - response.setContentType(MediaType.TEXT_PLAIN); - response.getWriter().println("Done!"); - } catch (Exception e) { - logger.error(e, "Error storing tweets"); - throw new ServletException(e); - } - } else { - response.sendError(401); - } - } -} \ No newline at end of file diff --git a/demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/domain/StoredTweetStatus.java b/demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/domain/StoredTweetStatus.java deleted file mode 100644 index 42ad65df01..0000000000 --- a/demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/domain/StoredTweetStatus.java +++ /dev/null @@ -1,149 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.domain; - -import java.io.Serializable; - -/** - * - * @author Adrian Cole - */ -public class StoredTweetStatus implements Comparable, Serializable { - - /** The serialVersionUID */ - private static final long serialVersionUID = -3257496189689220018L; - private final String service; - private final String host; - private final String container; - private final String id; - private final String from; - private final String tweet; - private final String status; - - @Override - public String toString() { - return "StoredTweetStatus [container=" + container + ", from=" + from + ", host=" + host - + ", id=" + id + ", service=" + service + ", status=" + status + ", tweet=" + tweet - + "]"; - } - - public StoredTweetStatus(String service, String host, String container, String id, String from, - String tweet, String status) { - this.service = service; - this.host = host; - this.container = container; - this.id = id; - this.from = from; - this.tweet = tweet; - this.status = status; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((container == null) ? 0 : container.hashCode()); - result = prime * result + ((from == null) ? 0 : from.hashCode()); - result = prime * result + ((host == null) ? 0 : host.hashCode()); - result = prime * result + ((id == null) ? 0 : id.hashCode()); - result = prime * result + ((service == null) ? 0 : service.hashCode()); - result = prime * result + ((tweet == null) ? 0 : tweet.hashCode()); - return result; - } - - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - StoredTweetStatus other = (StoredTweetStatus) obj; - if (container == null) { - if (other.container != null) - return false; - } else if (!container.equals(other.container)) - return false; - if (from == null) { - if (other.from != null) - return false; - } else if (!from.equals(other.from)) - return false; - if (host == null) { - if (other.host != null) - return false; - } else if (!host.equals(other.host)) - return false; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - if (service == null) { - if (other.service != null) - return false; - } else if (!service.equals(other.service)) - return false; - if (tweet == null) { - if (other.tweet != null) - return false; - } else if (!tweet.equals(other.tweet)) - return false; - return true; - } - - - public String getService() { - return service; - } - - public String getHost() { - return host; - } - - public String getContainer() { - return container; - } - - public String getFrom() { - return from; - } - - public String getTweet() { - return tweet; - } - - public String getStatus() { - return status; - } - - public int compareTo(StoredTweetStatus o) { - if (id == null) - return -1; - return (int) ((this == o) ? 0 : id.compareTo(o.id)); - } - - - public String getId() { - return id; - } - -} diff --git a/demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/functions/KeyToStoredTweetStatus.java b/demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/functions/KeyToStoredTweetStatus.java deleted file mode 100644 index f831b9780f..0000000000 --- a/demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/functions/KeyToStoredTweetStatus.java +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.functions; - -import javax.annotation.Resource; - -import org.jclouds.blobstore.BlobMap; -import org.jclouds.blobstore.domain.Blob; -import org.jclouds.demo.tweetstore.domain.StoredTweetStatus; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.jclouds.logging.Logger; -import org.jclouds.util.Strings2; - -import com.google.common.base.Function; - -/** - * - * @author Adrian Cole - */ -public class KeyToStoredTweetStatus implements Function { - private final String host; - private final BlobMap map; - private final String service; - private final String container; - - @Resource - protected Logger logger = Logger.NULL; - - KeyToStoredTweetStatus(BlobMap map, String service, String host, String container) { - this.host = host; - this.map = map; - this.service = service; - this.container = container; - } - - public StoredTweetStatus apply(String id) { - String status; - String from; - String tweet; - try { - long start = System.currentTimeMillis(); - Blob blob = map.get(id); - status = ((System.currentTimeMillis() - start) + "ms"); - from = blob.getMetadata().getUserMetadata().get(TweetStoreConstants.SENDER_NAME); - tweet = Strings2.toString(blob.getPayload()); - } catch (Exception e) { - logger.error(e, "Error listing container %s//%s/%s", service, container, id); - status = (e.getMessage()); - tweet = ""; - from = ""; - } - return new StoredTweetStatus(service, host, container, id, from, tweet, status); - } -} diff --git a/demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/functions/ServiceToStoredTweetStatuses.java b/demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/functions/ServiceToStoredTweetStatuses.java deleted file mode 100644 index b29ec14549..0000000000 --- a/demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/functions/ServiceToStoredTweetStatuses.java +++ /dev/null @@ -1,73 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.functions; - -import java.net.URI; -import java.util.Collections; -import java.util.Map; -import java.util.Set; - -import javax.annotation.Resource; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - -import org.jclouds.Context; -import org.jclouds.blobstore.BlobMap; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.demo.tweetstore.domain.StoredTweetStatus; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.jclouds.logging.Logger; - -import com.google.common.base.Function; -import com.google.common.collect.Iterables; - -@Singleton -public class ServiceToStoredTweetStatuses implements Function> { - - private final Map contexts; - private final String container; - - @Inject - public ServiceToStoredTweetStatuses(Map contexts, - @Named(TweetStoreConstants.PROPERTY_TWEETSTORE_CONTAINER) String container) { - this.contexts = contexts; - this.container = container; - } - - @Resource - protected Logger logger = Logger.NULL; - - public Iterable apply(String service) { - BlobStoreContext context = contexts.get(service); - String host = URI.create(context.unwrap(Context.class).getProviderMetadata().getEndpoint()).getHost(); - try { - BlobMap blobMap = context.createBlobMap(container); - Set blobs = blobMap.keySet(); - return Iterables.transform(blobs, new KeyToStoredTweetStatus(blobMap, service, host, - container)); - } catch (Exception e) { - StoredTweetStatus result = new StoredTweetStatus(service, host, container, null, null, - null, e.getMessage()); - logger.error(e, "Error listing service %s", service); - return Collections.singletonList(result); - } - - } -} \ No newline at end of file diff --git a/demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/reference/TweetStoreConstants.java b/demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/reference/TweetStoreConstants.java deleted file mode 100644 index 42ec480ae2..0000000000 --- a/demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/reference/TweetStoreConstants.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.reference; - -/** - * Configuration properties and constants used in TweetStore connections. - * - * @author Adrian Cole - */ -public interface TweetStoreConstants { - static final String PROPERTY_TWEETSTORE_BLOBSTORES = "jclouds.tweetstore.blobstores"; - static final String PROPERTY_TWEETSTORE_CONTAINER = "jclouds.tweetstore.container"; - /** - * Note that this has to conform to restrictions of all blobstores. for - * example, azure doesn't support periods. - */ - static final String SENDER_NAME = "sendername"; -} diff --git a/demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/reference/TwitterConstants.java b/demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/reference/TwitterConstants.java deleted file mode 100644 index dc8b97915f..0000000000 --- a/demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/reference/TwitterConstants.java +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.reference; - -/** - * Configuration properties and constants used in Twitter connections. - * - * @author Andrew Phillips - */ -public interface TwitterConstants { - static final String PROPERTY_TWITTER_CONSUMER_KEY = "twitter.consumer.identity"; - static final String PROPERTY_TWITTER_CONSUMER_SECRET = "twitter.consumer.credential"; - static final String PROPERTY_TWITTER_ACCESSTOKEN = "twitter.access.identity"; - static final String PROPERTY_TWITTER_ACCESSTOKEN_SECRET = "twitter.access.credential"; -} diff --git a/demos/tweetstore/rhcloud-tweetstore/src/main/platform/.gitignore b/demos/tweetstore/rhcloud-tweetstore/src/main/platform/.gitignore deleted file mode 100644 index 843dfe79c0..0000000000 --- a/demos/tweetstore/rhcloud-tweetstore/src/main/platform/.gitignore +++ /dev/null @@ -1 +0,0 @@ -# PaaS vendor specific files go in here \ No newline at end of file diff --git a/demos/tweetstore/rhcloud-tweetstore/src/main/webapp/WEB-INF/web.xml b/demos/tweetstore/rhcloud-tweetstore/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index 5bf6bdf0bb..0000000000 --- a/demos/tweetstore/rhcloud-tweetstore/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,51 +0,0 @@ - - - - jclouds-tweetstore - - - - guiceFilter - com.google.inject.servlet.GuiceFilter - - - - guiceFilter - /* - - - - - org.jclouds.demo.paas.config.PlatformServicesInitializer - - - - org.jclouds.demo.tweetstore.config.GuiceServletConfig - - - - index.jsp - - - \ No newline at end of file diff --git a/demos/tweetstore/rhcloud-tweetstore/src/main/webapp/images/openshift-logo.png b/demos/tweetstore/rhcloud-tweetstore/src/main/webapp/images/openshift-logo.png deleted file mode 100644 index fc0075f9d4..0000000000 Binary files a/demos/tweetstore/rhcloud-tweetstore/src/main/webapp/images/openshift-logo.png and /dev/null differ diff --git a/demos/tweetstore/rhcloud-tweetstore/src/main/webapp/index.jsp b/demos/tweetstore/rhcloud-tweetstore/src/main/webapp/index.jsp deleted file mode 100644 index 12101d3865..0000000000 --- a/demos/tweetstore/rhcloud-tweetstore/src/main/webapp/index.jsp +++ /dev/null @@ -1,30 +0,0 @@ -<%-- - - Licensed to jclouds, Inc. (jclouds) under one or more - contributor license agreements. See the NOTICE file - distributed with this work for additional information - regarding copyright ownership. jclouds licenses this file - to you under the Apache License, Version 2.0 (the - "License"); you may not use this file except in compliance - with the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, - software distributed under the License is distributed on an - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - KIND, either express or implied. See the License for the - specific language governing permissions and limitations - under the License. - ---%> - - -jclouds: anyweight cloudware for java - - -

Welcome!

-

Click here to see tweets about jclouds.

-

Powered by OpenShift Express

- - diff --git a/demos/tweetstore/rhcloud-tweetstore/src/main/webapp/tweets.jsp b/demos/tweetstore/rhcloud-tweetstore/src/main/webapp/tweets.jsp deleted file mode 100644 index bfdf462dde..0000000000 --- a/demos/tweetstore/rhcloud-tweetstore/src/main/webapp/tweets.jsp +++ /dev/null @@ -1,108 +0,0 @@ -<%-- - - Licensed to jclouds, Inc. (jclouds) under one or more - contributor license agreements. See the NOTICE file - distributed with this work for additional information - regarding copyright ownership. jclouds licenses this file - to you under the Apache License, Version 2.0 (the - "License"); you may not use this file except in compliance - with the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, - software distributed under the License is distributed on an - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - KIND, either express or implied. See the License for the - specific language governing permissions and limitations - under the License. - ---%> -<%@ page buffer="20kb"%> -<%@ taglib uri="http://displaytag.sf.net" prefix="display"%> - - -jclouds: anyweight cloudware for java - - - -

Tweets in Clouds

- - - - - - - -
-
- - - - - - - - -
-
Powered by OpenShift Express
- - diff --git a/demos/tweetstore/rhcloud-tweetstore/src/test/java/org/jboss/as/embedded/EmbeddedServerFactory2.java b/demos/tweetstore/rhcloud-tweetstore/src/test/java/org/jboss/as/embedded/EmbeddedServerFactory2.java deleted file mode 100644 index 8d5e3d69ab..0000000000 --- a/demos/tweetstore/rhcloud-tweetstore/src/test/java/org/jboss/as/embedded/EmbeddedServerFactory2.java +++ /dev/null @@ -1,96 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jboss.as.embedded; - -import java.io.File; -import java.util.Map; -import java.util.Properties; -import java.util.logging.LogManager; - -import org.jboss.modules.Module; -import org.jboss.modules.ModuleClassLoader; -import org.jboss.modules.ModuleIdentifier; -import org.jboss.modules.ModuleLoadException; -import org.jboss.modules.ModuleLoader; -import org.jboss.modules.log.JDKModuleLogger; -import org.jclouds.demo.tweetstore.integration.util.ObjectFields; - -/** - * A variant of {@link EmbeddedServerFactory} that resets JDK logging for JBoss, - * which requires its own settings in this area. - * - * Needs to be in the org.jboss.as.embedded package to be able to use - * {@code InitialModuleLoaderFactory}. - * - * @author Andrew Phillips - * @see EmbeddedServerFactory - */ -public class EmbeddedServerFactory2 { - - // mainly copied from EmbeddedServerFactory - public static StandaloneServer create(final File jbossHomeDir, final Properties systemProps, final Map systemEnv, String...systemPackages) { - if (jbossHomeDir == null || jbossHomeDir.isDirectory() == false) - throw new IllegalStateException("Invalid jboss.home.dir: " + jbossHomeDir); - - if (systemProps.getProperty(ServerEnvironment.HOME_DIR) == null) - systemProps.setProperty(ServerEnvironment.HOME_DIR, jbossHomeDir.getAbsolutePath()); - - File modulesDir = new File(jbossHomeDir + "/modules"); - final ModuleLoader moduleLoader = InitialModuleLoaderFactory.getModuleLoader(modulesDir, systemPackages); - - try { - Module.registerURLStreamHandlerFactoryModule(moduleLoader.loadModule(ModuleIdentifier.create("org.jboss.vfs"))); - - // Initialize the Logging system - ModuleIdentifier logModuleId = ModuleIdentifier.create("org.jboss.logmanager"); - ModuleClassLoader logModuleClassLoader = moduleLoader.loadModule(logModuleId).getClassLoader(); - try { - /* - * The original code simply sets the thread context classloader and lets LogManager - * load the class. This causes problems in tests because any other component that - * also happens to use JDK logging will have potentially loaded a *different* - * LogManager. - * If you force the JBoss LogManager to be loaded (by setting the 'java.util.logging.manager' - * system property) earlier in the test run, it will not be loaded by the correct - * classloader and cause ClassCastExceptions. - */ - LogManager jbossLogManager = (LogManager) logModuleClassLoader.loadClass("org.jboss.logmanager.LogManager").newInstance(); - ObjectFields.set("manager", null, jbossLogManager, LogManager.class); - ObjectFields.set("readPrimordialConfiguration", jbossLogManager, false, LogManager.class); - - if (LogManager.getLogManager().getClass() == LogManager.class) { - System.err.println("WARNING: Failed to load the specified logmodule " + logModuleId); - } else { - Module.setModuleLogger(new JDKModuleLogger()); - } - } catch (Exception exception) { - // copied from LogManager - System.err.println("Could not load Logmanager \"org.jboss.logmanager.LogManager\""); - exception.printStackTrace(); - } - - __redirected.__JAXPRedirected.changeAll(ModuleIdentifier.fromString("javax.xml.jaxp-provider"), moduleLoader); - - return EmbeddedServerFactory.create(moduleLoader, jbossHomeDir, systemProps, systemEnv); - } - catch (ModuleLoadException e) { - throw new RuntimeException(e); - } - } -} diff --git a/demos/tweetstore/rhcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/config/util/CredentialsCollectorTest.java b/demos/tweetstore/rhcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/config/util/CredentialsCollectorTest.java deleted file mode 100644 index 031bb199fc..0000000000 --- a/demos/tweetstore/rhcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/config/util/CredentialsCollectorTest.java +++ /dev/null @@ -1,82 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.config.util; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; - -import java.util.Map; -import java.util.Properties; - -import org.jclouds.demo.tweetstore.config.util.CredentialsCollector; -import org.jclouds.demo.tweetstore.config.util.CredentialsCollector.Credential; -import org.testng.annotations.Test; - -import com.google.common.collect.ImmutableMap; - -/** - * Tests behavior of {@code CredentialsCollector} - * - * @author Andrew Phillips - */ -@Test(groups = "unit") -public class CredentialsCollectorTest { - private CredentialsCollector collector = new CredentialsCollector(); - - public void testEmptyProperties() { - assertTrue(collector.apply(new Properties()).isEmpty(), - "Expected returned map to be empty"); - } - - public void testNoCredentials() { - Properties properties = propertiesOf(ImmutableMap.of("not-an-identity", - "v1", "not-a-credential", "v2")); - assertTrue(collector.apply(properties).isEmpty(), - "Expected returned map to be empty"); - } - - private static Properties propertiesOf(Map entries) { - Properties properties = new Properties(); - properties.putAll(entries); - return properties; - } - - public void testNonMatchingCredentials() { - Properties properties = propertiesOf(ImmutableMap.of("non_matching.identity", "v1", - "non_matching.credential", "v2")); - assertTrue(collector.apply(properties).isEmpty(), - "Expected returned map to be empty"); - } - - public void testIncompleteCredentials() { - Properties properties = propertiesOf(ImmutableMap.of("acme.identity", "v1", - "acme-2.credential", "v2")); - assertTrue(collector.apply(properties).isEmpty(), - "Expected returned map to be empty"); - } - - public void testCredentials() { - Properties properties = propertiesOf(ImmutableMap.of("acme.identity", "v1", - "acme.credential", "v2", "acme-2.identity", "v3", - "acme-2.credential", "v4")); - assertEquals(collector.apply(properties), - ImmutableMap.of("acme", new Credential("v1", "v2"), - "acme-2", new Credential("v3", "v4"))); - } -} \ No newline at end of file diff --git a/demos/tweetstore/rhcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/AddTweetsControllerTest.java b/demos/tweetstore/rhcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/AddTweetsControllerTest.java deleted file mode 100644 index 1c93403650..0000000000 --- a/demos/tweetstore/rhcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/AddTweetsControllerTest.java +++ /dev/null @@ -1,78 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.controller; - -import static org.testng.Assert.assertEquals; - -import java.io.IOException; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ExecutionException; - -import org.jclouds.ContextBuilder; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.blobstore.TransientApiMetadata; -import org.jclouds.blobstore.domain.Blob; -import org.jclouds.demo.tweetstore.domain.StoredTweetStatus; -import org.jclouds.demo.tweetstore.functions.ServiceToStoredTweetStatuses; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.testng.annotations.Test; -import org.testng.collections.Maps; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableSet; - -/** - * Tests behavior of {@code AddTweetsController} - * - * @author Adrian Cole - */ -@Test(groups = "unit") -public class AddTweetsControllerTest { - - Map createServices(String container) throws InterruptedException, - ExecutionException { - Map services = Maps.newHashMap(); - TransientApiMetadata transientApiMetadata = TransientApiMetadata.builder().build(); - for (String name : new String[] { "1", "2" }) { - BlobStoreContext context = ContextBuilder.newBuilder(transientApiMetadata).build(BlobStoreContext.class); - context.getAsyncBlobStore().createContainerInLocation(null, container).get(); - Blob blob = context.getAsyncBlobStore().blobBuilder("1").build(); - blob.getMetadata().getUserMetadata().put(TweetStoreConstants.SENDER_NAME, "frank"); - blob.setPayload("I love beans!"); - context.getAsyncBlobStore().putBlob(container, blob).get(); - services.put(name, context); - } - return services; - } - - public void testStoreTweets() throws IOException, InterruptedException, ExecutionException { - String container = "container"; - Map contexts = createServices(container); - - ServiceToStoredTweetStatuses function = new ServiceToStoredTweetStatuses(contexts, container); - AddTweetsController controller = new AddTweetsController(contexts, function); - List list = controller.apply(ImmutableSet.of("1", "2")); - assertEquals(list.size(), 2); - assertEquals(list, ImmutableList.of(new StoredTweetStatus("1", "localhost", container, "1", - "frank", "I love beans!", null), new StoredTweetStatus("2", "localhost", container, - "1", "frank", "I love beans!", null))); - - } -} diff --git a/demos/tweetstore/rhcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/ClearTweetsControllerTest.java b/demos/tweetstore/rhcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/ClearTweetsControllerTest.java deleted file mode 100644 index 81f0b9f3c7..0000000000 --- a/demos/tweetstore/rhcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/ClearTweetsControllerTest.java +++ /dev/null @@ -1,72 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.controller; - -import static org.testng.Assert.assertEquals; - -import java.io.IOException; -import java.util.Map; -import java.util.concurrent.ExecutionException; - -import org.jclouds.ContextBuilder; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.blobstore.TransientApiMetadata; -import org.jclouds.blobstore.domain.Blob; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.testng.annotations.Test; - -import com.google.common.collect.ImmutableMap; - -/** - * Tests behavior of {@code AddTweetsController} - * - * @author Adrian Cole - */ -@Test(groups = "unit") -public class ClearTweetsControllerTest { - - Map createBlobStores(String container) throws InterruptedException, ExecutionException { - TransientApiMetadata transientApiMetadata = TransientApiMetadata.builder().build(); - Map contexts = ImmutableMap.of( - "test1", ContextBuilder.newBuilder(transientApiMetadata).build(BlobStoreContext.class), - "test2", ContextBuilder.newBuilder(transientApiMetadata).build(BlobStoreContext.class)); - for (BlobStoreContext blobstore : contexts.values()) { - blobstore.getBlobStore().createContainerInLocation(null, container); - Blob blob = blobstore.getAsyncBlobStore().blobBuilder("1").build(); - blob.getMetadata().getUserMetadata().put(TweetStoreConstants.SENDER_NAME, "frank"); - blob.setPayload("I love beans!"); - blobstore.getBlobStore().putBlob(container, blob); - } - return contexts; - } - - public void testClearTweets() throws IOException, InterruptedException, ExecutionException { - String container = ClearTweetsControllerTest.class.getName() + "#container"; - Map contexts = createBlobStores(container); - - ClearTweetsController controller = new ClearTweetsController(contexts, - container); - controller.clearContainer("test1"); - controller.clearContainer("test2"); - - for (BlobStoreContext context : contexts.values()) { - assertEquals(context.getBlobStore().countBlobs(container), 0, context.toString()); - } - } -} diff --git a/demos/tweetstore/rhcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/EnqueueStoresControllerTest.java b/demos/tweetstore/rhcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/EnqueueStoresControllerTest.java deleted file mode 100644 index 3c5e5b1d80..0000000000 --- a/demos/tweetstore/rhcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/EnqueueStoresControllerTest.java +++ /dev/null @@ -1,85 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.controller; - -import static org.easymock.EasyMock.*; - -import java.net.URI; -import java.util.Map; - -import org.jclouds.ContextBuilder; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.blobstore.TransientApiMetadata; -import org.jclouds.demo.paas.RunnableHttpRequest; -import org.jclouds.demo.paas.RunnableHttpRequest.Factory; -import org.jclouds.demo.paas.service.taskqueue.TaskQueue; -import org.jclouds.http.HttpRequest; -import org.testng.annotations.Test; - -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableMultimap; - -/** - * Tests behavior of {@code EnqueueStoresController} - * - * @author Andrew Phillips - */ -@Test(groups = "unit") -public class EnqueueStoresControllerTest { - - Map createBlobStores() { - TransientApiMetadata transientApiMetadata = TransientApiMetadata.builder().build(); - Map contexts = ImmutableMap.of( - "test1", ContextBuilder.newBuilder(transientApiMetadata).build(BlobStoreContext.class), - "test2", ContextBuilder.newBuilder(transientApiMetadata).build(BlobStoreContext.class)); - return contexts; - } - - public void testEnqueueStores() { - Map stores = createBlobStores(); - TaskQueue taskQueue = createMock(TaskQueue.class); - Factory httpRequestFactory = createMock(Factory.class); - EnqueueStoresController function = new EnqueueStoresController(stores, - taskQueue, "http://localhost:8080"); - - expect(taskQueue.getHttpRequestFactory()).andStubReturn(httpRequestFactory); - - HttpRequest storeInTest1Request = HttpRequest.builder().endpoint( - URI.create("http://localhost:8080/store/do")) - .headers(ImmutableMultimap.of("context", "test1")).method("GET").build(); - RunnableHttpRequest storeInTest1Task = null; - expect(httpRequestFactory.create(eq(storeInTest1Request))).andReturn(storeInTest1Task); - - HttpRequest storeInTest2Request = HttpRequest.builder().endpoint( - URI.create("http://localhost:8080/store/do")) - .headers(ImmutableMultimap.of("context", "test2")).method("GET").build(); - RunnableHttpRequest storeInTest2Task = null; - expect(httpRequestFactory.create(eq(storeInTest2Request))).andReturn(storeInTest2Task); - - taskQueue.add(storeInTest1Task); - expectLastCall(); - taskQueue.add(storeInTest2Task); - expectLastCall(); - replay(httpRequestFactory, taskQueue); - - function.enqueueStoreTweetTasks(); - - verify(taskQueue); - } -} \ No newline at end of file diff --git a/demos/tweetstore/rhcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/StoreTweetsControllerTest.java b/demos/tweetstore/rhcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/StoreTweetsControllerTest.java deleted file mode 100644 index 2ac448103b..0000000000 --- a/demos/tweetstore/rhcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/StoreTweetsControllerTest.java +++ /dev/null @@ -1,120 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.controller; - -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.verify; -import static org.testng.Assert.assertEquals; - -import java.io.IOException; -import java.util.Map; -import java.util.Map.Entry; -import java.util.concurrent.ExecutionException; - -import org.jclouds.ContextBuilder; -import org.jclouds.blobstore.BlobMap; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.blobstore.TransientApiMetadata; -import org.jclouds.blobstore.domain.Blob; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.jclouds.util.Strings2; -import org.testng.annotations.Test; - -import twitter4j.Status; -import twitter4j.Twitter; -import twitter4j.User; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; - -/** - * Tests behavior of {@code StoreTweetsController} - * - * @author Adrian Cole - */ -@Test(groups = "unit") -public class StoreTweetsControllerTest { - - Twitter createTwitter() { - return createMock(Twitter.class); - } - - Map createBlobStores() throws InterruptedException, ExecutionException { - TransientApiMetadata transientApiMetadata = TransientApiMetadata.builder().build(); - Map contexts = ImmutableMap.of( - "test1", ContextBuilder.newBuilder(transientApiMetadata).build(BlobStoreContext.class), - "test2", ContextBuilder.newBuilder(transientApiMetadata).build(BlobStoreContext.class)); - for (BlobStoreContext blobstore : contexts.values()) { - blobstore.getAsyncBlobStore().createContainerInLocation(null, "favo").get(); - } - return contexts; - } - - public void testStoreTweets() throws IOException, InterruptedException, ExecutionException { - Map stores = createBlobStores(); - StoreTweetsController function = new StoreTweetsController(stores, "favo", createTwitter()); - - User frank = createMock(User.class); - expect(frank.getScreenName()).andReturn("frank").atLeastOnce(); - - Status frankStatus = createMock(Status.class); - expect(frankStatus.getId()).andReturn(1l).atLeastOnce(); - expect(frankStatus.getUser()).andReturn(frank).atLeastOnce(); - expect(frankStatus.getText()).andReturn("I love beans!").atLeastOnce(); - - User jimmy = createMock(User.class); - expect(jimmy.getScreenName()).andReturn("jimmy").atLeastOnce(); - - Status jimmyStatus = createMock(Status.class); - expect(jimmyStatus.getId()).andReturn(2l).atLeastOnce(); - expect(jimmyStatus.getUser()).andReturn(jimmy).atLeastOnce(); - expect(jimmyStatus.getText()).andReturn("cloud is king").atLeastOnce(); - - replay(frank); - replay(frankStatus); - replay(jimmy); - replay(jimmyStatus); - - function.addMyTweets("test1", ImmutableList.of(frankStatus, jimmyStatus)); - function.addMyTweets("test2", ImmutableList.of(frankStatus, jimmyStatus)); - - verify(frank); - verify(frankStatus); - verify(jimmy); - verify(jimmyStatus); - - for (Entry entry : stores.entrySet()) { - BlobMap map = entry.getValue().createBlobMap("favo"); - Blob frankBlob = map.get("1"); - assertEquals(frankBlob.getMetadata().getName(), "1"); - assertEquals(frankBlob.getMetadata().getUserMetadata().get(TweetStoreConstants.SENDER_NAME), "frank"); - assertEquals(frankBlob.getMetadata().getContentMetadata().getContentType(), "text/plain"); - assertEquals(Strings2.toString(frankBlob.getPayload()), "I love beans!"); - - Blob jimmyBlob = map.get("2"); - assertEquals(jimmyBlob.getMetadata().getName(), "2"); - assertEquals(jimmyBlob.getMetadata().getUserMetadata().get(TweetStoreConstants.SENDER_NAME), "jimmy"); - assertEquals(jimmyBlob.getMetadata().getContentMetadata().getContentType(), "text/plain"); - assertEquals(Strings2.toString(jimmyBlob.getPayload()), "cloud is king"); - } - - } -} diff --git a/demos/tweetstore/rhcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/functions/KeyToStoredTweetStatusTest.java b/demos/tweetstore/rhcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/functions/KeyToStoredTweetStatusTest.java deleted file mode 100644 index aab06ec0b6..0000000000 --- a/demos/tweetstore/rhcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/functions/KeyToStoredTweetStatusTest.java +++ /dev/null @@ -1,69 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.functions; - -import static org.testng.Assert.assertEquals; - -import java.io.IOException; -import java.util.concurrent.ExecutionException; - -import org.jclouds.ContextBuilder; -import org.jclouds.blobstore.BlobMap; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.blobstore.TransientApiMetadata; -import org.jclouds.blobstore.domain.Blob; -import org.jclouds.demo.tweetstore.domain.StoredTweetStatus; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.testng.annotations.Test; - -/** - * Tests behavior of {@code KeyToStoredTweetStatus} - * - * @author Adrian Cole - */ -@Test(groups = "unit") -public class KeyToStoredTweetStatusTest { - - BlobMap createMap() throws InterruptedException, ExecutionException { - BlobStoreContext context = - ContextBuilder.newBuilder(TransientApiMetadata.builder().build()).build(BlobStoreContext.class); - context.getBlobStore().createContainerInLocation(null, "test1"); - return context.createBlobMap("test1"); - } - - public void testStoreTweets() throws IOException, InterruptedException, ExecutionException { - BlobMap map = createMap(); - Blob blob = map.blobBuilder().name("1").build(); - blob.getMetadata().getUserMetadata().put(TweetStoreConstants.SENDER_NAME, "frank"); - blob.setPayload("I love beans!"); - map.put("1", blob); - String host = "localhost"; - String service = "stub"; - String container = "tweetstore"; - - KeyToStoredTweetStatus function = new KeyToStoredTweetStatus(map, service, host, container); - StoredTweetStatus result = function.apply("1"); - - StoredTweetStatus expected = new StoredTweetStatus(service, host, container, "1", "frank", - "I love beans!", null); - - assertEquals(result, expected); - - } -} diff --git a/demos/tweetstore/rhcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/functions/ServiceToStoredTweetStatusesTest.java b/demos/tweetstore/rhcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/functions/ServiceToStoredTweetStatusesTest.java deleted file mode 100644 index 5fec52711e..0000000000 --- a/demos/tweetstore/rhcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/functions/ServiceToStoredTweetStatusesTest.java +++ /dev/null @@ -1,75 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.functions; - -import static org.testng.Assert.assertEquals; - -import java.io.IOException; -import java.util.Map; -import java.util.concurrent.ExecutionException; - -import org.jclouds.ContextBuilder; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.blobstore.TransientApiMetadata; -import org.jclouds.blobstore.domain.Blob; -import org.jclouds.demo.tweetstore.domain.StoredTweetStatus; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.testng.annotations.Test; -import org.testng.collections.Maps; - -import com.google.common.collect.Iterables; - -/** - * Tests behavior of {@code ServiceToStoredTweetStatuses} - * - * @author Adrian Cole - */ -@Test(groups = "unit") -public class ServiceToStoredTweetStatusesTest { - - Map createServices(String container) throws InterruptedException, - ExecutionException { - Map services = Maps.newHashMap(); - TransientApiMetadata transientApiMetadata = TransientApiMetadata.builder().build(); - for (String name : new String[] { "1", "2" }) { - BlobStoreContext context = ContextBuilder.newBuilder(transientApiMetadata).build(BlobStoreContext.class); - context.getAsyncBlobStore().createContainerInLocation(null, container).get(); - Blob blob = context.getAsyncBlobStore().blobBuilder("1").build(); - blob.getMetadata().getUserMetadata().put(TweetStoreConstants.SENDER_NAME, "frank"); - blob.setPayload("I love beans!"); - context.getAsyncBlobStore().putBlob(container, blob).get(); - services.put(name, context); - } - return services; - } - - public void testStoreTweets() throws IOException, InterruptedException, ExecutionException { - String container = "container"; - Map contexts = createServices(container); - - ServiceToStoredTweetStatuses function = new ServiceToStoredTweetStatuses(contexts, container); - - assertEquals(Iterables.getLast(function.apply("1")), new StoredTweetStatus("1", "localhost", - container, "1", "frank", "I love beans!", null)); - - assertEquals(Iterables.getLast(function.apply("2")), new StoredTweetStatus("2", "localhost", - container, "1", "frank", "I love beans!", null)); - - } -} diff --git a/demos/tweetstore/rhcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/integration/RhcloudServer.java b/demos/tweetstore/rhcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/integration/RhcloudServer.java deleted file mode 100644 index 07b695ab65..0000000000 --- a/demos/tweetstore/rhcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/integration/RhcloudServer.java +++ /dev/null @@ -1,109 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.integration; - -import static com.google.common.collect.Iterables.find; -import static com.google.common.io.Closeables.closeQuietly; -import static java.lang.String.format; -import static org.jclouds.demo.tweetstore.integration.util.Zips.zipDir; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Properties; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; - -import org.jboss.as.controller.client.helpers.standalone.DeploymentAction; -import org.jboss.as.controller.client.helpers.standalone.DeploymentPlan; -import org.jboss.as.controller.client.helpers.standalone.ServerDeploymentActionResult; -import org.jboss.as.controller.client.helpers.standalone.ServerDeploymentManager; -import org.jboss.as.controller.client.helpers.standalone.ServerDeploymentPlanResult; -import org.jboss.as.embedded.EmbeddedServerFactory2; -import org.jboss.as.embedded.ServerStartException; -import org.jboss.as.embedded.StandaloneServer; - -import com.google.common.base.Predicate; -import com.google.common.io.Files; - -/** - * Basic functionality to start a local JBoss AS 7 instance. - * - * @author Andrew Phillips - */ -public class RhcloudServer { - private static final byte[] CONTEXT_ROOT_XML_BYTES = - "/".getBytes(); - - protected StandaloneServer server; - protected ServerDeploymentManager manager; - - public void writePropertiesAndStartServer(String warfile, - String serverHome, Properties props) throws IOException, - ServerStartException, InterruptedException, ExecutionException { - String propsfile = String.format("%1$s/WEB-INF/jclouds.properties", warfile); - System.err.println("file: " + propsfile); - storeProperties(propsfile, props); - assert new File(propsfile).exists(); - - // in OpenShift, TweetStore runs at the server root - String ctxrootfile = String.format("%1$s/WEB-INF/jboss-web.xml", warfile); - System.err.println("file: " + ctxrootfile); - Files.write(CONTEXT_ROOT_XML_BYTES, new File(ctxrootfile)); - assert new File(ctxrootfile).exists(); - - server = EmbeddedServerFactory2.create(new File(serverHome), System.getProperties(), System.getenv()); - server.start(); - TimeUnit.SECONDS.sleep(30); - manager = ServerDeploymentManager.Factory.create(server.getModelControllerClient()); - ServerDeploymentActionResult deploymentResult = deploy(warfile); - System.err.println("deployment result: " + deploymentResult.getResult()); - } - - private static void storeProperties(String filename, Properties props) - throws IOException { - FileOutputStream targetFile = new FileOutputStream(filename); - try { - props.store(targetFile, "test"); - } finally { - closeQuietly(targetFile); - } - } - - protected ServerDeploymentActionResult deploy(String explodedWar) - throws IOException, InterruptedException, ExecutionException { - File war = zipDir(explodedWar, format("%s-rhcloud.war", explodedWar)); - final String deploymentName = war.getName(); - - DeploymentPlan plan = - manager.newDeploymentPlan().add(deploymentName, war).andDeploy().build(); - ServerDeploymentPlanResult deploymentResult = manager.execute(plan).get(); - return deploymentResult.getDeploymentActionResult(find( - plan.getDeploymentActions(), new Predicate() { - @Override - public boolean apply(DeploymentAction input) { - return input.getDeploymentUnitUniqueName().equals(deploymentName); - } - }).getId()); - } - - public void stop() throws Exception { - server.stop(); - } -} \ No newline at end of file diff --git a/demos/tweetstore/rhcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/integration/TweetStoreLiveTest.java b/demos/tweetstore/rhcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/integration/TweetStoreLiveTest.java deleted file mode 100644 index 30dc27c70f..0000000000 --- a/demos/tweetstore/rhcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/integration/TweetStoreLiveTest.java +++ /dev/null @@ -1,238 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.integration; - -import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.demo.paas.RunnableHttpRequest.PLATFORM_REQUEST_ORIGINATOR_HEADER; -import static org.jclouds.demo.tweetstore.reference.TweetStoreConstants.PROPERTY_TWEETSTORE_BLOBSTORES; -import static org.jclouds.demo.tweetstore.reference.TweetStoreConstants.PROPERTY_TWEETSTORE_CONTAINER; -import static org.jclouds.demo.tweetstore.reference.TwitterConstants.PROPERTY_TWITTER_ACCESSTOKEN; -import static org.jclouds.demo.tweetstore.reference.TwitterConstants.PROPERTY_TWITTER_ACCESSTOKEN_SECRET; -import static org.jclouds.demo.tweetstore.reference.TwitterConstants.PROPERTY_TWITTER_CONSUMER_KEY; -import static org.jclouds.demo.tweetstore.reference.TwitterConstants.PROPERTY_TWITTER_CONSUMER_SECRET; - -import java.io.IOException; -import java.io.InputStream; -import java.net.HttpURLConnection; -import java.net.URL; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Properties; -import java.util.Set; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeoutException; - -import org.jclouds.Context; -import org.jclouds.ContextBuilder; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.demo.tweetstore.controller.StoreTweetsController; -import org.jclouds.logging.log4j.config.Log4JLoggingModule; -import org.jclouds.rest.AuthorizationException; -import org.jclouds.util.Strings2; -import org.testng.annotations.AfterTest; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.Parameters; -import org.testng.annotations.Test; - -import twitter4j.ResponseList; -import twitter4j.Status; -import twitter4j.Twitter; -import twitter4j.TwitterException; -import twitter4j.TwitterFactory; -import twitter4j.conf.Configuration; -import twitter4j.conf.ConfigurationBuilder; - -import com.google.common.base.Splitter; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Maps; -import com.google.inject.Module; - -/** - * Starts up a JBoss AS 7 server (simulating OpenShift Express) and deploys - * an application which tests accesses twitter and blobstores. - * - * @author Andrew Phillips - */ -@Test(groups = "live", singleThreaded = true) -public class TweetStoreLiveTest { - - RhcloudServer server; - private URL url; - private Map contexts; - private String container; - private static final Iterable blobstores = - Splitter.on(',').split(getRequiredSystemProperty(PROPERTY_TWEETSTORE_BLOBSTORES)); - private static final Properties props = new Properties(); - - @BeforeTest - void clearAndCreateContainers() throws InterruptedException, ExecutionException, TimeoutException, IOException, - TwitterException { - container = getRequiredSystemProperty(PROPERTY_TWEETSTORE_CONTAINER); - - props.setProperty(PROPERTY_TWEETSTORE_CONTAINER, container); - - // put all identity/credential pairs into the client - addCredentialsForBlobStores(props); - - // example of an ad-hoc client configuration - addConfigurationForTwitter(props); - - // for testing, capture logs. - final Set wiring = ImmutableSet. of(new Log4JLoggingModule()); - this.contexts = Maps.newConcurrentMap(); - - for (String provider : blobstores) { - contexts.put(provider, ContextBuilder.newBuilder(provider) - .modules(wiring).overrides(props).build(BlobStoreContext.class)); - } - - Configuration conf = new ConfigurationBuilder() - .setOAuthConsumerKey(props.getProperty(PROPERTY_TWITTER_CONSUMER_KEY)) - .setOAuthConsumerSecret(props.getProperty(PROPERTY_TWITTER_CONSUMER_SECRET)) - .setOAuthAccessToken(props.getProperty(PROPERTY_TWITTER_ACCESSTOKEN)) - .setOAuthAccessTokenSecret(props.getProperty(PROPERTY_TWITTER_ACCESSTOKEN_SECRET)) - .build(); - Twitter client = new TwitterFactory(conf).getInstance(); - StoreTweetsController controller = new StoreTweetsController(contexts, container, client); - - ResponseList statuses = client.getMentions(); - - boolean deleted = false; - for (BlobStoreContext context : contexts.values()) { - try { - if (context.getBlobStore().containerExists(container)) { - System.err.printf("deleting container %s at %s%n", container, - context.unwrap(Context.class).getProviderMetadata().getEndpoint()); - context.getBlobStore().deleteContainer(container); - deleted = true; - } - } catch (AuthorizationException e) { - throw new AuthorizationException("for context: " + context, e); - } - } - if (deleted) { - System.err.println("sleeping 60 seconds to allow containers to clear"); - Thread.sleep(60000); - } - for (BlobStoreContext context : contexts.values()) { - System.err.printf("creating container %s at %s%n", container, - context.unwrap(Context.class).getProviderMetadata().getEndpoint()); - context.getBlobStore().createContainerInLocation(null, container); - } - - if (deleted) { - System.err.println("sleeping 5 seconds to allow containers to create"); - Thread.sleep(5000); - } - - for (Entry entry : contexts.entrySet()) { - System.err.printf("filling container %s at %s%n", container, entry.getKey()); - controller.addMyTweets(entry.getKey(), statuses); - } - } - - private static String getRequiredSystemProperty(String key) { - return checkNotNull(System.getProperty(key), key); - } - - private void addConfigurationForTwitter(Properties props) { - props.setProperty(PROPERTY_TWITTER_CONSUMER_KEY, - getRequiredSystemProperty("test." + PROPERTY_TWITTER_CONSUMER_KEY)); - props.setProperty(PROPERTY_TWITTER_CONSUMER_SECRET, - getRequiredSystemProperty("test." + PROPERTY_TWITTER_CONSUMER_SECRET)); - props.setProperty(PROPERTY_TWITTER_ACCESSTOKEN, - getRequiredSystemProperty("test." + PROPERTY_TWITTER_ACCESSTOKEN)); - props.setProperty(PROPERTY_TWITTER_ACCESSTOKEN_SECRET, - getRequiredSystemProperty("test." + PROPERTY_TWITTER_ACCESSTOKEN_SECRET)); - } - - private void addCredentialsForBlobStores(Properties props) { - for (String provider : blobstores) { - props.setProperty(provider + ".identity", - getRequiredSystemProperty("test." + provider + ".identity")); - props.setProperty(provider + ".credential", - getRequiredSystemProperty("test." + provider + ".credential")); - } - } - - @BeforeTest(dependsOnMethods = "clearAndCreateContainers") - @Parameters({ "warfile", "jboss.address", "jboss.port", "jboss.home" }) - public void startDevAppServer(final String warfile, final String address, final String port, - String serverHome) throws Exception { - url = new URL(String.format("http://%s:%s", address, port)); - - server = new RhcloudServer(); - server.writePropertiesAndStartServer(warfile, serverHome, props); - } - - @Test - public void shouldPass() throws InterruptedException, IOException { - InputStream i = url.openStream(); - String string = Strings2.toStringAndClose(i); - assert string.indexOf("Welcome") >= 0 : string; - } - - @Test(dependsOnMethods = "shouldPass", expectedExceptions = IOException.class) - public void shouldFail() throws InterruptedException, IOException { - new URL(url, "/store/do").openStream(); - } - - @Test(dependsOnMethods = "shouldFail") - public void testPrimeContainers() throws IOException, InterruptedException { - URL gurl = new URL(url, "/store/do"); - - for (String context : blobstores) { - System.out.println("storing at context: " + context); - HttpURLConnection connection = (HttpURLConnection) gurl.openConnection(); - connection.addRequestProperty(PLATFORM_REQUEST_ORIGINATOR_HEADER, "taskqueue-twitter"); - connection.addRequestProperty("context", context); - InputStream i = connection.getInputStream(); - String string = Strings2.toStringAndClose(i); - assert string.indexOf("Done!") >= 0 : string; - connection.disconnect(); - } - - System.err.println("sleeping 20 seconds to allow for eventual consistency delay"); - Thread.sleep(20000); - for (BlobStoreContext context : contexts.values()) { - assert context.createInputStreamMap(container).size() > 0 : context.unwrap(Context.class).getProviderMetadata().getEndpoint(); - } - } - - @Test(invocationCount = 5, dependsOnMethods = "testPrimeContainers") - public void testSerial() throws InterruptedException, IOException { - URL gurl = new URL(url, "/tweets/get"); - InputStream i = gurl.openStream(); - String string = Strings2.toStringAndClose(i); - assert string.indexOf("Tweets in Clouds") >= 0 : string; - } - - @Test(invocationCount = 10, dependsOnMethods = "testPrimeContainers", threadPoolSize = 3) - public void testParallel() throws InterruptedException, IOException { - URL gurl = new URL(url, "/tweets/get"); - InputStream i = gurl.openStream(); - String string = Strings2.toStringAndClose(i); - assert string.indexOf("Tweets in Clouds") >= 0 : string; - } - - @AfterTest - public void stopDevAppServer() throws Exception { - server.stop(); - } -} diff --git a/demos/tweetstore/rhcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/integration/util/ObjectFields.java b/demos/tweetstore/rhcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/integration/util/ObjectFields.java deleted file mode 100644 index 8c4edd5ea9..0000000000 --- a/demos/tweetstore/rhcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/integration/util/ObjectFields.java +++ /dev/null @@ -1,43 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.integration.util; - -import java.lang.reflect.Field; - -public class ObjectFields { - - private static Field getAccessibleField(String name, Class declaringClass) throws SecurityException, NoSuchFieldException { - Field field = declaringClass.getDeclaredField(name); - field.setAccessible(true); - return field; - } - - public static void set(String fieldName, Object target, Object value) { - set(fieldName, target, value, target.getClass()); - } - - public static void set(String fieldName, Object target, Object value, - Class fieldDeclaringClass) { - try { - getAccessibleField(fieldName, fieldDeclaringClass).set(target, value); - } catch (Exception exception) { - throw new IllegalArgumentException(exception); - } - } -} diff --git a/demos/tweetstore/rhcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/integration/util/Zips.java b/demos/tweetstore/rhcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/integration/util/Zips.java deleted file mode 100644 index 571c9083a3..0000000000 --- a/demos/tweetstore/rhcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/integration/util/Zips.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.integration.util; - -import java.io.File; -import java.io.IOException; - -import org.codehaus.plexus.archiver.zip.ZipArchiver; - -public class Zips { - - public static File zipDir(String dirToZip, String zipFile) throws IOException { - ZipArchiver archiver = new ZipArchiver(); - archiver.addDirectory(new File(dirToZip)); - File zip = new File(zipFile); - archiver.setDestFile(zip); - archiver.createArchive(); - return zip; - } -} \ No newline at end of file diff --git a/demos/tweetstore/rhcloud-tweetstore/src/test/resources/jbossas7/configuration/standalone.xml b/demos/tweetstore/rhcloud-tweetstore/src/test/resources/jbossas7/configuration/standalone.xml deleted file mode 100644 index dcdf6049b6..0000000000 --- a/demos/tweetstore/rhcloud-tweetstore/src/test/resources/jbossas7/configuration/standalone.xml +++ /dev/null @@ -1,208 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - jdbc:h2:${jboss.server.data.dir}/test;DB_CLOSE_DELAY=-1 - h2 - - - sa - sa - - - - - - - jdbc:mysql://${OPENSHIFT_DB_HOST}:${OPENSHIFT_DB_PORT}/${OPENSHIFT_APP_NAME} - mysql - - ${OPENSHIFT_DB_USERNAME} - ${OPENSHIFT_DB_PASSWORD} - - - - - org.h2.jdbcx.JdbcDataSource - - - com.mysql.jdbc.jdbc2.optional.MysqlXADataSource - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/demos/tweetstore/rhcloud-tweetstore/src/test/resources/log4j.xml b/demos/tweetstore/rhcloud-tweetstore/src/test/resources/log4j.xml deleted file mode 100644 index 2e5d01fb9e..0000000000 --- a/demos/tweetstore/rhcloud-tweetstore/src/test/resources/log4j.xml +++ /dev/null @@ -1,95 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/demos/tweetstore/runatcloud-tweetstore/README.txt b/demos/tweetstore/runatcloud-tweetstore/README.txt deleted file mode 100644 index 5488f63442..0000000000 --- a/demos/tweetstore/runatcloud-tweetstore/README.txt +++ /dev/null @@ -1,52 +0,0 @@ -==== - Licensed to jclouds, Inc. (jclouds) under one or more - contributor license agreements. See the NOTICE file - distributed with this work for additional information - regarding copyright ownership. jclouds licenses this file - to you under the Apache License, Version 2.0 (the - "License"); you may not use this file except in compliance - with the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, - software distributed under the License is distributed on an - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - KIND, either express or implied. See the License for the - specific language governing permissions and limitations - under the License. -==== - -A guide to generating Twitter consumer keys and access tokens is at http://tinyurl.com/2fhebgb - -Please modify your maven settings.xml like below before attempting to run 'mvn -Plive install' - - - cloudbees - - true - - - yourapikey - yoursecret - - - - - keys - - true - - - YOUR_ACCESS_KEY_ID - YOUR_SECRET_KEY - YOUR_USER - YOUR_HEX_KEY - YOUR_ACCOUNT - YOUR_BASE64_ENCODED_KEY - YOUR_TWITTER_CONSUMER_KEY - YOUR_TWITTER_CONSUMER_SECRET - YOUR_TWITTER_ACCESSTOKEN - YOUR_TWITTER_ACCESSTOKEN_SECRET - - \ No newline at end of file diff --git a/demos/tweetstore/runatcloud-tweetstore/pom.xml b/demos/tweetstore/runatcloud-tweetstore/pom.xml deleted file mode 100644 index 26e156aa56..0000000000 --- a/demos/tweetstore/runatcloud-tweetstore/pom.xml +++ /dev/null @@ -1,164 +0,0 @@ - - - - 4.0.0 - - org.jclouds - jclouds-demos-tweetstore-project - 1.5.0-SNAPSHOT - - jclouds-demo-runatcloud-tweetstore - war - jclouds TweetStore for RUN@cloud - jclouds TweetStore for CloudBees' RUN@cloud using Guice for Dependency Injection - - - jclouds/tweetstore - - tweetstore - localhost - 8088 - jclouds-runatcloud-tweetstore - - - - - com.google.inject.extensions - guice-servlet - 3.0 - - - org.quartz-scheduler - quartz - 2.1.3 - - - org.slf4j - slf4j-api - - - - - - - net.stax - stax-appserver - 1.0.20110131-SNAPSHOT - test - - - - - - - bees-snapshots - http://repository-cloudbees.forge.cloudbees.com/public-snapshot - - false - - - true - - - - - - - live - - - - maven-surefire-plugin - - - integration - integration-test - - test - - - - ${test.twitter.runatcloud-tweetstore.consumer.identity} - ${test.twitter.runatcloud-tweetstore.consumer.credential} - ${test.twitter.runatcloud-tweetstore.access.identity} - ${test.twitter.runatcloud-tweetstore.access.credential} - ${test.azureblob.identity} - ${test.azureblob.credential} - ${test.cloudfiles-us.identity} - ${test.cloudfiles-us.credential} - ${test.aws-s3.identity} - ${test.aws-s3.credential} - ${test.cloudonestorage.identity} - ${test.cloudonestorage.credential} - ${test.ninefold-storage.identity} - ${test.ninefold-storage.credential} - ${test.bees.address} - ${test.bees.port} - ${jclouds.tweetstore.blobstores} - - test.${jclouds.tweetstore.container}2 - ${project.build.directory}/bees - ${project.build.directory}/${project.artifactId} - - - - - - - - - - - deploy - - - runatcloud-tweetstore - - - - bees-snapshots - http://repository-cloudbees.forge.cloudbees.com/public-snapshot - - false - - - true - - - - - - - com.cloudbees - bees-maven-plugin - 1.0-SNAPSHOT - - run - ${bees.apikey} - ${bees.secret} - - - - - - - diff --git a/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/paas/PlatformServices.java b/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/paas/PlatformServices.java deleted file mode 100644 index 0997005157..0000000000 --- a/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/paas/PlatformServices.java +++ /dev/null @@ -1,64 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.paas; - -import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.demo.paas.config.PlatformServicesInitializer.PLATFORM_SERVICES_ATTRIBUTE_NAME; - -import java.util.Map; - -import javax.servlet.ServletContext; - -import org.jclouds.demo.paas.service.scheduler.Scheduler; -import org.jclouds.demo.paas.service.taskqueue.TaskQueue; -import org.jclouds.javax.annotation.Nullable; - -import com.google.common.collect.ImmutableMap; - -/** - * @author Andrew Phillips - */ -public class PlatformServices { - protected final String baseUrl; - protected final Scheduler scheduler; - private ImmutableMap taskQueues; - - public PlatformServices(String baseUrl, Scheduler scheduler, Map taskQueues) { - this.baseUrl = baseUrl; - this.scheduler = scheduler; - this.taskQueues = ImmutableMap.copyOf(taskQueues); - } - - public String getBaseUrl() { - return baseUrl; - } - - public Scheduler getScheduler() { - return scheduler; - } - - public @Nullable TaskQueue getTaskQueue(String name) { - return taskQueues.get(name); - } - - public static PlatformServices get(ServletContext context) { - return (PlatformServices) checkNotNull(context.getAttribute( - PLATFORM_SERVICES_ATTRIBUTE_NAME), PLATFORM_SERVICES_ATTRIBUTE_NAME); - } -} diff --git a/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/paas/RunnableHttpRequest.java b/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/paas/RunnableHttpRequest.java deleted file mode 100644 index ad72a1a58d..0000000000 --- a/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/paas/RunnableHttpRequest.java +++ /dev/null @@ -1,126 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.paas; - -import static java.lang.String.format; - -import org.jclouds.http.HttpCommand; -import org.jclouds.http.HttpCommandExecutorService; -import org.jclouds.http.HttpRequest; - -import com.google.common.collect.ImmutableMultimap; -import com.google.common.collect.Multimap; - -public class RunnableHttpRequest implements Runnable { - public static final String PLATFORM_REQUEST_ORIGINATOR_HEADER = "X-Platform-Originator"; - - public static Factory factory(HttpCommandExecutorService httpClient) { - return factory(httpClient, format("%s@%d", Factory.class.getName(), System.currentTimeMillis())); - } - - public static Factory factory(HttpCommandExecutorService httpClient, String originator) { - return new Factory(httpClient, originator); - } - - public static class Factory { - protected final HttpCommandExecutorService httpClient; - protected final String originator; - - private Factory(HttpCommandExecutorService httpClient, String originator) { - this.httpClient = httpClient; - this.originator = originator; - } - - public RunnableHttpRequest create(HttpRequest request) { - HttpRequest requestWithSubmitter = request.toBuilder() - .headers(copyOfWithEntry(request.getHeaders(), - PLATFORM_REQUEST_ORIGINATOR_HEADER, originator)).build(); - return new RunnableHttpRequest(httpClient, requestWithSubmitter); - } - - private static Multimap copyOfWithEntry( - Multimap multimap, K k1, V v1) { - return ImmutableMultimap.builder().putAll(multimap).put(k1, v1).build(); - } - } - - private final HttpCommandExecutorService httpClient; - private final HttpRequest request; - - private RunnableHttpRequest(HttpCommandExecutorService httpClient, HttpRequest request) { - this.httpClient = httpClient; - this.request = request; - } - - @Override - public void run() { - httpClient.submit(new ImmutableHttpCommand(request)); - } - - private class ImmutableHttpCommand implements HttpCommand { - private final HttpRequest request; - - public ImmutableHttpCommand(HttpRequest request) { - this.request = request; - } - - @Override - public void setException(Exception exception) { - } - - @Override - public void setCurrentRequest(HttpRequest request) { - } - - @Override - public boolean isReplayable() { - return false; - } - - @Override - public int incrementRedirectCount() { - return 0; - } - - @Override - public int incrementFailureCount() { - return 0; - } - - @Override - public int getRedirectCount() { - return 0; - } - - @Override - public int getFailureCount() { - return 0; - } - - @Override - public Exception getException() { - return null; - } - - @Override - public HttpRequest getCurrentRequest() { - return request; - } - } -} diff --git a/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/paas/config/HttpClientModule.java b/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/paas/config/HttpClientModule.java deleted file mode 100644 index 5aa077b6cd..0000000000 --- a/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/paas/config/HttpClientModule.java +++ /dev/null @@ -1,65 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.paas.config; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.inject.name.Names.bindProperties; -import static org.jclouds.Constants.*; - -import java.util.Properties; - -import javax.servlet.ServletContext; -import javax.ws.rs.core.UriBuilder; - -import org.jclouds.demo.tweetstore.config.util.PropertiesLoader; - -import com.google.inject.AbstractModule; -import com.sun.jersey.api.uri.UriBuilderImpl; - -/** - * @author Andrew Phillips - */ -public class HttpClientModule extends AbstractModule { - private final ServletContext context; - - HttpClientModule(ServletContext context) { - this.context = context; - } - - @Override - protected void configure() { - // URL connection defaults - Properties toBind = defaultProperties(); - toBind.putAll(checkNotNull(new PropertiesLoader(context).get(), "properties")); - toBind.putAll(System.getProperties()); - bindProperties(binder(), toBind); - bind(UriBuilder.class).to(UriBuilderImpl.class); - } - - private static Properties defaultProperties() { - Properties props = new Properties(); - props.setProperty(PROPERTY_MAX_CONNECTIONS_PER_CONTEXT, 20 + ""); - props.setProperty(PROPERTY_MAX_CONNECTIONS_PER_HOST, 0 + ""); - props.setProperty(PROPERTY_SO_TIMEOUT, 60000 + ""); - props.setProperty(PROPERTY_CONNECTION_TIMEOUT, 60000 + ""); - props.setProperty(PROPERTY_USER_THREADS, 0 + ""); - props.setProperty(PROPERTY_IO_WORKER_THREADS, 20 + ""); - return props; - } -} diff --git a/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/paas/config/PlatformServicesInitializer.java b/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/paas/config/PlatformServicesInitializer.java deleted file mode 100644 index ee74adaf6e..0000000000 --- a/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/paas/config/PlatformServicesInitializer.java +++ /dev/null @@ -1,87 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.paas.config; - -import static com.google.common.base.Preconditions.checkNotNull; -import static java.util.concurrent.TimeUnit.SECONDS; - -import javax.servlet.ServletContext; -import javax.servlet.ServletContextEvent; -import javax.servlet.ServletContextListener; - -import org.jclouds.concurrent.config.ExecutorServiceModule; -import org.jclouds.demo.paas.PlatformServices; -import org.jclouds.demo.paas.service.scheduler.Scheduler; -import org.jclouds.demo.paas.service.taskqueue.TaskQueue; -import org.jclouds.http.HttpCommandExecutorService; -import org.jclouds.http.config.JavaUrlHttpCommandExecutorServiceModule; - -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableMap.Builder; -import com.google.inject.Guice; - -/** - * @author Andrew Phillips - */ -public class PlatformServicesInitializer implements ServletContextListener { - public static final String PLATFORM_SERVICES_ATTRIBUTE_NAME = PlatformServices.class.getName(); - - // keep in sync with cloudbees-web.xml - protected static final String HOST_PARAMETER = "application.host"; - - @Override - public void contextInitialized(ServletContextEvent contextEvent) { - ServletContext context = contextEvent.getServletContext(); - context.setAttribute(PLATFORM_SERVICES_ATTRIBUTE_NAME, createServices(context)); - } - - protected static PlatformServices createServices(ServletContext context) { - HttpCommandExecutorService httpClient = createHttpClient(context); - return new PlatformServices(getBaseUrl(context), new Scheduler(httpClient), - createTaskQueues(httpClient)); - } - - protected static HttpCommandExecutorService createHttpClient( - final ServletContext context) { - return Guice.createInjector(new ExecutorServiceModule(), - new JavaUrlHttpCommandExecutorServiceModule(), - new HttpClientModule(context)) - .getInstance(HttpCommandExecutorService.class); - } - - protected static String getBaseUrl(ServletContext context) { - return "http://" + checkNotNull(context.getInitParameter(HOST_PARAMETER), HOST_PARAMETER) - + context.getContextPath(); - } - - // TODO: make the number and names of queues configurable - protected static ImmutableMap createTaskQueues(HttpCommandExecutorService httpClient) { - Builder taskQueues = ImmutableMap.builder(); - taskQueues.put("twitter", TaskQueue.builder(httpClient) - .name("twitter").period(SECONDS.toMillis(30)) - .build()); - return taskQueues.build(); - } - - @Override - public void contextDestroyed(ServletContextEvent servletContextEvent) { - ServletContext context = servletContextEvent.getServletContext(); - context.removeAttribute(PLATFORM_SERVICES_ATTRIBUTE_NAME); - } -} diff --git a/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/paas/service/scheduler/HttpRequestJob.java b/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/paas/service/scheduler/HttpRequestJob.java deleted file mode 100644 index 902f5fe356..0000000000 --- a/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/paas/service/scheduler/HttpRequestJob.java +++ /dev/null @@ -1,69 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.paas.service.scheduler; - -import static com.google.common.base.Preconditions.checkNotNull; - -import java.net.URI; - -import javax.servlet.ServletContext; - -import org.jclouds.demo.paas.PlatformServices; -import org.jclouds.demo.paas.RunnableHttpRequest; -import org.jclouds.http.HttpRequest; -import org.quartz.Job; -import org.quartz.JobExecutionContext; -import org.quartz.JobExecutionException; -import org.quartz.SchedulerException; - -/** - * @author Andrew Phillips - */ -public class HttpRequestJob implements Job { - protected static final String URL_ATTRIBUTE_NAME = "url"; - - // keep in sync with "quartz:scheduler-context-servlet-context-key" param in web.xml - protected static final String SERVLET_CONTEXT_KEY = "servlet-context"; - - @Override - public void execute(JobExecutionContext context) throws JobExecutionException { - PlatformServices platform = JobContexts.getPlatform(context); - RunnableHttpRequest request = platform.getScheduler().getHttpRequestFactory().create( - HttpRequest.builder() - .endpoint(JobContexts.getTargetUrl(platform.getBaseUrl(), context)) - .method("GET").build()); - request.run(); - } - - private static class JobContexts { - private static URI getTargetUrl(String baseUrl, JobExecutionContext context) { - return URI.create(baseUrl + (String) checkNotNull( - context.getMergedJobDataMap().get(URL_ATTRIBUTE_NAME), URL_ATTRIBUTE_NAME)); - } - - private static PlatformServices getPlatform(JobExecutionContext jobContext) throws JobExecutionException { - try { - return PlatformServices.get((ServletContext) checkNotNull( - jobContext.getScheduler().getContext().get(SERVLET_CONTEXT_KEY), SERVLET_CONTEXT_KEY)); - } catch (SchedulerException exception) { - throw new JobExecutionException("Unable to get platform services from the job execution context", exception); - } - } - } -} diff --git a/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/paas/service/scheduler/Scheduler.java b/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/paas/service/scheduler/Scheduler.java deleted file mode 100644 index dabdff877b..0000000000 --- a/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/paas/service/scheduler/Scheduler.java +++ /dev/null @@ -1,41 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.paas.service.scheduler; - -import org.jclouds.demo.paas.RunnableHttpRequest; -import org.jclouds.demo.paas.RunnableHttpRequest.Factory; -import org.jclouds.http.HttpCommandExecutorService; - -/** - * @author Andrew Phillips - */ -public class Scheduler { - protected static final String SCHEDULER_ORIGINATOR_NAME = "scheduler"; - - protected final Factory httpRequestFactory; - - public Scheduler(HttpCommandExecutorService httpClient) { - httpRequestFactory = - RunnableHttpRequest.factory(httpClient, SCHEDULER_ORIGINATOR_NAME); - } - - public Factory getHttpRequestFactory() { - return httpRequestFactory; - } -} diff --git a/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/paas/service/scheduler/quartz/plugins/TransactionlessXmlSchedulingDataProcessorPlugin.java b/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/paas/service/scheduler/quartz/plugins/TransactionlessXmlSchedulingDataProcessorPlugin.java deleted file mode 100644 index b47f81dfad..0000000000 --- a/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/paas/service/scheduler/quartz/plugins/TransactionlessXmlSchedulingDataProcessorPlugin.java +++ /dev/null @@ -1,401 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.paas.service.scheduler.quartz.plugins; - -import static org.quartz.SimpleScheduleBuilder.simpleSchedule; -import static org.quartz.TriggerBuilder.newTrigger; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.UnsupportedEncodingException; -import java.net.URL; -import java.net.URLDecoder; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Set; -import java.util.StringTokenizer; - -import org.jclouds.logging.Logger; -import org.quartz.JobBuilder; -import org.quartz.JobDetail; -import org.quartz.Scheduler; -import org.quartz.SchedulerException; -import org.quartz.SimpleTrigger; -import org.quartz.TriggerKey; -import org.quartz.jobs.FileScanJob; -import org.quartz.jobs.FileScanListener; -import org.quartz.plugins.xml.XMLSchedulingDataProcessorPlugin; -import org.quartz.simpl.CascadingClassLoadHelper; -import org.quartz.spi.ClassLoadHelper; -import org.quartz.spi.SchedulerPlugin; -import org.quartz.xml.XMLSchedulingDataProcessor; - -/** - * A copy of {@link XMLSchedulingDataProcessorPlugin} that does not reference - * {@code javax.transaction.UserTransaction} as so does not require a dependency - * on JTA. - * - * @author Andrew Phillips - * @see XMLSchedulingDataProcessorPlugin - */ -public class TransactionlessXmlSchedulingDataProcessorPlugin implements - FileScanListener, SchedulerPlugin { - - /* - * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - * - * Data members. - * - * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - */ - private static final int MAX_JOB_TRIGGER_NAME_LEN = 80; - private static final String JOB_INITIALIZATION_PLUGIN_NAME = "JobSchedulingDataLoaderPlugin"; - private static final String FILE_NAME_DELIMITERS = ","; - - private String name; - private Scheduler scheduler; - private final Logger log = Logger.CONSOLE; - - private boolean failOnFileNotFound = true; - - private String fileNames = XMLSchedulingDataProcessor.QUARTZ_XML_DEFAULT_FILE_NAME; - - // Populated by initialization - private Map jobFiles = new LinkedHashMap(); - - private long scanInterval = 0; - - boolean started = false; - - protected ClassLoadHelper classLoadHelper = null; - - private Set jobTriggerNameSet = new HashSet(); - - /* - * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - * - * Interface. - * - * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - */ - - /** - * Comma separated list of file names (with paths) to the XML files that should be read. - */ - public String getFileNames() { - return fileNames; - } - - /** - * The file name (and path) to the XML file that should be read. - */ - public void setFileNames(String fileNames) { - this.fileNames = fileNames; - } - - /** - * The interval (in seconds) at which to scan for changes to the file. - * If the file has been changed, it is re-loaded and parsed. The default - * value for the interval is 0, which disables scanning. - * - * @return Returns the scanInterval. - */ - public long getScanInterval() { - return scanInterval / 1000; - } - - /** - * The interval (in seconds) at which to scan for changes to the file. - * If the file has been changed, it is re-loaded and parsed. The default - * value for the interval is 0, which disables scanning. - * - * @param scanInterval The scanInterval to set. - */ - public void setScanInterval(long scanInterval) { - this.scanInterval = scanInterval * 1000; - } - - /** - * Whether or not initialization of the plugin should fail (throw an - * exception) if the file cannot be found. Default is true. - */ - public boolean isFailOnFileNotFound() { - return failOnFileNotFound; - } - - /** - * Whether or not initialization of the plugin should fail (throw an - * exception) if the file cannot be found. Default is true. - */ - public void setFailOnFileNotFound(boolean failOnFileNotFound) { - this.failOnFileNotFound = failOnFileNotFound; - } - - /* - * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - * - * SchedulerPlugin Interface. - * - * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - */ - - /** - *

- * Called during creation of the Scheduler in order to give - * the SchedulerPlugin a chance to initialize. - *

- * - * @throws org.quartz.SchedulerConfigException - * if there is an error initializing. - */ - @Override - public void initialize(String name, Scheduler scheduler) - throws SchedulerException { - this.name = name; - this.scheduler = scheduler; - - classLoadHelper = new CascadingClassLoadHelper(); - classLoadHelper.initialize(); - - log.info("Registering Quartz Job Initialization Plug-in."); - - // Create JobFile objects - StringTokenizer stok = new StringTokenizer(fileNames, FILE_NAME_DELIMITERS); - while (stok.hasMoreTokens()) { - final String fileName = stok.nextToken(); - final JobFile jobFile = new JobFile(fileName); - jobFiles.put(fileName, jobFile); - } - } - - @Override - public void start() { - try { - if (jobFiles.isEmpty() == false) { - - if (scanInterval > 0) { - scheduler.getContext().put(JOB_INITIALIZATION_PLUGIN_NAME + '_' + name, this); - } - - Iterator iterator = jobFiles.values().iterator(); - while (iterator.hasNext()) { - JobFile jobFile = iterator.next(); - - if (scanInterval > 0) { - String jobTriggerName = buildJobTriggerName(jobFile.getFileBasename()); - TriggerKey tKey = new TriggerKey(jobTriggerName, JOB_INITIALIZATION_PLUGIN_NAME); - - // remove pre-existing job/trigger, if any - scheduler.unscheduleJob(tKey); - - // TODO: convert to use builder - SimpleTrigger trig = newTrigger() - .withIdentity(jobTriggerName, JOB_INITIALIZATION_PLUGIN_NAME) - .startNow() - .endAt(null) - .withSchedule(simpleSchedule() - .repeatForever() - .withIntervalInMilliseconds(scanInterval)) - .build(); - - JobDetail job = JobBuilder.newJob(FileScanJob.class) - .withIdentity(jobTriggerName, JOB_INITIALIZATION_PLUGIN_NAME) - .build(); - job.getJobDataMap().put(FileScanJob.FILE_NAME, jobFile.getFileName()); - job.getJobDataMap().put(FileScanJob.FILE_SCAN_LISTENER_NAME, JOB_INITIALIZATION_PLUGIN_NAME + '_' + name); - - scheduler.scheduleJob(job, trig); - log.debug("Scheduled file scan job for data file: {}, at interval: {}", jobFile.getFileName(), scanInterval); - } - - processFile(jobFile); - } - } - } catch(SchedulerException se) { - log.error("Error starting background-task for watching jobs file.", se); - } finally { - started = true; - } - } - - /** - * Helper method for generating unique job/trigger name for the - * file scanning jobs (one per FileJob). The unique names are saved - * in jobTriggerNameSet. - */ - private String buildJobTriggerName( - String fileBasename) { - // Name w/o collisions will be prefix + _ + filename (with '.' of filename replaced with '_') - // For example: JobInitializationPlugin_jobInitializer_myjobs_xml - String jobTriggerName = JOB_INITIALIZATION_PLUGIN_NAME + '_' + name + '_' + fileBasename.replace('.', '_'); - - // If name is too long (DB column is 80 chars), then truncate to max length - if (jobTriggerName.length() > MAX_JOB_TRIGGER_NAME_LEN) { - jobTriggerName = jobTriggerName.substring(0, MAX_JOB_TRIGGER_NAME_LEN); - } - - // Make sure this name is unique in case the same file name under different - // directories is being checked, or had a naming collision due to length truncation. - // If there is a conflict, keep incrementing a _# suffix on the name (being sure - // not to get too long), until we find a unique name. - int currentIndex = 1; - while (jobTriggerNameSet.add(jobTriggerName) == false) { - // If not our first time through, then strip off old numeric suffix - if (currentIndex > 1) { - jobTriggerName = jobTriggerName.substring(0, jobTriggerName.lastIndexOf('_')); - } - - String numericSuffix = "_" + currentIndex++; - - // If the numeric suffix would make the name too long, then make room for it. - if (jobTriggerName.length() > (MAX_JOB_TRIGGER_NAME_LEN - numericSuffix.length())) { - jobTriggerName = jobTriggerName.substring(0, (MAX_JOB_TRIGGER_NAME_LEN - numericSuffix.length())); - } - - jobTriggerName += numericSuffix; - } - - return jobTriggerName; - } - - @Override - public void shutdown() { - // nothing to do - } - - private void processFile(JobFile jobFile) { - if (jobFile == null || !jobFile.getFileFound()) { - return; - } - - try { - XMLSchedulingDataProcessor processor = - new XMLSchedulingDataProcessor(this.classLoadHelper); - - processor.addJobGroupToNeverDelete(JOB_INITIALIZATION_PLUGIN_NAME); - processor.addTriggerGroupToNeverDelete(JOB_INITIALIZATION_PLUGIN_NAME); - - processor.processFileAndScheduleJobs( - jobFile.getFileName(), - jobFile.getFileName(), // systemId - scheduler); - } catch (Exception e) { - log.error("Error scheduling jobs: " + e.getMessage(), e); - } - } - - public void processFile(String filePath) { - processFile((JobFile)jobFiles.get(filePath)); - } - - /** - * @see org.quartz.jobs.FileScanListener#fileUpdated(java.lang.String) - */ - public void fileUpdated(String fileName) { - if (started) { - processFile(fileName); - } - } - - class JobFile { - private String fileName; - - // These are set by initialize() - private String filePath; - private String fileBasename; - private boolean fileFound; - - protected JobFile(String fileName) throws SchedulerException { - this.fileName = fileName; - initialize(); - } - - protected String getFileName() { - return fileName; - } - - protected boolean getFileFound() { - return fileFound; - } - - protected String getFilePath() { - return filePath; - } - - protected String getFileBasename() { - return fileBasename; - } - - private void initialize() throws SchedulerException { - InputStream f = null; - try { - String furl = null; - - File file = new File(getFileName()); // files in filesystem - if (!file.exists()) { - URL url = classLoadHelper.getResource(getFileName()); - if(url != null) { - try { - furl = URLDecoder.decode(url.getPath(), "UTF-8"); - } catch (UnsupportedEncodingException e) { - furl = url.getPath(); - } - file = new File(furl); - try { - f = url.openStream(); - } catch (IOException ignore) { - // Swallow the exception - } - } - } else { - try { - f = new java.io.FileInputStream(file); - }catch (FileNotFoundException e) { - // ignore - } - } - - if (f == null) { - if (isFailOnFileNotFound()) { - throw new SchedulerException( - "File named '" + getFileName() + "' does not exist."); - } else { - log.warn("File named '" + getFileName() + "' does not exist."); - } - } else { - fileFound = true; - } - filePath = (furl != null) ? furl : file.getAbsolutePath(); - fileBasename = file.getName(); - } finally { - try { - if (f != null) { - f.close(); - } - } catch (IOException ioe) { - log.warn("Error closing jobs file " + getFileName(), ioe); - } - } - } - } -} \ No newline at end of file diff --git a/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/paas/service/taskqueue/TaskQueue.java b/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/paas/service/taskqueue/TaskQueue.java deleted file mode 100644 index e317a305cf..0000000000 --- a/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/paas/service/taskqueue/TaskQueue.java +++ /dev/null @@ -1,107 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.paas.service.taskqueue; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; -import static java.lang.String.format; - -import java.util.Timer; -import java.util.TimerTask; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.TimeUnit; - -import org.jclouds.demo.paas.RunnableHttpRequest; -import org.jclouds.demo.paas.RunnableHttpRequest.Factory; -import org.jclouds.http.HttpCommandExecutorService; - -import com.google.inject.Provider; - -public class TaskQueue { - protected final Factory httpRequestFactory; - private final Timer timer; - private final ConcurrentLinkedQueue tasks = new ConcurrentLinkedQueue(); - - private TaskQueue(String name, long pollingIntervalMillis, Factory httpRequestFactory) { - this.httpRequestFactory = httpRequestFactory; - timer = new Timer(name); - timer.scheduleAtFixedRate(new TimerTask() { - @Override - public void run() { - Runnable task = tasks.poll(); - if (task != null) { - task.run(); - } - } - }, 0, pollingIntervalMillis); - } - - public void add(final Runnable task) { - tasks.add(task); - } - - public Factory getHttpRequestFactory() { - return httpRequestFactory; - } - - public void destroy() { - timer.cancel(); - tasks.clear(); - } - - public static Builder builder(HttpCommandExecutorService httpClient) { - return new Builder(httpClient); - } - - public static class Builder implements Provider { - protected final HttpCommandExecutorService httpClient; - protected String name = "default"; - protected long pollingIntervalMillis = TimeUnit.SECONDS.toMillis(1); - - private Builder(HttpCommandExecutorService httpClient) { - this.httpClient = checkNotNull(httpClient, "httpClient"); - } - - public Builder name(String name) { - this.name = checkNotNull(name, "name"); - return this; - } - - public Builder period(TimeUnit period) { - this.pollingIntervalMillis = checkNotNull(period, "period").toMillis(1); - return this; - } - - public Builder period(long pollingIntervalMillis) { - checkArgument(pollingIntervalMillis > 0, "pollingIntervalMillis"); - this.pollingIntervalMillis = pollingIntervalMillis; - return this; - } - - public TaskQueue build() { - return new TaskQueue(name, pollingIntervalMillis, - RunnableHttpRequest.factory(httpClient, format("taskqueue-%s", name))); - } - - @Override - public TaskQueue get() { - return build(); - } - } -} \ No newline at end of file diff --git a/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/config/GuiceServletConfig.java b/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/config/GuiceServletConfig.java deleted file mode 100644 index c03434388a..0000000000 --- a/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/config/GuiceServletConfig.java +++ /dev/null @@ -1,155 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.config; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Preconditions.checkState; -import static com.google.common.base.Predicates.in; -import static com.google.common.collect.ImmutableSet.copyOf; -import static com.google.common.collect.Sets.filter; -import static org.jclouds.demo.paas.reference.PaasConstants.PROPERTY_PLATFORM_BASE_URL; -import static org.jclouds.demo.tweetstore.reference.TweetStoreConstants.PROPERTY_TWEETSTORE_BLOBSTORES; -import static org.jclouds.demo.tweetstore.reference.TweetStoreConstants.PROPERTY_TWEETSTORE_CONTAINER; -import static org.jclouds.demo.tweetstore.reference.TwitterConstants.PROPERTY_TWITTER_ACCESSTOKEN; -import static org.jclouds.demo.tweetstore.reference.TwitterConstants.PROPERTY_TWITTER_ACCESSTOKEN_SECRET; -import static org.jclouds.demo.tweetstore.reference.TwitterConstants.PROPERTY_TWITTER_CONSUMER_KEY; -import static org.jclouds.demo.tweetstore.reference.TwitterConstants.PROPERTY_TWITTER_CONSUMER_SECRET; - -import java.util.Map; -import java.util.Properties; -import java.util.Set; - -import javax.servlet.ServletContext; -import javax.servlet.ServletContextEvent; - -import org.jclouds.ContextBuilder; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.demo.paas.PlatformServices; -import org.jclouds.demo.paas.service.taskqueue.TaskQueue; -import org.jclouds.demo.tweetstore.config.util.CredentialsCollector; -import org.jclouds.demo.tweetstore.config.util.PropertiesLoader; -import org.jclouds.demo.tweetstore.controller.AddTweetsController; -import org.jclouds.demo.tweetstore.controller.ClearTweetsController; -import org.jclouds.demo.tweetstore.controller.EnqueueStoresController; -import org.jclouds.demo.tweetstore.controller.StoreTweetsController; - -import twitter4j.Twitter; -import twitter4j.TwitterFactory; -import twitter4j.conf.Configuration; -import twitter4j.conf.ConfigurationBuilder; - -import com.google.common.base.Splitter; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Maps; -import com.google.inject.Guice; -import com.google.inject.Injector; -import com.google.inject.Module; -import com.google.inject.TypeLiteral; -import com.google.inject.name.Names; -import com.google.inject.servlet.GuiceServletContextListener; -import com.google.inject.servlet.ServletModule; - -/** - * Setup Logging and create Injector for use in testing S3. - * - * @author Adrian Cole - */ -public class GuiceServletConfig extends GuiceServletContextListener { - private Map providerTypeToBlobStoreMap; - private Twitter twitterClient; - private String container; - private TaskQueue queue; - private String baseUrl; - - @Override - public void contextInitialized(ServletContextEvent servletContextEvent) { - ServletContext servletContext = servletContextEvent.getServletContext(); - - Properties props = new PropertiesLoader(servletContext).get(); - Set modules = ImmutableSet.of(); - // shared across all blobstores and used to retrieve tweets - try { - Configuration twitterConf = new ConfigurationBuilder() - .setOAuthConsumerKey(props.getProperty(PROPERTY_TWITTER_CONSUMER_KEY)) - .setOAuthConsumerSecret(props.getProperty(PROPERTY_TWITTER_CONSUMER_SECRET)) - .setOAuthAccessToken(props.getProperty(PROPERTY_TWITTER_ACCESSTOKEN)) - .setOAuthAccessTokenSecret(props.getProperty(PROPERTY_TWITTER_ACCESSTOKEN_SECRET)) - .build(); - twitterClient = new TwitterFactory(twitterConf).getInstance(); - } catch (IllegalArgumentException e) { - throw new IllegalArgumentException("properties for twitter not configured properly in " + props.toString(), e); - } - // common namespace for storing tweets - container = checkNotNull(props.getProperty(PROPERTY_TWEETSTORE_CONTAINER), PROPERTY_TWEETSTORE_CONTAINER); - - // instantiate and store references to all blobstores by provider name - providerTypeToBlobStoreMap = Maps.newHashMap(); - for (String hint : getBlobstoreContexts(props)) { - providerTypeToBlobStoreMap.put(hint, ContextBuilder.newBuilder(hint) - .modules(modules).overrides(props).build(BlobStoreContext.class)); - } - - // get a queue for submitting store tweet requests and the application's base URL - PlatformServices platform = PlatformServices.get(servletContext); - queue = platform.getTaskQueue("twitter"); - baseUrl = platform.getBaseUrl(); - - super.contextInitialized(servletContextEvent); - } - - private static Iterable getBlobstoreContexts(Properties props) { - Set contexts = new CredentialsCollector().apply(props).keySet(); - String explicitContexts = props.getProperty(PROPERTY_TWEETSTORE_BLOBSTORES); - if (explicitContexts != null) { - contexts = filter(contexts, in(copyOf(Splitter.on(',').split(explicitContexts)))); - } - checkState(!contexts.isEmpty(), "no credentials available for any requested context"); - return contexts; - } - - @Override - protected Injector getInjector() { - return Guice.createInjector(new ServletModule() { - @Override - protected void configureServlets() { - bind(new TypeLiteral>() {}) - .toInstance(providerTypeToBlobStoreMap); - bind(Twitter.class).toInstance(twitterClient); - bind(TaskQueue.class).toInstance(queue); - bindConstant().annotatedWith(Names.named(PROPERTY_PLATFORM_BASE_URL)) - .to(baseUrl); - bindConstant().annotatedWith(Names.named(PROPERTY_TWEETSTORE_CONTAINER)) - .to(container); - serve("/store/*").with(StoreTweetsController.class); - serve("/tweets/*").with(AddTweetsController.class); - serve("/stores/*").with(EnqueueStoresController.class); - serve("/clear/*").with(ClearTweetsController.class); - } - }); - } - - @Override - public void contextDestroyed(ServletContextEvent servletContextEvent) { - for (BlobStoreContext context : providerTypeToBlobStoreMap.values()) { - context.close(); - } - queue.destroy(); - super.contextDestroyed(servletContextEvent); - } -} \ No newline at end of file diff --git a/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/config/util/CredentialsCollector.java b/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/config/util/CredentialsCollector.java deleted file mode 100644 index ce3943376e..0000000000 --- a/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/config/util/CredentialsCollector.java +++ /dev/null @@ -1,153 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.config.util; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Preconditions.checkState; -import static com.google.common.base.Predicates.notNull; -import static com.google.common.collect.Collections2.filter; -import static com.google.common.collect.Collections2.transform; -import static com.google.common.collect.ImmutableSet.copyOf; -import static com.google.common.collect.Maps.filterValues; -import static org.jclouds.util.Maps2.fromKeys; - -import java.util.Collection; -import java.util.Map; -import java.util.Properties; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.jclouds.demo.tweetstore.config.util.CredentialsCollector.Credential; - -import com.google.common.annotations.GwtIncompatible; -import com.google.common.base.Function; -import com.google.common.base.Predicate; - -/** - * Reads provider credentials from a {@link Properties} bag. - * - * @author Andrew Phillips - * - */ -public class CredentialsCollector implements Function> { - private static final String IDENTITY_PROPERTY_SUFFIX = ".identity"; - private static final String CREDENTIAL_PROPERTY_SUFFIX = ".credential"; - - // using the identity for provider name extraction - private static final Pattern IDENTITY_PROPERTY_PATTERN = - Pattern.compile("([a-zA-Z0-9-]+)" + Pattern.quote(IDENTITY_PROPERTY_SUFFIX)); - - @Override - public Map apply(final Properties properties) { - Collection providerNames = transform( - filter(properties.stringPropertyNames(), MatchesPattern.matches(IDENTITY_PROPERTY_PATTERN)), - new Function() { - @Override - public String apply(String input) { - Matcher matcher = IDENTITY_PROPERTY_PATTERN.matcher(input); - // as a side-effect, sets the matching group! - checkState(matcher.matches(), "'%s' should match '%s'", input, IDENTITY_PROPERTY_PATTERN); - return matcher.group(1); - } - }); - /* - * Providers without a credential property result in null values, which are - * removed from the returned map. - */ - return filterValues(fromKeys(copyOf(providerNames), new Function() { - @Override - public Credential apply(String providerName) { - String identity = properties.getProperty(providerName + IDENTITY_PROPERTY_SUFFIX); - String credential = properties.getProperty(providerName + CREDENTIAL_PROPERTY_SUFFIX); - return (((identity != null) && (credential != null)) - ? new Credential(identity, credential) - : null); - } - }), notNull()); - } - - public static class Credential { - private final String identity; - private final String credential; - - public Credential(String identity, String credential) { - this.identity = checkNotNull(identity, "identity"); - this.credential = checkNotNull(credential, "credential"); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result - + ((credential == null) ? 0 : credential.hashCode()); - result = prime * result - + ((identity == null) ? 0 : identity.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Credential other = (Credential) obj; - if (credential == null) { - if (other.credential != null) - return false; - } else if (!credential.equals(other.credential)) - return false; - if (identity == null) { - if (other.identity != null) - return false; - } else if (!identity.equals(other.identity)) - return false; - return true; - } - - public String getIdentity() { - return identity; - } - - public String getCredential() { - return credential; - } - } - - @GwtIncompatible(value = "java.util.regex.Pattern") - private static class MatchesPattern implements Predicate { - private final Pattern pattern; - - private MatchesPattern(Pattern pattern) { - this.pattern = pattern; - } - - @Override - public boolean apply(String input) { - return pattern.matcher(input).matches(); - } - - private static MatchesPattern matches(Pattern pattern) { - return new MatchesPattern(pattern); - } - } -} diff --git a/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/config/util/PropertiesLoader.java b/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/config/util/PropertiesLoader.java deleted file mode 100644 index dafa5c311b..0000000000 --- a/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/config/util/PropertiesLoader.java +++ /dev/null @@ -1,59 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.config.util; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; - -import javax.servlet.ServletContext; - -import com.google.common.io.Closeables; -import com.google.inject.Provider; - -/** - * @author Andrew Phillips - */ -public class PropertiesLoader implements Provider{ - private static final String PROPERTIES_FILE = "/WEB-INF/jclouds.properties"; - - private final Properties properties; - - public PropertiesLoader(ServletContext context) { - properties = loadJcloudsProperties(context); - } - - private static Properties loadJcloudsProperties(ServletContext context) { - InputStream input = context.getResourceAsStream(PROPERTIES_FILE); - Properties props = new Properties(); - try { - props.load(input); - } catch (IOException e) { - throw new RuntimeException(e); - } finally { - Closeables.closeQuietly(input); - } - return props; - } - - @Override - public Properties get() { - return properties; - } -} diff --git a/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/controller/AddTweetsController.java b/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/controller/AddTweetsController.java deleted file mode 100644 index 007fbafdef..0000000000 --- a/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/controller/AddTweetsController.java +++ /dev/null @@ -1,96 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.controller; - -import java.io.IOException; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeoutException; - -import javax.annotation.Resource; -import javax.inject.Inject; -import javax.inject.Singleton; -import javax.servlet.RequestDispatcher; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.demo.tweetstore.domain.StoredTweetStatus; -import org.jclouds.demo.tweetstore.functions.ServiceToStoredTweetStatuses; -import org.jclouds.logging.Logger; - -import com.google.common.base.Function; -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; - -/** - * Shows an example of how to use @{link BlobStoreContext} injected with Guice. - * - * @author Adrian Cole - */ -@Singleton -public class AddTweetsController extends HttpServlet implements - Function, List> { - - /** The serialVersionUID */ - private static final long serialVersionUID = 3888348023150822683L; - private final Map contexts; - private final ServiceToStoredTweetStatuses blobStoreContextToContainerResult; - - @Resource - protected Logger logger = Logger.NULL; - - @Inject - AddTweetsController(Map contexts, - ServiceToStoredTweetStatuses blobStoreContextToContainerResult) { - this.contexts = contexts; - this.blobStoreContextToContainerResult = blobStoreContextToContainerResult; - } - - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) - throws ServletException, IOException { - try { - addMyTweetsToRequest(request); - RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/tweets.jsp"); - dispatcher.forward(request, response); - } catch (Exception e) { - logger.error(e, "Error listing containers"); - throw new ServletException(e); - } - } - - void addMyTweetsToRequest(HttpServletRequest request) throws InterruptedException, - ExecutionException, TimeoutException { - request.setAttribute("tweets", apply(contexts.keySet())); - } - - public List apply(Set in) { - List statuses = Lists.newArrayList(); - for (Iterable list : Iterables.transform(in, - blobStoreContextToContainerResult)) { - Iterables.addAll(statuses, list); - } - return statuses; - } -} diff --git a/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/controller/ClearTweetsController.java b/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/controller/ClearTweetsController.java deleted file mode 100644 index e08cfbc19e..0000000000 --- a/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/controller/ClearTweetsController.java +++ /dev/null @@ -1,96 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.controller; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Strings.nullToEmpty; - -import java.io.IOException; -import java.util.Map; - -import javax.annotation.Resource; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.core.MediaType; - -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.jclouds.logging.Logger; - -import com.google.common.annotations.VisibleForTesting; - -/** - * Grab tweets related to me and store them into blobstores - * - * @author Adrian Cole - */ -@Singleton -public class ClearTweetsController extends HttpServlet { - /** The serialVersionUID */ - private static final long serialVersionUID = 7215420527854203714L; - - private final Map contexts; - private final String container; - - @Resource - protected Logger logger = Logger.NULL; - - @Inject - @VisibleForTesting - public ClearTweetsController(Map contexts, - @Named(TweetStoreConstants.PROPERTY_TWEETSTORE_CONTAINER) String container) { - this.container = container; - this.contexts = contexts; - } - - @VisibleForTesting - public void clearContainer(String contextName) { - BlobStoreContext context = checkNotNull(contexts.get(contextName), - "no context for %s in %s", contextName, contexts.keySet()); - try { - context.getBlobStore().clearContainer(container); - } catch (Exception e) { - logger.error(e, "Error clearing tweets in %s/%s", container, context); - } - } - - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - if (nullToEmpty(request.getHeader("X-Originator")).equals("admin")) { - try { - String contextName = checkNotNull(request.getHeader("context"), "missing header context"); - logger.info("clearing tweets in %s/%s", container, contextName); - clearContainer(contextName); - logger.debug("done clearing tweets"); - response.setContentType(MediaType.TEXT_PLAIN); - response.getWriter().println("Done!"); - } catch (Exception e) { - logger.error(e, "Error clearing tweets"); - throw new ServletException(e); - } - } else { - response.sendError(401); - } - } -} \ No newline at end of file diff --git a/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/controller/EnqueueStoresController.java b/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/controller/EnqueueStoresController.java deleted file mode 100644 index 592eaaa8bd..0000000000 --- a/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/controller/EnqueueStoresController.java +++ /dev/null @@ -1,101 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.controller; - -import static com.google.common.base.Strings.nullToEmpty; -import static org.jclouds.demo.paas.RunnableHttpRequest.PLATFORM_REQUEST_ORIGINATOR_HEADER; - -import java.io.IOException; -import java.net.URI; -import java.util.Map; -import java.util.Set; - -import javax.annotation.Resource; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.core.MediaType; - -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.demo.paas.reference.PaasConstants; -import org.jclouds.demo.paas.service.taskqueue.TaskQueue; -import org.jclouds.http.HttpRequest; -import org.jclouds.logging.Logger; - -import com.google.common.annotations.VisibleForTesting; -import com.google.common.collect.ImmutableMultimap; - -/** - * Adds tasks to retrieve and store tweets in all registered contexts to an async - * task queue. - * - * @author Andrew Phillips - * @see StoreTweetsController - */ -@Singleton -public class EnqueueStoresController extends HttpServlet { - /** The serialVersionUID */ - private static final long serialVersionUID = 7215420527854203714L; - - private final Set contextNames; - private final TaskQueue taskQueue; - private final String baseUrl; - - @Resource - protected Logger logger = Logger.NULL; - - @Inject - public EnqueueStoresController(Map contexts, TaskQueue taskQueue, - @Named(PaasConstants.PROPERTY_PLATFORM_BASE_URL) String baseUrl) { - contextNames = contexts.keySet(); - this.taskQueue = taskQueue; - this.baseUrl = baseUrl; - } - - @VisibleForTesting - void enqueueStoreTweetTasks() { - for (String contextName : contextNames) { - logger.debug("enqueuing task to store tweets in blobstore '%s'", contextName); - taskQueue.add(taskQueue.getHttpRequestFactory().create(HttpRequest.builder() - .endpoint(URI.create(baseUrl + "/store/do")) - .headers(ImmutableMultimap.of("context", contextName)) - .method("GET").build())); - } - } - - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - if (!nullToEmpty(request.getHeader(PLATFORM_REQUEST_ORIGINATOR_HEADER)).equals("scheduler")) { - response.sendError(401); - } - - try { - enqueueStoreTweetTasks(); - response.setContentType(MediaType.TEXT_PLAIN); - response.getWriter().println("Done!"); - } catch (Exception e) { - logger.error(e, "Error storing tweets"); - throw new ServletException(e); - } - } -} \ No newline at end of file diff --git a/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/controller/StoreTweetsController.java b/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/controller/StoreTweetsController.java deleted file mode 100644 index 948c9ff4ca..0000000000 --- a/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/controller/StoreTweetsController.java +++ /dev/null @@ -1,130 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.controller; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Strings.nullToEmpty; -import static org.jclouds.demo.paas.RunnableHttpRequest.PLATFORM_REQUEST_ORIGINATOR_HEADER; - -import java.io.IOException; -import java.util.Map; - -import javax.annotation.Resource; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.ws.rs.core.MediaType; - -import org.jclouds.blobstore.BlobMap; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.blobstore.domain.Blob; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.jclouds.logging.Logger; -import org.jclouds.rest.AuthorizationException; - -import twitter4j.Status; -import twitter4j.Twitter; - -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Function; - -/** - * Grab tweets related to me and store them into blobstores - * - * @author Adrian Cole - */ -@Singleton -public class StoreTweetsController extends HttpServlet { - - private static final class StatusToBlob implements Function { - private final BlobMap map; - - private StatusToBlob(BlobMap map) { - this.map = map; - } - - public Blob apply(Status from) { - Blob to = map.blobBuilder().name(from.getId() + "").build(); - to.setPayload(from.getText()); - to.getPayload().getContentMetadata().setContentType(MediaType.TEXT_PLAIN); - to.getMetadata().getUserMetadata().put(TweetStoreConstants.SENDER_NAME, from.getUser().getScreenName()); - return to; - } - } - - /** The serialVersionUID */ - private static final long serialVersionUID = 7215420527854203714L; - - private final Map contexts; - private final Twitter client; - private final String container; - - @Resource - protected Logger logger = Logger.NULL; - - @Inject - @VisibleForTesting - public StoreTweetsController(Map contexts, - @Named(TweetStoreConstants.PROPERTY_TWEETSTORE_CONTAINER) String container, Twitter client) { - this.container = container; - this.contexts = contexts; - this.client = client; - } - - @VisibleForTesting - public void addMyTweets(String contextName, Iterable responseList) { - BlobStoreContext context = checkNotNull(contexts.get(contextName), "no context for " + contextName + " in " - + contexts.keySet()); - BlobMap map = context.createBlobMap(container); - for (Status status : responseList) { - Blob blob = null; - try { - blob = new StatusToBlob(map).apply(status); - map.put(status.getId() + "", blob); - } catch (AuthorizationException e) { - throw e; - } catch (Exception e) { - logger.error(e, "Error storing tweet %s (blob[%s]) on map %s/%s", status.getId(), blob, context, container); - } - } - } - - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - if (nullToEmpty(request.getHeader(PLATFORM_REQUEST_ORIGINATOR_HEADER)).equals("taskqueue-twitter")) { - try { - String contextName = checkNotNull(request.getHeader("context"), "missing header context"); - logger.info("retrieving tweets"); - addMyTweets(contextName, client.getMentions()); - logger.debug("done storing tweets"); - response.setContentType(MediaType.TEXT_PLAIN); - response.getWriter().println("Done!"); - } catch (Exception e) { - logger.error(e, "Error storing tweets"); - throw new ServletException(e); - } - } else { - response.sendError(401); - } - } -} \ No newline at end of file diff --git a/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/domain/StoredTweetStatus.java b/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/domain/StoredTweetStatus.java deleted file mode 100644 index 42ad65df01..0000000000 --- a/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/domain/StoredTweetStatus.java +++ /dev/null @@ -1,149 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.domain; - -import java.io.Serializable; - -/** - * - * @author Adrian Cole - */ -public class StoredTweetStatus implements Comparable, Serializable { - - /** The serialVersionUID */ - private static final long serialVersionUID = -3257496189689220018L; - private final String service; - private final String host; - private final String container; - private final String id; - private final String from; - private final String tweet; - private final String status; - - @Override - public String toString() { - return "StoredTweetStatus [container=" + container + ", from=" + from + ", host=" + host - + ", id=" + id + ", service=" + service + ", status=" + status + ", tweet=" + tweet - + "]"; - } - - public StoredTweetStatus(String service, String host, String container, String id, String from, - String tweet, String status) { - this.service = service; - this.host = host; - this.container = container; - this.id = id; - this.from = from; - this.tweet = tweet; - this.status = status; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((container == null) ? 0 : container.hashCode()); - result = prime * result + ((from == null) ? 0 : from.hashCode()); - result = prime * result + ((host == null) ? 0 : host.hashCode()); - result = prime * result + ((id == null) ? 0 : id.hashCode()); - result = prime * result + ((service == null) ? 0 : service.hashCode()); - result = prime * result + ((tweet == null) ? 0 : tweet.hashCode()); - return result; - } - - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - StoredTweetStatus other = (StoredTweetStatus) obj; - if (container == null) { - if (other.container != null) - return false; - } else if (!container.equals(other.container)) - return false; - if (from == null) { - if (other.from != null) - return false; - } else if (!from.equals(other.from)) - return false; - if (host == null) { - if (other.host != null) - return false; - } else if (!host.equals(other.host)) - return false; - if (id == null) { - if (other.id != null) - return false; - } else if (!id.equals(other.id)) - return false; - if (service == null) { - if (other.service != null) - return false; - } else if (!service.equals(other.service)) - return false; - if (tweet == null) { - if (other.tweet != null) - return false; - } else if (!tweet.equals(other.tweet)) - return false; - return true; - } - - - public String getService() { - return service; - } - - public String getHost() { - return host; - } - - public String getContainer() { - return container; - } - - public String getFrom() { - return from; - } - - public String getTweet() { - return tweet; - } - - public String getStatus() { - return status; - } - - public int compareTo(StoredTweetStatus o) { - if (id == null) - return -1; - return (int) ((this == o) ? 0 : id.compareTo(o.id)); - } - - - public String getId() { - return id; - } - -} diff --git a/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/functions/KeyToStoredTweetStatus.java b/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/functions/KeyToStoredTweetStatus.java deleted file mode 100644 index f831b9780f..0000000000 --- a/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/functions/KeyToStoredTweetStatus.java +++ /dev/null @@ -1,70 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.functions; - -import javax.annotation.Resource; - -import org.jclouds.blobstore.BlobMap; -import org.jclouds.blobstore.domain.Blob; -import org.jclouds.demo.tweetstore.domain.StoredTweetStatus; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.jclouds.logging.Logger; -import org.jclouds.util.Strings2; - -import com.google.common.base.Function; - -/** - * - * @author Adrian Cole - */ -public class KeyToStoredTweetStatus implements Function { - private final String host; - private final BlobMap map; - private final String service; - private final String container; - - @Resource - protected Logger logger = Logger.NULL; - - KeyToStoredTweetStatus(BlobMap map, String service, String host, String container) { - this.host = host; - this.map = map; - this.service = service; - this.container = container; - } - - public StoredTweetStatus apply(String id) { - String status; - String from; - String tweet; - try { - long start = System.currentTimeMillis(); - Blob blob = map.get(id); - status = ((System.currentTimeMillis() - start) + "ms"); - from = blob.getMetadata().getUserMetadata().get(TweetStoreConstants.SENDER_NAME); - tweet = Strings2.toString(blob.getPayload()); - } catch (Exception e) { - logger.error(e, "Error listing container %s//%s/%s", service, container, id); - status = (e.getMessage()); - tweet = ""; - from = ""; - } - return new StoredTweetStatus(service, host, container, id, from, tweet, status); - } -} diff --git a/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/functions/ServiceToStoredTweetStatuses.java b/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/functions/ServiceToStoredTweetStatuses.java deleted file mode 100644 index b29ec14549..0000000000 --- a/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/functions/ServiceToStoredTweetStatuses.java +++ /dev/null @@ -1,73 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.functions; - -import java.net.URI; -import java.util.Collections; -import java.util.Map; -import java.util.Set; - -import javax.annotation.Resource; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - -import org.jclouds.Context; -import org.jclouds.blobstore.BlobMap; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.demo.tweetstore.domain.StoredTweetStatus; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.jclouds.logging.Logger; - -import com.google.common.base.Function; -import com.google.common.collect.Iterables; - -@Singleton -public class ServiceToStoredTweetStatuses implements Function> { - - private final Map contexts; - private final String container; - - @Inject - public ServiceToStoredTweetStatuses(Map contexts, - @Named(TweetStoreConstants.PROPERTY_TWEETSTORE_CONTAINER) String container) { - this.contexts = contexts; - this.container = container; - } - - @Resource - protected Logger logger = Logger.NULL; - - public Iterable apply(String service) { - BlobStoreContext context = contexts.get(service); - String host = URI.create(context.unwrap(Context.class).getProviderMetadata().getEndpoint()).getHost(); - try { - BlobMap blobMap = context.createBlobMap(container); - Set blobs = blobMap.keySet(); - return Iterables.transform(blobs, new KeyToStoredTweetStatus(blobMap, service, host, - container)); - } catch (Exception e) { - StoredTweetStatus result = new StoredTweetStatus(service, host, container, null, null, - null, e.getMessage()); - logger.error(e, "Error listing service %s", service); - return Collections.singletonList(result); - } - - } -} \ No newline at end of file diff --git a/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/reference/TweetStoreConstants.java b/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/reference/TweetStoreConstants.java deleted file mode 100644 index 42ec480ae2..0000000000 --- a/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/reference/TweetStoreConstants.java +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.reference; - -/** - * Configuration properties and constants used in TweetStore connections. - * - * @author Adrian Cole - */ -public interface TweetStoreConstants { - static final String PROPERTY_TWEETSTORE_BLOBSTORES = "jclouds.tweetstore.blobstores"; - static final String PROPERTY_TWEETSTORE_CONTAINER = "jclouds.tweetstore.container"; - /** - * Note that this has to conform to restrictions of all blobstores. for - * example, azure doesn't support periods. - */ - static final String SENDER_NAME = "sendername"; -} diff --git a/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/reference/TwitterConstants.java b/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/reference/TwitterConstants.java deleted file mode 100644 index dc8b97915f..0000000000 --- a/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/tweetstore/reference/TwitterConstants.java +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.reference; - -/** - * Configuration properties and constants used in Twitter connections. - * - * @author Andrew Phillips - */ -public interface TwitterConstants { - static final String PROPERTY_TWITTER_CONSUMER_KEY = "twitter.consumer.identity"; - static final String PROPERTY_TWITTER_CONSUMER_SECRET = "twitter.consumer.credential"; - static final String PROPERTY_TWITTER_ACCESSTOKEN = "twitter.access.identity"; - static final String PROPERTY_TWITTER_ACCESSTOKEN_SECRET = "twitter.access.credential"; -} diff --git a/demos/tweetstore/runatcloud-tweetstore/src/main/platform/cloudbees-web.xml b/demos/tweetstore/runatcloud-tweetstore/src/main/platform/cloudbees-web.xml deleted file mode 100644 index 3fb9478938..0000000000 --- a/demos/tweetstore/runatcloud-tweetstore/src/main/platform/cloudbees-web.xml +++ /dev/null @@ -1,40 +0,0 @@ - - - - ${bees.appid} - - - - application.host - ${test.bees.address}:${test.bees.port} - - - - - - - application.host - ${bees.apptitle}.jclouds.cloudbees.net - - - \ No newline at end of file diff --git a/demos/tweetstore/runatcloud-tweetstore/src/main/resources/jobs.xml b/demos/tweetstore/runatcloud-tweetstore/src/main/resources/jobs.xml deleted file mode 100644 index b740fdd52f..0000000000 --- a/demos/tweetstore/runatcloud-tweetstore/src/main/resources/jobs.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - enqueue-store-tweet-tasks - Enqueue 'store tweet' tasks for all contexts - org.jclouds.demo.paas.service.scheduler.HttpRequestJob - - - url - /stores/do - - - - - - - submit-recurring-job - enqueue-store-tweet-tasks - 10 - MINUTE - - - - \ No newline at end of file diff --git a/demos/tweetstore/runatcloud-tweetstore/src/main/resources/quartz.properties b/demos/tweetstore/runatcloud-tweetstore/src/main/resources/quartz.properties deleted file mode 100644 index 12a0fcfe91..0000000000 --- a/demos/tweetstore/runatcloud-tweetstore/src/main/resources/quartz.properties +++ /dev/null @@ -1,28 +0,0 @@ -#============================================================================ -# Configure Main Scheduler Properties -#============================================================================ - -org.quartz.scheduler.skipUpdateCheck: true - -#============================================================================ -# Configure ThreadPool -#============================================================================ - -org.quartz.threadPool.class: org.quartz.simpl.SimpleThreadPool -org.quartz.threadPool.threadCount: 1 - -#============================================================================ -# Configure JobStore -#============================================================================ - -org.quartz.jobStore.class: org.quartz.simpl.RAMJobStore - -#============================================================================ -# Configure the Job Initialization Plugin -#============================================================================ - -org.quartz.plugin.jobInitializer.class: org.jclouds.demo.paas.service.scheduler.quartz.plugins.TransactionlessXmlSchedulingDataProcessorPlugin -org.quartz.plugin.jobInitializer.fileNames: jobs.xml -org.quartz.plugin.jobInitializer.failOnFileNotFound: true -org.quartz.plugin.jobInitializer.scanInterval: 0 -#org.quartz.plugin.jobInitializer.wrapInUserTransaction: false \ No newline at end of file diff --git a/demos/tweetstore/runatcloud-tweetstore/src/main/webapp/WEB-INF/web.xml b/demos/tweetstore/runatcloud-tweetstore/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index 9482bd9d9e..0000000000 --- a/demos/tweetstore/runatcloud-tweetstore/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,60 +0,0 @@ - - - - jclouds-tweetstore - - - quartz:scheduler-context-servlet-context-key - servlet-context - - - - - guiceFilter - com.google.inject.servlet.GuiceFilter - - - - guiceFilter - /* - - - - - org.jclouds.demo.paas.config.PlatformServicesInitializer - - - - org.quartz.ee.servlet.QuartzInitializerListener - - - - org.jclouds.demo.tweetstore.config.GuiceServletConfig - - - - index.jsp - - - \ No newline at end of file diff --git a/demos/tweetstore/runatcloud-tweetstore/src/main/webapp/index.jsp b/demos/tweetstore/runatcloud-tweetstore/src/main/webapp/index.jsp deleted file mode 100644 index d8d1724bcf..0000000000 --- a/demos/tweetstore/runatcloud-tweetstore/src/main/webapp/index.jsp +++ /dev/null @@ -1,31 +0,0 @@ -<%-- - - Licensed to jclouds, Inc. (jclouds) under one or more - contributor license agreements. See the NOTICE file - distributed with this work for additional information - regarding copyright ownership. jclouds licenses this file - to you under the Apache License, Version 2.0 (the - "License"); you may not use this file except in compliance - with the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, - software distributed under the License is distributed on an - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - KIND, either express or implied. See the License for the - specific language governing permissions and limitations - under the License. - ---%> - - -jclouds: anyweight cloudware for java - - -

Welcome!

-

Click here to see tweets about jclouds.

-

- - diff --git a/demos/tweetstore/runatcloud-tweetstore/src/main/webapp/tweets.jsp b/demos/tweetstore/runatcloud-tweetstore/src/main/webapp/tweets.jsp deleted file mode 100644 index 1b30f7ea11..0000000000 --- a/demos/tweetstore/runatcloud-tweetstore/src/main/webapp/tweets.jsp +++ /dev/null @@ -1,109 +0,0 @@ -<%-- - - Licensed to jclouds, Inc. (jclouds) under one or more - contributor license agreements. See the NOTICE file - distributed with this work for additional information - regarding copyright ownership. jclouds licenses this file - to you under the Apache License, Version 2.0 (the - "License"); you may not use this file except in compliance - with the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, - software distributed under the License is distributed on an - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - KIND, either express or implied. See the License for the - specific language governing permissions and limitations - under the License. - ---%> -<%@ page buffer="20kb"%> -<%@ taglib uri="http://displaytag.sf.net" prefix="display"%> - - -jclouds: anyweight cloudware for java - - - -

Tweets in Clouds

- - - - - - - -
-
- - - - - - - - -
-
- - diff --git a/demos/tweetstore/runatcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/config/util/CredentialsCollectorTest.java b/demos/tweetstore/runatcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/config/util/CredentialsCollectorTest.java deleted file mode 100644 index 031bb199fc..0000000000 --- a/demos/tweetstore/runatcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/config/util/CredentialsCollectorTest.java +++ /dev/null @@ -1,82 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.config.util; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; - -import java.util.Map; -import java.util.Properties; - -import org.jclouds.demo.tweetstore.config.util.CredentialsCollector; -import org.jclouds.demo.tweetstore.config.util.CredentialsCollector.Credential; -import org.testng.annotations.Test; - -import com.google.common.collect.ImmutableMap; - -/** - * Tests behavior of {@code CredentialsCollector} - * - * @author Andrew Phillips - */ -@Test(groups = "unit") -public class CredentialsCollectorTest { - private CredentialsCollector collector = new CredentialsCollector(); - - public void testEmptyProperties() { - assertTrue(collector.apply(new Properties()).isEmpty(), - "Expected returned map to be empty"); - } - - public void testNoCredentials() { - Properties properties = propertiesOf(ImmutableMap.of("not-an-identity", - "v1", "not-a-credential", "v2")); - assertTrue(collector.apply(properties).isEmpty(), - "Expected returned map to be empty"); - } - - private static Properties propertiesOf(Map entries) { - Properties properties = new Properties(); - properties.putAll(entries); - return properties; - } - - public void testNonMatchingCredentials() { - Properties properties = propertiesOf(ImmutableMap.of("non_matching.identity", "v1", - "non_matching.credential", "v2")); - assertTrue(collector.apply(properties).isEmpty(), - "Expected returned map to be empty"); - } - - public void testIncompleteCredentials() { - Properties properties = propertiesOf(ImmutableMap.of("acme.identity", "v1", - "acme-2.credential", "v2")); - assertTrue(collector.apply(properties).isEmpty(), - "Expected returned map to be empty"); - } - - public void testCredentials() { - Properties properties = propertiesOf(ImmutableMap.of("acme.identity", "v1", - "acme.credential", "v2", "acme-2.identity", "v3", - "acme-2.credential", "v4")); - assertEquals(collector.apply(properties), - ImmutableMap.of("acme", new Credential("v1", "v2"), - "acme-2", new Credential("v3", "v4"))); - } -} \ No newline at end of file diff --git a/demos/tweetstore/runatcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/AddTweetsControllerTest.java b/demos/tweetstore/runatcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/AddTweetsControllerTest.java deleted file mode 100644 index 1c93403650..0000000000 --- a/demos/tweetstore/runatcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/AddTweetsControllerTest.java +++ /dev/null @@ -1,78 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.controller; - -import static org.testng.Assert.assertEquals; - -import java.io.IOException; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ExecutionException; - -import org.jclouds.ContextBuilder; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.blobstore.TransientApiMetadata; -import org.jclouds.blobstore.domain.Blob; -import org.jclouds.demo.tweetstore.domain.StoredTweetStatus; -import org.jclouds.demo.tweetstore.functions.ServiceToStoredTweetStatuses; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.testng.annotations.Test; -import org.testng.collections.Maps; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableSet; - -/** - * Tests behavior of {@code AddTweetsController} - * - * @author Adrian Cole - */ -@Test(groups = "unit") -public class AddTweetsControllerTest { - - Map createServices(String container) throws InterruptedException, - ExecutionException { - Map services = Maps.newHashMap(); - TransientApiMetadata transientApiMetadata = TransientApiMetadata.builder().build(); - for (String name : new String[] { "1", "2" }) { - BlobStoreContext context = ContextBuilder.newBuilder(transientApiMetadata).build(BlobStoreContext.class); - context.getAsyncBlobStore().createContainerInLocation(null, container).get(); - Blob blob = context.getAsyncBlobStore().blobBuilder("1").build(); - blob.getMetadata().getUserMetadata().put(TweetStoreConstants.SENDER_NAME, "frank"); - blob.setPayload("I love beans!"); - context.getAsyncBlobStore().putBlob(container, blob).get(); - services.put(name, context); - } - return services; - } - - public void testStoreTweets() throws IOException, InterruptedException, ExecutionException { - String container = "container"; - Map contexts = createServices(container); - - ServiceToStoredTweetStatuses function = new ServiceToStoredTweetStatuses(contexts, container); - AddTweetsController controller = new AddTweetsController(contexts, function); - List list = controller.apply(ImmutableSet.of("1", "2")); - assertEquals(list.size(), 2); - assertEquals(list, ImmutableList.of(new StoredTweetStatus("1", "localhost", container, "1", - "frank", "I love beans!", null), new StoredTweetStatus("2", "localhost", container, - "1", "frank", "I love beans!", null))); - - } -} diff --git a/demos/tweetstore/runatcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/ClearTweetsControllerTest.java b/demos/tweetstore/runatcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/ClearTweetsControllerTest.java deleted file mode 100644 index 81f0b9f3c7..0000000000 --- a/demos/tweetstore/runatcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/ClearTweetsControllerTest.java +++ /dev/null @@ -1,72 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.controller; - -import static org.testng.Assert.assertEquals; - -import java.io.IOException; -import java.util.Map; -import java.util.concurrent.ExecutionException; - -import org.jclouds.ContextBuilder; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.blobstore.TransientApiMetadata; -import org.jclouds.blobstore.domain.Blob; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.testng.annotations.Test; - -import com.google.common.collect.ImmutableMap; - -/** - * Tests behavior of {@code AddTweetsController} - * - * @author Adrian Cole - */ -@Test(groups = "unit") -public class ClearTweetsControllerTest { - - Map createBlobStores(String container) throws InterruptedException, ExecutionException { - TransientApiMetadata transientApiMetadata = TransientApiMetadata.builder().build(); - Map contexts = ImmutableMap.of( - "test1", ContextBuilder.newBuilder(transientApiMetadata).build(BlobStoreContext.class), - "test2", ContextBuilder.newBuilder(transientApiMetadata).build(BlobStoreContext.class)); - for (BlobStoreContext blobstore : contexts.values()) { - blobstore.getBlobStore().createContainerInLocation(null, container); - Blob blob = blobstore.getAsyncBlobStore().blobBuilder("1").build(); - blob.getMetadata().getUserMetadata().put(TweetStoreConstants.SENDER_NAME, "frank"); - blob.setPayload("I love beans!"); - blobstore.getBlobStore().putBlob(container, blob); - } - return contexts; - } - - public void testClearTweets() throws IOException, InterruptedException, ExecutionException { - String container = ClearTweetsControllerTest.class.getName() + "#container"; - Map contexts = createBlobStores(container); - - ClearTweetsController controller = new ClearTweetsController(contexts, - container); - controller.clearContainer("test1"); - controller.clearContainer("test2"); - - for (BlobStoreContext context : contexts.values()) { - assertEquals(context.getBlobStore().countBlobs(container), 0, context.toString()); - } - } -} diff --git a/demos/tweetstore/runatcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/EnqueueStoresControllerTest.java b/demos/tweetstore/runatcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/EnqueueStoresControllerTest.java deleted file mode 100644 index 3c5e5b1d80..0000000000 --- a/demos/tweetstore/runatcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/EnqueueStoresControllerTest.java +++ /dev/null @@ -1,85 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.controller; - -import static org.easymock.EasyMock.*; - -import java.net.URI; -import java.util.Map; - -import org.jclouds.ContextBuilder; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.blobstore.TransientApiMetadata; -import org.jclouds.demo.paas.RunnableHttpRequest; -import org.jclouds.demo.paas.RunnableHttpRequest.Factory; -import org.jclouds.demo.paas.service.taskqueue.TaskQueue; -import org.jclouds.http.HttpRequest; -import org.testng.annotations.Test; - -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableMultimap; - -/** - * Tests behavior of {@code EnqueueStoresController} - * - * @author Andrew Phillips - */ -@Test(groups = "unit") -public class EnqueueStoresControllerTest { - - Map createBlobStores() { - TransientApiMetadata transientApiMetadata = TransientApiMetadata.builder().build(); - Map contexts = ImmutableMap.of( - "test1", ContextBuilder.newBuilder(transientApiMetadata).build(BlobStoreContext.class), - "test2", ContextBuilder.newBuilder(transientApiMetadata).build(BlobStoreContext.class)); - return contexts; - } - - public void testEnqueueStores() { - Map stores = createBlobStores(); - TaskQueue taskQueue = createMock(TaskQueue.class); - Factory httpRequestFactory = createMock(Factory.class); - EnqueueStoresController function = new EnqueueStoresController(stores, - taskQueue, "http://localhost:8080"); - - expect(taskQueue.getHttpRequestFactory()).andStubReturn(httpRequestFactory); - - HttpRequest storeInTest1Request = HttpRequest.builder().endpoint( - URI.create("http://localhost:8080/store/do")) - .headers(ImmutableMultimap.of("context", "test1")).method("GET").build(); - RunnableHttpRequest storeInTest1Task = null; - expect(httpRequestFactory.create(eq(storeInTest1Request))).andReturn(storeInTest1Task); - - HttpRequest storeInTest2Request = HttpRequest.builder().endpoint( - URI.create("http://localhost:8080/store/do")) - .headers(ImmutableMultimap.of("context", "test2")).method("GET").build(); - RunnableHttpRequest storeInTest2Task = null; - expect(httpRequestFactory.create(eq(storeInTest2Request))).andReturn(storeInTest2Task); - - taskQueue.add(storeInTest1Task); - expectLastCall(); - taskQueue.add(storeInTest2Task); - expectLastCall(); - replay(httpRequestFactory, taskQueue); - - function.enqueueStoreTweetTasks(); - - verify(taskQueue); - } -} \ No newline at end of file diff --git a/demos/tweetstore/runatcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/StoreTweetsControllerTest.java b/demos/tweetstore/runatcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/StoreTweetsControllerTest.java deleted file mode 100644 index 2eb77041d3..0000000000 --- a/demos/tweetstore/runatcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/controller/StoreTweetsControllerTest.java +++ /dev/null @@ -1,120 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.controller; - -import static org.easymock.EasyMock.createMock; -import static org.easymock.EasyMock.expect; -import static org.easymock.EasyMock.replay; -import static org.easymock.EasyMock.verify; -import static org.testng.Assert.assertEquals; - -import java.io.IOException; -import java.util.Map; -import java.util.Map.Entry; -import java.util.concurrent.ExecutionException; - -import org.jclouds.ContextBuilder; -import org.jclouds.blobstore.BlobMap; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.blobstore.TransientApiMetadata; -import org.jclouds.blobstore.domain.Blob; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.jclouds.util.Strings2; -import org.testng.annotations.Test; - -import twitter4j.Status; -import twitter4j.Twitter; -import twitter4j.User; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; - -/** - * Tests behavior of {@code StoreTweetsController} - * - * @author Adrian Cole - */ -@Test(groups = "unit") -public class StoreTweetsControllerTest { - - Twitter createTwitter() { - return createMock(Twitter.class); - } - - Map createBlobStores() throws InterruptedException, ExecutionException { - TransientApiMetadata transientApiMetadata = TransientApiMetadata.builder().build(); - Map contexts = ImmutableMap.of( - "test1", ContextBuilder.newBuilder(transientApiMetadata).build(BlobStoreContext.class), - "test2", ContextBuilder.newBuilder(transientApiMetadata).build(BlobStoreContext.class)); - for (BlobStoreContext blobstore : contexts.values()) { - blobstore.getAsyncBlobStore().createContainerInLocation(null, "favo").get(); - } - return contexts; - } - - public void testStoreTweets() throws IOException, InterruptedException, ExecutionException { - Map stores = createBlobStores(); - StoreTweetsController function = new StoreTweetsController(stores, "favo", createTwitter()); - - User frank = createMock(User.class); - expect(frank.getScreenName()).andReturn("frank").atLeastOnce(); - - Status frankStatus = createMock(Status.class); - expect(frankStatus.getId()).andReturn(1l).atLeastOnce(); - expect(frankStatus.getUser()).andReturn(frank).atLeastOnce(); - expect(frankStatus.getText()).andReturn("I love beans!").atLeastOnce(); - - User jimmy = createMock(User.class); - expect(jimmy.getScreenName()).andReturn("jimmy").atLeastOnce(); - - Status jimmyStatus = createMock(Status.class); - expect(jimmyStatus.getId()).andReturn(2l).atLeastOnce(); - expect(jimmyStatus.getUser()).andReturn(jimmy).atLeastOnce(); - expect(jimmyStatus.getText()).andReturn("cloud is king").atLeastOnce(); - - replay(frank); - replay(frankStatus); - replay(jimmy); - replay(jimmyStatus); - - function.addMyTweets("test1", ImmutableList.of(frankStatus, jimmyStatus)); - function.addMyTweets("test2", ImmutableList.of(frankStatus, jimmyStatus)); - - verify(frank); - verify(frankStatus); - verify(jimmy); - verify(jimmyStatus); - - for (Entry entry : stores.entrySet()) { - BlobMap map = entry.getValue().createBlobMap("favo"); - Blob frankBlob = map.get("1"); - assertEquals(frankBlob.getMetadata().getName(), "1"); - assertEquals(frankBlob.getMetadata().getUserMetadata().get(TweetStoreConstants.SENDER_NAME), "frank"); - assertEquals(frankBlob.getMetadata().getContentMetadata().getContentType(), "text/plain"); - assertEquals(Strings2.toString(frankBlob.getPayload()), "I love beans!"); - - Blob jimmyBlob = map.get("2"); - assertEquals(jimmyBlob.getMetadata().getName(), "2"); - assertEquals(jimmyBlob.getMetadata().getUserMetadata().get(TweetStoreConstants.SENDER_NAME), "jimmy"); - assertEquals(jimmyBlob.getMetadata().getContentMetadata().getContentType(), "text/plain"); - assertEquals(Strings2.toString(jimmyBlob.getPayload()), "cloud is king"); - } - - } -} diff --git a/demos/tweetstore/runatcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/functions/KeyToStoredTweetStatusTest.java b/demos/tweetstore/runatcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/functions/KeyToStoredTweetStatusTest.java deleted file mode 100644 index aab06ec0b6..0000000000 --- a/demos/tweetstore/runatcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/functions/KeyToStoredTweetStatusTest.java +++ /dev/null @@ -1,69 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.functions; - -import static org.testng.Assert.assertEquals; - -import java.io.IOException; -import java.util.concurrent.ExecutionException; - -import org.jclouds.ContextBuilder; -import org.jclouds.blobstore.BlobMap; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.blobstore.TransientApiMetadata; -import org.jclouds.blobstore.domain.Blob; -import org.jclouds.demo.tweetstore.domain.StoredTweetStatus; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.testng.annotations.Test; - -/** - * Tests behavior of {@code KeyToStoredTweetStatus} - * - * @author Adrian Cole - */ -@Test(groups = "unit") -public class KeyToStoredTweetStatusTest { - - BlobMap createMap() throws InterruptedException, ExecutionException { - BlobStoreContext context = - ContextBuilder.newBuilder(TransientApiMetadata.builder().build()).build(BlobStoreContext.class); - context.getBlobStore().createContainerInLocation(null, "test1"); - return context.createBlobMap("test1"); - } - - public void testStoreTweets() throws IOException, InterruptedException, ExecutionException { - BlobMap map = createMap(); - Blob blob = map.blobBuilder().name("1").build(); - blob.getMetadata().getUserMetadata().put(TweetStoreConstants.SENDER_NAME, "frank"); - blob.setPayload("I love beans!"); - map.put("1", blob); - String host = "localhost"; - String service = "stub"; - String container = "tweetstore"; - - KeyToStoredTweetStatus function = new KeyToStoredTweetStatus(map, service, host, container); - StoredTweetStatus result = function.apply("1"); - - StoredTweetStatus expected = new StoredTweetStatus(service, host, container, "1", "frank", - "I love beans!", null); - - assertEquals(result, expected); - - } -} diff --git a/demos/tweetstore/runatcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/functions/ServiceToStoredTweetStatusesTest.java b/demos/tweetstore/runatcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/functions/ServiceToStoredTweetStatusesTest.java deleted file mode 100644 index 5fec52711e..0000000000 --- a/demos/tweetstore/runatcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/functions/ServiceToStoredTweetStatusesTest.java +++ /dev/null @@ -1,75 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.functions; - -import static org.testng.Assert.assertEquals; - -import java.io.IOException; -import java.util.Map; -import java.util.concurrent.ExecutionException; - -import org.jclouds.ContextBuilder; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.blobstore.TransientApiMetadata; -import org.jclouds.blobstore.domain.Blob; -import org.jclouds.demo.tweetstore.domain.StoredTweetStatus; -import org.jclouds.demo.tweetstore.reference.TweetStoreConstants; -import org.testng.annotations.Test; -import org.testng.collections.Maps; - -import com.google.common.collect.Iterables; - -/** - * Tests behavior of {@code ServiceToStoredTweetStatuses} - * - * @author Adrian Cole - */ -@Test(groups = "unit") -public class ServiceToStoredTweetStatusesTest { - - Map createServices(String container) throws InterruptedException, - ExecutionException { - Map services = Maps.newHashMap(); - TransientApiMetadata transientApiMetadata = TransientApiMetadata.builder().build(); - for (String name : new String[] { "1", "2" }) { - BlobStoreContext context = ContextBuilder.newBuilder(transientApiMetadata).build(BlobStoreContext.class); - context.getAsyncBlobStore().createContainerInLocation(null, container).get(); - Blob blob = context.getAsyncBlobStore().blobBuilder("1").build(); - blob.getMetadata().getUserMetadata().put(TweetStoreConstants.SENDER_NAME, "frank"); - blob.setPayload("I love beans!"); - context.getAsyncBlobStore().putBlob(container, blob).get(); - services.put(name, context); - } - return services; - } - - public void testStoreTweets() throws IOException, InterruptedException, ExecutionException { - String container = "container"; - Map contexts = createServices(container); - - ServiceToStoredTweetStatuses function = new ServiceToStoredTweetStatuses(contexts, container); - - assertEquals(Iterables.getLast(function.apply("1")), new StoredTweetStatus("1", "localhost", - container, "1", "frank", "I love beans!", null)); - - assertEquals(Iterables.getLast(function.apply("2")), new StoredTweetStatus("2", "localhost", - container, "1", "frank", "I love beans!", null)); - - } -} diff --git a/demos/tweetstore/runatcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/integration/RunAtCloudServer.java b/demos/tweetstore/runatcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/integration/RunAtCloudServer.java deleted file mode 100644 index 2ce1ec21aa..0000000000 --- a/demos/tweetstore/runatcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/integration/RunAtCloudServer.java +++ /dev/null @@ -1,68 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.integration; - -import static com.google.common.io.Closeables.closeQuietly; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Properties; -import java.util.concurrent.TimeUnit; - -import javax.servlet.ServletException; - -import org.apache.commons.cli.ParseException; - -/** - * Basic functionality to start a local RUN@cloud instance. - * - * @author Andrew Phillips - */ -public class RunAtCloudServer { - protected StaxSdkAppServer2 server; - - public void writePropertiesAndStartServer(final String port, final String warfile, - final String environments, final String serverBaseDirectory, - Properties props) throws IOException, InterruptedException, ParseException, ServletException { - String filename = String.format( - "%1$s/WEB-INF/jclouds.properties", warfile); - System.err.println("file: " + filename); - storeProperties(filename, props); - assert new File(filename).exists(); - server = StaxSdkAppServer2.createServer(new String[] { "-web", warfile, "-port", port, "-env", environments, - "-dir", serverBaseDirectory }, new String[0], Thread.currentThread().getContextClassLoader()); - server.start(); - TimeUnit.SECONDS.sleep(30); - } - - private static void storeProperties(String filename, Properties props) throws IOException { - FileOutputStream targetFile = new FileOutputStream(filename); - try { - props.store(targetFile, "test"); - } finally { - closeQuietly(targetFile); - } - } - - public void stop() throws Exception { - server.stop(); - } - -} \ No newline at end of file diff --git a/demos/tweetstore/runatcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/integration/StaxSdkAppServer2.java b/demos/tweetstore/runatcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/integration/StaxSdkAppServer2.java deleted file mode 100644 index 4dbece1747..0000000000 --- a/demos/tweetstore/runatcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/integration/StaxSdkAppServer2.java +++ /dev/null @@ -1,192 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.integration; - -import static com.google.common.base.Predicates.instanceOf; -import static java.util.Arrays.asList; -import static org.jclouds.demo.tweetstore.integration.util.ObjectFields.set; -import static org.jclouds.demo.tweetstore.integration.util.ObjectFields.valueOf; - -import java.io.File; -import java.io.IOException; -import java.util.Timer; - -import javax.servlet.ServletException; - -import net.stax.appserver.webapp.RequestMonitorValve; -import net.stax.appserver.webapp.WebAppEngine; - -import org.apache.catalina.Engine; -import org.apache.commons.cli.ParseException; - -import com.google.common.base.Predicate; -import com.google.common.collect.Iterables; -import com.staxnet.appserver.IAppServerConfiguration; -import com.staxnet.appserver.IEngineFactory; -import com.staxnet.appserver.ServerCallbackClient; -import com.staxnet.appserver.StaxAppServerBase; -import com.staxnet.appserver.StaxSdkAppServer; -import com.staxnet.appserver.StaxSdkAppServerCLI; -import com.staxnet.appserver.TomcatServerBase; -import com.staxnet.appserver.WarBasedServerConfiguration; -import com.staxnet.appserver.config.AppServerConfig; - -class StaxSdkAppServer2 { - // code more or less exactly from StaxSdkAppServer.java - public static StaxSdkAppServer2 createServer(String[] args, String[] classPaths, - ClassLoader cl) throws ParseException, ServletException { - StaxSdkAppServerCLI cli = StaxSdkAppServerCLI.parse(args); - if (cli.getMissingOptions().length > 0) { - throw new ParseException("Missing required options: " + cli.formatMissingOptions(", ")); - } - - String[] environments = cli.getEnvironment(); - File serverConfig = cli.getServerConfigFile(); - File baseDir = new File(cli.getBaseDir()); - File webRoot = new File(cli.getWebdir()); - File workDir = new File(baseDir, "work"); - - File staxWebXml = new File(webRoot, "WEB-INF/cloudbees-web.xml"); - if (!(staxWebXml.exists())) - staxWebXml = new File(webRoot, "WEB-INF/stax-web.xml"); - IAppServerConfiguration config = WarBasedServerConfiguration.load( - serverConfig, webRoot, staxWebXml, environments); - // force the RequestMonitorValve to sleep for only a short period - set("statusInterval", StaxReflect.getAppServerConfig(config), 5); - StaxSdkAppServer server = new StaxSdkAppServer( - baseDir.getAbsolutePath(), workDir.getAbsolutePath(), cl, - classPaths, cli.getPort(), config, cli.getRepositoryPath()); - return new StaxSdkAppServer2(server); - } - - private final StaxSdkAppServer server; - private final Thread serverThread; - - private StaxSdkAppServer2(StaxSdkAppServer server) { - this.server = server; - serverThread = new Thread(new Runnable() { - public void run() { - try { - StaxSdkAppServer2.this.server.start(); - } catch (ServletException exception) { - System.err.println("exception starting server: " + exception); - } - } - }); - } - - void start() throws ServletException { - Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { - public void run() { - stop(); - } - })); - serverThread.start(); - } - - void stop() { - server.stop(); - serverThread.interrupt(); - StaxReflect.getStaxAppQueryTimer(server).cancel(); - KillerCallback requestMonitorAssassin = new KillerCallback(StaxReflect.getRequestMonitorTimerCallback(server)); - /* - * Hoping for the best here in terms of visibility - we're setting a variable in a - * different thread which isn't guaranteed to see the change. - * But we can't set the callbackClient before serverThread starts (which would create - * a happens-before relationship) because the objects on which the callbackClient is - * set have not been created yet at that point. - */ - set("callbackClient", StaxReflect.getRequestMonitorTimer(server), requestMonitorAssassin); - requestMonitorAssassin.setToKill(); - } - - private class KillerCallback extends ServerCallbackClient { - private final ServerCallbackClient delegate; - private volatile boolean killCaller = false; - - private KillerCallback(ServerCallbackClient delegate) { - super("", ""); - this.delegate = delegate; - } - - @Override - public AuthenticationResult getApplicationTicket(String username, - String password) throws IOException { - return delegate.getApplicationTicket(username, password); - } - - @Override - public AuthenticationResult renewApplicationTicket(String userAuthTicket) - throws IOException { - return delegate.renewApplicationTicket(userAuthTicket); - } - - @Override - public void updateStatus(State state) throws ServletException, - IOException { - if (killCaller) { - throw new ThreadDeath(); - } - delegate.updateStatus(state); - } - - private void setToKill() { - killCaller = true; - } - } - - private static class StaxReflect { - private static WebAppEngine getWebAppEngine(StaxSdkAppServer server) { - return (WebAppEngine) Iterables.find(asList((IEngineFactory[]) - valueOf("engineFactories", server, StaxAppServerBase.class)), - instanceOf(WebAppEngine.class)); - } - - private static Timer getStaxAppQueryTimer(StaxSdkAppServer server) { - return (Timer) valueOf("timer", getWebAppEngine(server)); - } - - private static AppServerConfig getAppServerConfig(IAppServerConfiguration config) { - return (AppServerConfig) valueOf("appServerConfig", config); - } - - private static Engine getLocalEngine(StaxSdkAppServer server) { - return (Engine) Iterables.find(asList((Engine[]) - valueOf("engines", valueOf("container", server, TomcatServerBase.class))), - new Predicate() { - @Override - public boolean apply(Engine input) { - return input.getName().equals("localEngine"); - } - }); - } - - private static Runnable getRequestMonitorTimer(StaxSdkAppServer server) { - return (Runnable) valueOf("idleTimer", Iterables.find( - asList(getLocalEngine(server).getPipeline().getValves()), - instanceOf(RequestMonitorValve.class))); - } - - private static ServerCallbackClient getRequestMonitorTimerCallback( - StaxSdkAppServer server) { - return (ServerCallbackClient) valueOf("callbackClient", - getRequestMonitorTimer(server)); - } - } -} diff --git a/demos/tweetstore/runatcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/integration/TweetStoreLiveTest.java b/demos/tweetstore/runatcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/integration/TweetStoreLiveTest.java deleted file mode 100644 index 207ec2b6e6..0000000000 --- a/demos/tweetstore/runatcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/integration/TweetStoreLiveTest.java +++ /dev/null @@ -1,239 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.integration; - -import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.demo.paas.RunnableHttpRequest.PLATFORM_REQUEST_ORIGINATOR_HEADER; -import static org.jclouds.demo.tweetstore.reference.TweetStoreConstants.PROPERTY_TWEETSTORE_BLOBSTORES; -import static org.jclouds.demo.tweetstore.reference.TweetStoreConstants.PROPERTY_TWEETSTORE_CONTAINER; -import static org.jclouds.demo.tweetstore.reference.TwitterConstants.PROPERTY_TWITTER_ACCESSTOKEN; -import static org.jclouds.demo.tweetstore.reference.TwitterConstants.PROPERTY_TWITTER_ACCESSTOKEN_SECRET; -import static org.jclouds.demo.tweetstore.reference.TwitterConstants.PROPERTY_TWITTER_CONSUMER_KEY; -import static org.jclouds.demo.tweetstore.reference.TwitterConstants.PROPERTY_TWITTER_CONSUMER_SECRET; - -import java.io.IOException; -import java.io.InputStream; -import java.net.HttpURLConnection; -import java.net.URL; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Properties; -import java.util.Set; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeoutException; - -import org.jclouds.Context; -import org.jclouds.ContextBuilder; -import org.jclouds.blobstore.BlobStoreContext; -import org.jclouds.demo.tweetstore.controller.StoreTweetsController; -import org.jclouds.logging.log4j.config.Log4JLoggingModule; -import org.jclouds.rest.AuthorizationException; -import org.jclouds.util.Strings2; -import org.testng.annotations.AfterTest; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.Parameters; -import org.testng.annotations.Test; - -import twitter4j.ResponseList; -import twitter4j.Status; -import twitter4j.Twitter; -import twitter4j.TwitterException; -import twitter4j.TwitterFactory; -import twitter4j.conf.Configuration; -import twitter4j.conf.ConfigurationBuilder; - -import com.google.common.base.Splitter; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Maps; -import com.google.inject.Module; - -/** - * Starts up the RUN@cloud for Java Development environment and deploys an application which - * tests accesses twitter and blobstores. - * - * @author Andrew Phillips - */ -@Test(groups = "live", singleThreaded = true) -public class TweetStoreLiveTest { - - RunAtCloudServer server; - private URL url; - private Map contexts; - private String container; - private static final Iterable blobstores = - Splitter.on(',').split(getRequiredSystemProperty(PROPERTY_TWEETSTORE_BLOBSTORES)); - private static final Properties props = new Properties(); - - @BeforeTest - void clearAndCreateContainers() throws InterruptedException, ExecutionException, TimeoutException, IOException, - TwitterException { - container = getRequiredSystemProperty(PROPERTY_TWEETSTORE_CONTAINER); - - props.setProperty(PROPERTY_TWEETSTORE_CONTAINER, container); - - // put all identity/credential pairs into the client - addCredentialsForBlobStores(props); - - // example of an ad-hoc client configuration - addConfigurationForTwitter(props); - - // for testing, capture logs. - final Set wiring = ImmutableSet. of(new Log4JLoggingModule()); - this.contexts = Maps.newConcurrentMap(); - - for (String provider : blobstores) { - contexts.put(provider, ContextBuilder.newBuilder(provider) - .modules(wiring).overrides(props).build(BlobStoreContext.class)); - } - - Configuration conf = new ConfigurationBuilder() - .setOAuthConsumerKey(props.getProperty(PROPERTY_TWITTER_CONSUMER_KEY)) - .setOAuthConsumerSecret(props.getProperty(PROPERTY_TWITTER_CONSUMER_SECRET)) - .setOAuthAccessToken(props.getProperty(PROPERTY_TWITTER_ACCESSTOKEN)) - .setOAuthAccessTokenSecret(props.getProperty(PROPERTY_TWITTER_ACCESSTOKEN_SECRET)) - .build(); - Twitter client = new TwitterFactory(conf).getInstance(); - StoreTweetsController controller = new StoreTweetsController(contexts, container, client); - - ResponseList statuses = client.getMentions(); - - boolean deleted = false; - for (BlobStoreContext context : contexts.values()) { - try { - if (context.getBlobStore().containerExists(container)) { - System.err.printf("deleting container %s at %s%n", container, - context.unwrap(Context.class).getProviderMetadata().getEndpoint()); - context.getBlobStore().deleteContainer(container); - deleted = true; - } - } catch (AuthorizationException e) { - throw new AuthorizationException("for context: " + context, e); - } - } - if (deleted) { - System.err.println("sleeping 60 seconds to allow containers to clear"); - Thread.sleep(60000); - } - for (BlobStoreContext context : contexts.values()) { - System.err.printf("creating container %s at %s%n", container, - context.unwrap(Context.class).getProviderMetadata().getEndpoint()); - context.getBlobStore().createContainerInLocation(null, container); - } - - if (deleted) { - System.err.println("sleeping 5 seconds to allow containers to create"); - Thread.sleep(5000); - } - - for (Entry entry : contexts.entrySet()) { - System.err.printf("filling container %s at %s%n", container, entry.getKey()); - controller.addMyTweets(entry.getKey(), statuses); - } - } - - private static String getRequiredSystemProperty(String key) { - return checkNotNull(System.getProperty(key), key); - } - - private void addConfigurationForTwitter(Properties props) { - props.setProperty(PROPERTY_TWITTER_CONSUMER_KEY, - getRequiredSystemProperty("test." + PROPERTY_TWITTER_CONSUMER_KEY)); - props.setProperty(PROPERTY_TWITTER_CONSUMER_SECRET, - getRequiredSystemProperty("test." + PROPERTY_TWITTER_CONSUMER_SECRET)); - props.setProperty(PROPERTY_TWITTER_ACCESSTOKEN, - getRequiredSystemProperty("test." + PROPERTY_TWITTER_ACCESSTOKEN)); - props.setProperty(PROPERTY_TWITTER_ACCESSTOKEN_SECRET, - getRequiredSystemProperty("test." + PROPERTY_TWITTER_ACCESSTOKEN_SECRET)); - } - - private void addCredentialsForBlobStores(Properties props) { - for (String provider : blobstores) { - props.setProperty(provider + ".identity", - getRequiredSystemProperty("test." + provider + ".identity")); - props.setProperty(provider + ".credential", - getRequiredSystemProperty("test." + provider + ".credential")); - } - } - - @BeforeTest(dependsOnMethods = "clearAndCreateContainers") - @Parameters({ "warfile", "bees.address", "bees.port", "bees.basedir" }) - public void startDevAppServer(final String warfile, final String address, final String port, - String serverBaseDirectory) throws Exception { - url = new URL(String.format("http://%s:%s", address, port)); - - server = new RunAtCloudServer(); - server.writePropertiesAndStartServer(port, warfile, "itest", - serverBaseDirectory, props); - } - - @Test - public void shouldPass() throws InterruptedException, IOException { - InputStream i = url.openStream(); - String string = Strings2.toStringAndClose(i); - assert string.indexOf("Welcome") >= 0 : string; - } - - @Test(dependsOnMethods = "shouldPass", expectedExceptions = IOException.class) - public void shouldFail() throws InterruptedException, IOException { - new URL(url, "/store/do").openStream(); - } - - @Test(dependsOnMethods = "shouldFail") - public void testPrimeContainers() throws IOException, InterruptedException { - URL gurl = new URL(url, "/store/do"); - - for (String context : blobstores) { - System.out.println("storing at context: " + context); - HttpURLConnection connection = (HttpURLConnection) gurl.openConnection(); - connection.addRequestProperty(PLATFORM_REQUEST_ORIGINATOR_HEADER, "taskqueue-twitter"); - connection.addRequestProperty("context", context); - InputStream i = connection.getInputStream(); - String string = Strings2.toStringAndClose(i); - assert string.indexOf("Done!") >= 0 : string; - connection.disconnect(); - } - - System.err.println("sleeping 20 seconds to allow for eventual consistency delay"); - Thread.sleep(20000); - for (BlobStoreContext context : contexts.values()) { - assert context.createInputStreamMap(container).size() > 0 : context.unwrap(Context.class).getProviderMetadata().getEndpoint(); - } - } - - @Test(invocationCount = 5, dependsOnMethods = "testPrimeContainers") - public void testSerial() throws InterruptedException, IOException { - URL gurl = new URL(url, "/tweets/get"); - InputStream i = gurl.openStream(); - String string = Strings2.toStringAndClose(i); - assert string.indexOf("Tweets in Clouds") >= 0 : string; - } - - @Test(invocationCount = 10, dependsOnMethods = "testPrimeContainers", threadPoolSize = 3) - public void testParallel() throws InterruptedException, IOException { - URL gurl = new URL(url, "/tweets/get"); - InputStream i = gurl.openStream(); - String string = Strings2.toStringAndClose(i); - assert string.indexOf("Tweets in Clouds") >= 0 : string; - } - - @AfterTest - public void stopDevAppServer() throws Exception { - server.stop(); - } -} diff --git a/demos/tweetstore/runatcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/integration/util/ObjectFields.java b/demos/tweetstore/runatcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/integration/util/ObjectFields.java deleted file mode 100644 index cc7c696c55..0000000000 --- a/demos/tweetstore/runatcloud-tweetstore/src/test/java/org/jclouds/demo/tweetstore/integration/util/ObjectFields.java +++ /dev/null @@ -1,56 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.demo.tweetstore.integration.util; - -import java.lang.reflect.Field; - -public class ObjectFields { - - public static Object valueOf(String fieldName, Object source) { - return valueOf(fieldName, source, source.getClass()); - } - - public static Object valueOf(String fieldName, Object source, - Class fieldDeclaringClass) { - try { - return getAccessibleField(fieldName, fieldDeclaringClass).get(source); - } catch (Exception exception) { - throw new IllegalArgumentException(exception); - } - } - - private static Field getAccessibleField(String name, Class declaringClass) throws SecurityException, NoSuchFieldException { - Field field = declaringClass.getDeclaredField(name); - field.setAccessible(true); - return field; - } - - public static void set(String fieldName, Object target, Object value) { - set(fieldName, target, value, target.getClass()); - } - - public static void set(String fieldName, Object target, Object value, - Class fieldDeclaringClass) { - try { - getAccessibleField(fieldName, fieldDeclaringClass).set(target, value); - } catch (Exception exception) { - throw new IllegalArgumentException(exception); - } - } -} diff --git a/demos/tweetstore/runatcloud-tweetstore/src/test/resources/log4j.xml b/demos/tweetstore/runatcloud-tweetstore/src/test/resources/log4j.xml deleted file mode 100644 index 2e5d01fb9e..0000000000 --- a/demos/tweetstore/runatcloud-tweetstore/src/test/resources/log4j.xml +++ /dev/null @@ -1,95 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/drivers/apachehc/pom.xml b/drivers/apachehc/pom.xml index 9806b486cb..66bb486eb2 100644 --- a/drivers/apachehc/pom.xml +++ b/drivers/apachehc/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.driver diff --git a/drivers/bouncycastle/pom.xml b/drivers/bouncycastle/pom.xml index e2abd25e5b..4b916ba328 100644 --- a/drivers/bouncycastle/pom.xml +++ b/drivers/bouncycastle/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.driver diff --git a/drivers/enterprise/pom.xml b/drivers/enterprise/pom.xml index 9915f43dba..b89c5e3ceb 100644 --- a/drivers/enterprise/pom.xml +++ b/drivers/enterprise/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.driver diff --git a/drivers/gae/pom.xml b/drivers/gae/pom.xml index 7d3eabc0b4..0de4ea0cd4 100644 --- a/drivers/gae/pom.xml +++ b/drivers/gae/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.driver diff --git a/drivers/joda/pom.xml b/drivers/joda/pom.xml index 68e5fe517e..20e1ccb344 100644 --- a/drivers/joda/pom.xml +++ b/drivers/joda/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.driver diff --git a/drivers/jsch/pom.xml b/drivers/jsch/pom.xml index 10dea262a6..b095d88722 100644 --- a/drivers/jsch/pom.xml +++ b/drivers/jsch/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.driver diff --git a/drivers/jsch/src/test/java/org/jclouds/ssh/jsch/JschSshClientLiveTest.java b/drivers/jsch/src/test/java/org/jclouds/ssh/jsch/JschSshClientLiveTest.java index 033c01bfed..0466d0e253 100644 --- a/drivers/jsch/src/test/java/org/jclouds/ssh/jsch/JschSshClientLiveTest.java +++ b/drivers/jsch/src/test/java/org/jclouds/ssh/jsch/JschSshClientLiveTest.java @@ -26,7 +26,6 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.File; -import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintStream; @@ -49,9 +48,11 @@ import org.jclouds.util.Strings2; import org.testng.annotations.BeforeGroups; import org.testng.annotations.Test; +import com.google.common.base.Charsets; import com.google.common.base.Strings; import com.google.common.base.Suppliers; import com.google.common.io.Closeables; +import com.google.common.io.Files; import com.google.common.net.HostAndPort; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; @@ -148,7 +149,7 @@ public class JschSshClientLiveTest { SshClient connection; if (Strings.emptyToNull(sshKeyFile) != null) { connection = factory.create(HostAndPort.fromParts(sshHost, port), LoginCredentials.builder().user(sshUser) - .privateKey(Strings2.toStringAndClose(new FileInputStream(sshKeyFile))).build()); + .privateKey(Files.toString(new File(sshKeyFile), Charsets.UTF_8)).build()); } else { connection = factory.create(HostAndPort.fromParts(sshHost, port), LoginCredentials.builder().user(sshUser).password(sshPass).build()); diff --git a/drivers/log4j/pom.xml b/drivers/log4j/pom.xml index 748c5047c3..87969c4587 100644 --- a/drivers/log4j/pom.xml +++ b/drivers/log4j/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.driver diff --git a/drivers/netty/pom.xml b/drivers/netty/pom.xml index f79f463196..e44101baf8 100644 --- a/drivers/netty/pom.xml +++ b/drivers/netty/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.driver diff --git a/drivers/pom.xml b/drivers/pom.xml index 3589a8710b..bc476ec72c 100644 --- a/drivers/pom.xml +++ b/drivers/pom.xml @@ -24,7 +24,7 @@ jclouds-project org.jclouds - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../project/pom.xml jclouds-drivers-project diff --git a/drivers/slf4j/pom.xml b/drivers/slf4j/pom.xml index 905683c817..f8acc2577a 100644 --- a/drivers/slf4j/pom.xml +++ b/drivers/slf4j/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.driver diff --git a/drivers/sshj/pom.xml b/drivers/sshj/pom.xml index f8587209f7..ef9aa78a12 100644 --- a/drivers/sshj/pom.xml +++ b/drivers/sshj/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.driver diff --git a/drivers/sshj/src/main/java/org/jclouds/sshj/SshjSshClient.java b/drivers/sshj/src/main/java/org/jclouds/sshj/SshjSshClient.java index ed78a53091..437c14398d 100644 --- a/drivers/sshj/src/main/java/org/jclouds/sshj/SshjSshClient.java +++ b/drivers/sshj/src/main/java/org/jclouds/sshj/SshjSshClient.java @@ -35,7 +35,6 @@ import java.io.IOException; import java.io.InputStream; import java.net.ConnectException; import java.net.SocketTimeoutException; -import java.util.Collections; import java.util.concurrent.TimeUnit; import javax.annotation.PreDestroy; @@ -74,6 +73,7 @@ import com.google.common.base.Predicates; import com.google.common.base.Splitter; import com.google.common.base.Supplier; import com.google.common.base.Throwables; +import com.google.common.collect.ImmutableMap; import com.google.common.io.Closeables; import com.google.common.net.HostAndPort; import com.google.inject.Inject; @@ -412,7 +412,7 @@ public class SshjSshClient implements SshClient { public Session create() throws Exception { checkConnected(); session = sshClientConnection.ssh.startSession(); - session.allocatePTY("vt100", 80, 24, 0, 0, Collections. emptyMap()); + session.allocatePTY("vt100", 80, 24, 0, 0, ImmutableMap. of()); return session; } diff --git a/drivers/sshj/src/test/java/org/jclouds/sshj/SshjSshClientLiveTest.java b/drivers/sshj/src/test/java/org/jclouds/sshj/SshjSshClientLiveTest.java index 7f64209a2c..fa55a3fbe2 100644 --- a/drivers/sshj/src/test/java/org/jclouds/sshj/SshjSshClientLiveTest.java +++ b/drivers/sshj/src/test/java/org/jclouds/sshj/SshjSshClientLiveTest.java @@ -24,7 +24,6 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.File; -import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintStream; @@ -42,9 +41,11 @@ import org.jclouds.util.Strings2; import org.testng.annotations.BeforeGroups; import org.testng.annotations.Test; +import com.google.common.base.Charsets; import com.google.common.base.Strings; import com.google.common.base.Suppliers; import com.google.common.io.Closeables; +import com.google.common.io.Files; import com.google.common.net.HostAndPort; import com.google.inject.Guice; import com.google.inject.Injector; @@ -136,7 +137,7 @@ public class SshjSshClientLiveTest { SshClient connection; if (Strings.emptyToNull(sshKeyFile) != null) { connection = factory.create(HostAndPort.fromParts(sshHost, port), LoginCredentials.builder().user(sshUser) - .privateKey(Strings2.toStringAndClose(new FileInputStream(sshKeyFile))).build()); + .privateKey(Files.toString(new File(sshKeyFile), Charsets.UTF_8)).build()); } else { connection = factory.create(HostAndPort.fromParts(sshHost, port), LoginCredentials.builder().user(sshUser).password(sshPass).build()); diff --git a/labs/abiquo/README.md b/labs/abiquo/README.md new file mode 100644 index 0000000000..cdf6b8489d --- /dev/null +++ b/labs/abiquo/README.md @@ -0,0 +1,10 @@ +Jclouds Abiquo Provider +======================= + +This is the jclouds Abiquo provider. It enables compute features for the Abiquo cloud platform. + +Detailed information about the Abiquo REST API can be found in the +[Abiquo documentation page](http://community.abiquo.com). + +If you find any issue in the provider api, please submit it to the [Bug tracking system](http://jira.abiquo.com/browse/ABIQUOJC) and we will do our best to fix it. + diff --git a/labs/abiquo/pom.xml b/labs/abiquo/pom.xml new file mode 100644 index 0000000000..88bd3fa62d --- /dev/null +++ b/labs/abiquo/pom.xml @@ -0,0 +1,233 @@ + + + 4.0.0 + + org.jclouds + jclouds-project + 1.6.0-SNAPSHOT + ../../project/pom.xml + + + org.jclouds.labs + abiquo + jclouds Abiquo api + jclouds components to access an implementation of Abiquo + bundle + + + 2.1.1 + http://localhost/api + FIXME + FIXME + + + org.jclouds.abiquo*;version="${project.version}" + org.jclouds*;version="${project.version}",* + + + + + + abiquo-repo + Abiquo Maven Repository + http://repo.community.abiquo.com/repo + + + + + + org.jclouds + jclouds-core + ${project.version} + + + org.jclouds + jclouds-compute + ${project.version} + + + + com.abiquo + api-model-transport + ${abiquo.version} + + + javax.ws.rs + jsr311-api + + + org.uncommons + reportng + + + + + com.abiquo + am-model + ${abiquo.version} + + + javax.ws.rs + jsr311-api + + + org.uncommons + reportng + + + + + + org.apache.wink + wink-common + 1.1-incubating + + + org.slf4j + slf4j-jdk14 + + + javax.ws.rs + jsr311-api + + + javax.xml.stream + stax-api + + + + + + org.jclouds + jclouds-core + ${project.version} + test-jar + test + + + org.jclouds + jclouds-compute + ${project.version} + test-jar + test + + + org.jclouds.driver + jclouds-sshj + ${project.version} + test + + + org.jclouds.driver + jclouds-slf4j + ${project.version} + test + + + ch.qos.logback + logback-core + 1.0.0 + test + + + ch.qos.logback + logback-classic + 1.0.0 + test + + + + + + + src/test/resources + true + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*IntegrationTest.java + **/*LiveTest.java + **/*LiveApiTest.java + **/*LiveUcsTest.java + + + + + + + + + live + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration + integration-test + + test + + + + ${test.abiquo.idenfity} + ${test.abiquo.credential} + ${test.abiquo.api-version} + ${test.abiquo.build-version} + + + + + + + + + + api + + + src/test/resources/filters/filters.properties + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration + integration-test + + test + + + + 1 + + none + + + **/*LiveApiTest.java + + + ${test.abiquo.identity} + ${test.abiquo.credential} + ${test.abiquo.api-version} + ${test.abiquo.build-version} + + + + + + + + + + diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/AbiquoApi.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/AbiquoApi.java new file mode 100644 index 0000000000..0e5cb99fda --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/AbiquoApi.java @@ -0,0 +1,100 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo; + +import java.util.concurrent.TimeUnit; + +import org.jclouds.abiquo.features.AdminApi; +import org.jclouds.abiquo.features.CloudApi; +import org.jclouds.abiquo.features.ConfigApi; +import org.jclouds.abiquo.features.EnterpriseApi; +import org.jclouds.abiquo.features.EventApi; +import org.jclouds.abiquo.features.InfrastructureApi; +import org.jclouds.abiquo.features.PricingApi; +import org.jclouds.abiquo.features.TaskApi; +import org.jclouds.abiquo.features.VirtualMachineTemplateApi; +import org.jclouds.concurrent.Timeout; +import org.jclouds.rest.annotations.Delegate; + +/** + * Provides synchronous access to Abiquo. + * + * @see API: + * http://community.abiquo.com/display/ABI20/API+Reference + * @see AbiquoAsyncApi + * @author Ignasi Barrera + */ +@Timeout(duration = 30, timeUnit = TimeUnit.SECONDS) +public interface AbiquoApi { + /** + * Provides synchronous access to Admin features. + */ + @Delegate + AdminApi getAdminApi(); + + /** + * Provides synchronous access to Infrastructure features. + */ + @Delegate + InfrastructureApi getInfrastructureApi(); + + /** + * Provides synchronous access to Cloud features. + */ + @Delegate + CloudApi getCloudApi(); + + /** + * Provides synchronous access to Apps library features. + */ + @Delegate + VirtualMachineTemplateApi getVirtualMachineTemplateApi(); + + /** + * Provides synchronous access to Enterprise features. + */ + @Delegate + EnterpriseApi getEnterpriseApi(); + + /** + * Provides synchronous access to configuration features. + */ + @Delegate + ConfigApi getConfigApi(); + + /** + * Provides synchronous access to task asynchronous features. + */ + @Delegate + TaskApi getTaskApi(); + + /** + * Provides synchronous access to Event features. + */ + @Delegate + EventApi getEventApi(); + + /** + * Provides synchronous access to Pricing features. + */ + @Delegate + PricingApi getPricingApi(); + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/AbiquoApiMetadata.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/AbiquoApiMetadata.java new file mode 100644 index 0000000000..d3d5c78b61 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/AbiquoApiMetadata.java @@ -0,0 +1,112 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo; + +import static org.jclouds.Constants.PROPERTY_MAX_REDIRECTS; +import static org.jclouds.abiquo.config.AbiquoProperties.ASYNC_TASK_MONITOR_DELAY; +import static org.jclouds.abiquo.config.AbiquoProperties.CREDENTIAL_IS_TOKEN; + +import java.net.URI; +import java.util.Properties; + +import org.jclouds.abiquo.compute.config.AbiquoComputeServiceContextModule; +import org.jclouds.abiquo.config.AbiquoRestClientModule; +import org.jclouds.apis.ApiMetadata; +import org.jclouds.concurrent.config.ScheduledExecutorServiceModule; +import org.jclouds.rest.RestContext; +import org.jclouds.rest.internal.BaseRestApiMetadata; + +import com.google.common.base.CharMatcher; +import com.google.common.collect.ImmutableSet; +import com.google.common.reflect.TypeToken; +import com.google.inject.Module; + +/** + * Implementation of {@link ApiMetadata} for Abiquo API. + * + * @author Ignasi Barrera + */ +public class AbiquoApiMetadata extends BaseRestApiMetadata { + /** Serial UID. */ + private static final long serialVersionUID = -8355533493674898171L; + + /** The token describing the rest api context. */ + public static final TypeToken> CONTEXT_TOKEN = new TypeToken>() { + private static final long serialVersionUID = -5070937833892503232L; + }; + + public AbiquoApiMetadata() { + this(new Builder()); + } + + protected AbiquoApiMetadata(final Builder builder) { + super(builder); + } + + public static Properties defaultProperties() { + Properties properties = BaseRestApiMetadata.defaultProperties(); + // By default redirects will be handled in the domain objects + properties.setProperty(PROPERTY_MAX_REDIRECTS, "0"); + // The default polling delay between AsyncTask monitor requests + properties.setProperty(ASYNC_TASK_MONITOR_DELAY, "5000"); + // By default the provided credential is not a token + properties.setProperty(CREDENTIAL_IS_TOKEN, "false"); + return properties; + } + + @Override + public Builder toBuilder() { + return new Builder().fromApiMetadata(this); + } + + public static class Builder extends BaseRestApiMetadata.Builder { + private static final String DOCUMENTATION_ROOT = "http://community.abiquo.com/display/ABI" + + CharMatcher.DIGIT.retainFrom(AbiquoAsyncApi.API_VERSION); + + protected Builder() { + super(AbiquoApi.class, AbiquoAsyncApi.class); + id("abiquo") + .name("Abiquo API") + .identityName("API Username") + .credentialName("API Password") + .documentation(URI.create(DOCUMENTATION_ROOT + "/API+Reference")) + .defaultEndpoint("http://localhost/api") + .version(AbiquoAsyncApi.API_VERSION) + .buildVersion(AbiquoAsyncApi.BUILD_VERSION) + .view(TypeToken.of(AbiquoContext.class)) + .defaultProperties(AbiquoApiMetadata.defaultProperties()) + .defaultModules( + ImmutableSet.> of(AbiquoRestClientModule.class, + AbiquoComputeServiceContextModule.class, ScheduledExecutorServiceModule.class)); + } + + @Override + public AbiquoApiMetadata build() { + return new AbiquoApiMetadata(this); + } + + @Override + public Builder fromApiMetadata(final ApiMetadata in) { + super.fromApiMetadata(in); + return this; + } + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/AbiquoAsyncApi.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/AbiquoAsyncApi.java new file mode 100644 index 0000000000..166e3fdfd9 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/AbiquoAsyncApi.java @@ -0,0 +1,107 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo; + +import org.jclouds.abiquo.features.AdminAsyncApi; +import org.jclouds.abiquo.features.CloudAsyncApi; +import org.jclouds.abiquo.features.ConfigAsyncApi; +import org.jclouds.abiquo.features.EnterpriseAsyncApi; +import org.jclouds.abiquo.features.EventAsyncApi; +import org.jclouds.abiquo.features.InfrastructureAsyncApi; +import org.jclouds.abiquo.features.PricingAsyncApi; +import org.jclouds.abiquo.features.TaskAsyncApi; +import org.jclouds.abiquo.features.VirtualMachineTemplateAsyncApi; +import org.jclouds.rest.annotations.Delegate; + +import com.abiquo.model.transport.SingleResourceTransportDto; + +/** + * Provides asynchronous access to Abiquo via their REST API. + * + * @see API: + * http://community.abiquo.com/display/ABI20/API+Reference + * @see InfrastructureAsyncApi + * @author Ignasi Barrera + */ +public interface AbiquoAsyncApi { + /** + * The version of the supported Abiquo API. + */ + public static final String API_VERSION = SingleResourceTransportDto.API_VERSION; + + /** + * The supported build version of the Abiquo Api. + */ + public static final String BUILD_VERSION = "7bbfe95-158721b"; + + /** + * Provides asynchronous access to Admin features. + */ + @Delegate + AdminAsyncApi getAdminApi(); + + /** + * Provides asynchronous access to Infrastructure features. + */ + @Delegate + InfrastructureAsyncApi getInfrastructureApi(); + + /** + * Provides asynchronous access to Cloud features. + */ + @Delegate + CloudAsyncApi getCloudApi(); + + /** + * Provides asynchronous access to Apps library features. + */ + @Delegate + VirtualMachineTemplateAsyncApi getVirtualMachineTemplateApi(); + + /** + * Provides asynchronous access to Enterprise features. + */ + @Delegate + EnterpriseAsyncApi getEnterpriseApi(); + + /** + * Provides asynchronous access to configuration features. + */ + @Delegate + ConfigAsyncApi getConfigApi(); + + /** + * Provides asynchronous access to task asynchronous features. + */ + @Delegate + TaskAsyncApi getTaskApi(); + + /** + * Provides asynchronous access to Event features. + */ + @Delegate + EventAsyncApi getEventApi(); + + /** + * Provides asynchronous access to Pricing features. + */ + @Delegate + PricingAsyncApi getPricingApi(); +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/AbiquoContext.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/AbiquoContext.java new file mode 100644 index 0000000000..7989a90ef2 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/AbiquoContext.java @@ -0,0 +1,93 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo; + +import org.jclouds.abiquo.features.services.AdministrationService; +import org.jclouds.abiquo.features.services.CloudService; +import org.jclouds.abiquo.features.services.EventService; +import org.jclouds.abiquo.features.services.MonitoringService; +import org.jclouds.abiquo.features.services.PricingService; +import org.jclouds.abiquo.features.services.SearchService; +import org.jclouds.abiquo.internal.AbiquoContextImpl; +import org.jclouds.compute.ComputeServiceContext; +import org.jclouds.rest.RestContext; + +import com.google.inject.ImplementedBy; + +/** + * Abiquo {@link ComputeServiceContext} implementation to expose high level + * Abiquo functionalities. + * + * @author Ignasi Barrera + */ +@ImplementedBy(AbiquoContextImpl.class) +public interface AbiquoContext extends ComputeServiceContext { + /** + * Returns the Abiquo API context, providing direct access to the Abiquo Rest + * API. + * + * @return The Abiquo API context. + */ + RestContext getApiContext(); + + /** + * Returns the administration service. + *

+ * This service provides an entry point to infrastructure administration + * tasks. + */ + AdministrationService getAdministrationService(); + + /** + * Returns the cloud service. + *

+ * This service provides an entry point to cloud management tasks. + */ + CloudService getCloudService(); + + /** + * Returns the search service. + *

+ * This service provides an entry point to listing and filtering tasks. + */ + SearchService getSearchService(); + + /** + * Returns the monitoring service. + *

+ * This service provides an entry point to asynchronous task monitoring + * tasks. + */ + MonitoringService getMonitoringService(); + + /** + * Returns the event service. + *

+ * This service provides an entry point to event management tasks. + */ + EventService getEventService(); + + /** + * Returns the pricing service. + *

+ * This service provides an entry point to pricing management tasks. + */ + PricingService getPricingService(); +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/AppendToPath.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/AppendToPath.java new file mode 100644 index 0000000000..ff05887e99 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/AppendToPath.java @@ -0,0 +1,53 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.binders; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.net.URI; + +import javax.inject.Singleton; + +import org.jclouds.http.HttpRequest; +import org.jclouds.rest.Binder; + +/** + * Appends the parameter value to the end of the request URI. + * + * @author Ignasi Barrera + */ +@Singleton +public class AppendToPath implements Binder { + @SuppressWarnings("unchecked") + @Override + public R bindToRequest(final R request, final Object input) { + // Append the parameter to the request URI + String valueToAppend = getValue(request, checkNotNull(input, "input")); + URI path = URI.create(request.getEndpoint().toString() + "/" + valueToAppend); + return (R) request.toBuilder().endpoint(path).build(); + } + + /** + * Get the value that will be appended to the request URI. + */ + protected String getValue(final R request, final Object input) { + return input.toString(); + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/BindLinkToPath.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/BindLinkToPath.java new file mode 100644 index 0000000000..e7bd255a05 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/BindLinkToPath.java @@ -0,0 +1,46 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.binders; + +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; + +import javax.inject.Singleton; + +import org.jclouds.rest.internal.GeneratedHttpRequest; + +import com.abiquo.model.rest.RESTLink; + +/** + * Binds the given link to the uri. + * + * @author Francesc Montserrat + */ +@Singleton +public class BindLinkToPath extends BindToPath { + + @Override + protected String getNewEndpoint(final GeneratedHttpRequest gRequest, final Object input) { + checkArgument(checkNotNull(input, "input") instanceof RESTLink, "this binder is only valid for RESTLink objects"); + + return ((RESTLink) input).getHref(); + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/BindLinkToPathAndAcceptHeader.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/BindLinkToPathAndAcceptHeader.java new file mode 100644 index 0000000000..e8ae015693 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/BindLinkToPathAndAcceptHeader.java @@ -0,0 +1,50 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.binders; + +import static com.google.common.base.Preconditions.checkNotNull; + +import javax.inject.Singleton; +import javax.ws.rs.core.HttpHeaders; + +import org.jclouds.http.HttpRequest; + +import com.abiquo.model.rest.RESTLink; +import com.google.common.annotations.VisibleForTesting; + +/** + * Binds the given link to the uri and the Accept header. + * + * @author Ignasi Barrera + */ +@Singleton +public class BindLinkToPathAndAcceptHeader extends BindLinkToPath { + @Override + public R bindToRequest(final R request, final Object input) { + R updatedRequest = super.bindToRequest(request, input); + return addHeader(updatedRequest, HttpHeaders.ACCEPT, ((RESTLink) input).getType()); + } + + @SuppressWarnings("unchecked") + @VisibleForTesting + R addHeader(final R request, final String header, final String value) { + return (R) request.toBuilder().replaceHeader(HttpHeaders.ACCEPT, checkNotNull(value, "value")).build(); + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/BindRefsToPayload.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/BindRefsToPayload.java new file mode 100644 index 0000000000..3dc129fcfc --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/BindRefsToPayload.java @@ -0,0 +1,68 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.binders; + +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; + +import javax.inject.Inject; + +import org.jclouds.http.HttpRequest; +import org.jclouds.rest.binders.BindToXMLPayload; +import org.jclouds.xml.XMLParser; + +import com.abiquo.model.rest.RESTLink; +import com.abiquo.model.transport.LinksDto; +import com.abiquo.model.transport.SingleResourceTransportDto; + +/** + * Bind multiple objects to the payload of the request as a list of links. + * + * @author Ignasi Barrera + */ +public abstract class BindRefsToPayload extends BindToXMLPayload { + @Inject + public BindRefsToPayload(final XMLParser xmlParser) { + super(xmlParser); + } + + protected abstract String getRelToUse(final Object input); + + @Override + public R bindToRequest(final R request, final Object input) { + checkArgument(checkNotNull(input, "input") instanceof SingleResourceTransportDto[], + "this binder is only valid for SingleResourceTransportDto arrays"); + + SingleResourceTransportDto[] dtos = (SingleResourceTransportDto[]) input; + LinksDto refs = new LinksDto(); + + for (SingleResourceTransportDto dto : dtos) { + RESTLink editLink = checkNotNull(dto.getEditLink(), "entity must have an edit link"); + + // Do not add repeated references + if (refs.searchLinkByHref(editLink.getHref()) == null) { + refs.addLink(new RESTLink(getRelToUse(input), editLink.getHref())); + } + } + + return super.bindToRequest(request, refs); + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/BindToPath.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/BindToPath.java new file mode 100644 index 0000000000..a8da04c4f0 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/BindToPath.java @@ -0,0 +1,146 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.binders; + +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 java.lang.annotation.Annotation; +import java.net.URI; +import java.util.Arrays; + +import javax.inject.Singleton; + +import org.jclouds.abiquo.rest.annotations.EndpointLink; +import org.jclouds.http.HttpRequest; +import org.jclouds.rest.Binder; +import org.jclouds.rest.binders.BindException; +import org.jclouds.rest.internal.GeneratedHttpRequest; + +import com.abiquo.model.rest.RESTLink; +import com.abiquo.model.transport.SingleResourceTransportDto; +import com.google.common.base.Predicates; +import com.google.common.collect.Iterables; + +/** + * Binds the given object to the path.. + * + * @author Ignasi Barrera + */ +@Singleton +public class BindToPath implements Binder { + @Override + public R bindToRequest(final R request, final Object input) { + checkArgument(checkNotNull(request, "request") instanceof GeneratedHttpRequest, + "this binder is only valid for GeneratedHttpRequests"); + GeneratedHttpRequest gRequest = (GeneratedHttpRequest) request; + checkState(gRequest.getArgs() != null, "args should be initialized at this point"); + + // Update the request URI with the configured link URI + String newEndpoint = getNewEndpoint(gRequest, input); + return bindToPath(request, newEndpoint); + } + + /** + * Get the new endpoint to use. + * + * @param gRequest + * The request. + * @param input + * The input parameter. + * @return The new endpoint to use. + */ + protected String getNewEndpoint(final GeneratedHttpRequest gRequest, final Object input) { + SingleResourceTransportDto dto = checkValidInput(input); + return getLinkToUse(gRequest, dto).getHref(); + } + + /** + * Get the link to be used to build the request URI. + * + * @param request + * The current request. + * @param payload + * The object containing the link. + * @return The link to be used to build the request URI. + */ + static RESTLink getLinkToUse(final GeneratedHttpRequest request, final SingleResourceTransportDto payload) { + int argIndex = request.getArgs().indexOf(payload); + Annotation[] annotations = request.getJavaMethod().getParameterAnnotations()[argIndex]; + + EndpointLink linkName = (EndpointLink) Iterables.find(Arrays.asList(annotations), + Predicates.instanceOf(EndpointLink.class), null); + + if (linkName == null) { + throw new BindException(request, "Expected a EndpointLink annotation but not found in the parameter"); + } + + return checkNotNull(payload.searchLink(linkName.value()), "No link was found in object with rel: " + linkName); + } + + /** + * Bind the given link to the request URI. + * + * @param request + * The request to modify. + * @param endpoint + * The endpoint to use as the request URI. + * @return The updated request. + */ + @SuppressWarnings("unchecked") + static R bindToPath(final R request, final String endpoint) { + // Preserve current query and matrix parameters + String newEndpoint = endpoint + getParameterString(request); + + // Replace the URI with the edit link in the DTO + URI path = URI.create(newEndpoint); + return (R) request.toBuilder().endpoint(path).build(); + } + + protected static SingleResourceTransportDto checkValidInput(final Object input) { + checkArgument(checkNotNull(input, "input") instanceof SingleResourceTransportDto, + "this binder is only valid for SingleResourceTransportDto objects"); + + return (SingleResourceTransportDto) input; + } + + protected static String getParameterString(final R request) { + String endpoint = request.getEndpoint().toString(); + + int query = endpoint.indexOf('?'); + int matrix = endpoint.indexOf(';'); + + if (query == -1 && matrix == -1) { + // No parameters + return ""; + } else if (query != -1 && matrix != -1) { + // Both parameter types + return endpoint.substring(query < matrix ? query : matrix); + } else if (query != -1) { + // Only request parameters + return endpoint.substring(query); + } else { + // Only matrix parameters + return endpoint.substring(matrix); + } + + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/BindToXMLPayloadAndPath.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/BindToXMLPayloadAndPath.java new file mode 100644 index 0000000000..074fa311e7 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/BindToXMLPayloadAndPath.java @@ -0,0 +1,81 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.binders; + +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 javax.inject.Inject; +import javax.inject.Singleton; +import javax.ws.rs.PUT; + +import org.jclouds.http.HttpRequest; +import org.jclouds.rest.binders.BindToXMLPayload; +import org.jclouds.rest.internal.GeneratedHttpRequest; +import org.jclouds.xml.XMLParser; + +import com.abiquo.model.transport.SingleResourceTransportDto; + +/** + * Binds teh given object to the payload and extracts the path parameters from + * the edit link. + *

+ * This method should be used in {@link PUT} methods to automatically extract + * the path parameters from the edit link of the updated object. + * + * @author Ignasi Barrera + */ +@Singleton +public class BindToXMLPayloadAndPath extends BindToXMLPayload { + @Inject + public BindToXMLPayloadAndPath(final XMLParser xmlParser) { + super(xmlParser); + } + + @Override + public R bindToRequest(final R request, final Object payload) { + checkArgument(checkNotNull(request, "request") instanceof GeneratedHttpRequest, + "this binder is only valid for GeneratedHttpRequests"); + GeneratedHttpRequest gRequest = (GeneratedHttpRequest) request; + checkState(gRequest.getArgs() != null, "args should be initialized at this point"); + + // Update the request URI with the configured link URI + String newEndpoint = getNewEndpoint(gRequest, payload); + R updatedRequest = BindToPath.bindToPath(request, newEndpoint); + + // Add the payload + return super.bindToRequest(updatedRequest, payload); + } + + /** + * Get the new endpoint to use. + * + * @param gRequest + * The request. + * @param input + * The input parameter. + * @return The new endpoint to use. + */ + protected String getNewEndpoint(final GeneratedHttpRequest gRequest, final Object input) { + SingleResourceTransportDto dto = BindToPath.checkValidInput(input); + return BindToPath.getLinkToUse(gRequest, dto).getHref(); + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/cloud/BindHardDiskRefsToPayload.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/cloud/BindHardDiskRefsToPayload.java new file mode 100644 index 0000000000..dbcf72f6e3 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/cloud/BindHardDiskRefsToPayload.java @@ -0,0 +1,48 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.binders.cloud; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.abiquo.binders.BindRefsToPayload; +import org.jclouds.xml.XMLParser; + +import com.abiquo.server.core.infrastructure.storage.DiskManagementDto; + +/** + * Bind multiple {@link DiskManagementDto} objects to the payload of the request + * as a list of links. + * + * @author Ignasi Barrera + */ +@Singleton +public class BindHardDiskRefsToPayload extends BindRefsToPayload { + @Inject + public BindHardDiskRefsToPayload(final XMLParser xmlParser) { + super(xmlParser); + } + + @Override + protected String getRelToUse(final Object input) { + return "disk"; + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/cloud/BindIpRefToPayload.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/cloud/BindIpRefToPayload.java new file mode 100644 index 0000000000..e9a1ec4377 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/cloud/BindIpRefToPayload.java @@ -0,0 +1,61 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.binders.cloud; + +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.http.HttpRequest; +import org.jclouds.rest.binders.BindToXMLPayload; +import org.jclouds.xml.XMLParser; + +import com.abiquo.model.rest.RESTLink; +import com.abiquo.model.transport.LinksDto; +import com.abiquo.server.core.infrastructure.network.AbstractIpDto; + +/** + * Bind the link reference to an {@link AbstractIpDto} object into the payload. + * + * @author Ignasi Barrera + */ +@Singleton +public class BindIpRefToPayload extends BindToXMLPayload { + @Inject + public BindIpRefToPayload(final XMLParser xmlParser) { + super(xmlParser); + } + + @Override + public R bindToRequest(final R request, final Object input) { + checkArgument(checkNotNull(input, "input") instanceof AbstractIpDto, + "this binder is only valid for AbstractIpDto objects"); + + AbstractIpDto ip = (AbstractIpDto) input; + RESTLink selfLink = checkNotNull(ip.searchLink("self"), "AbstractIpDto must have an self link"); + + LinksDto refs = new LinksDto(); + refs.addLink(new RESTLink(selfLink.getTitle(), selfLink.getHref())); + + return super.bindToRequest(request, refs); + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/cloud/BindIpRefsToPayload.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/cloud/BindIpRefsToPayload.java new file mode 100644 index 0000000000..71596fe3c7 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/cloud/BindIpRefsToPayload.java @@ -0,0 +1,68 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.binders.cloud; + +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.abiquo.domain.util.LinkUtils; +import org.jclouds.http.HttpRequest; +import org.jclouds.rest.binders.BindToXMLPayload; +import org.jclouds.xml.XMLParser; + +import com.abiquo.model.rest.RESTLink; +import com.abiquo.model.transport.LinksDto; +import com.abiquo.server.core.infrastructure.network.AbstractIpDto; + +/** + * Bind the link reference to an {@link AbstractIpDto} object into the payload. + * + * @author Ignasi Barrera + */ +@Singleton +public class BindIpRefsToPayload extends BindToXMLPayload { + @Inject + public BindIpRefsToPayload(final XMLParser xmlParser) { + super(xmlParser); + } + + @Override + public R bindToRequest(final R request, final Object input) { + checkArgument(checkNotNull(input, "input") instanceof AbstractIpDto[], + "this binder is only valid for AbstractIpDto arrays"); + + AbstractIpDto[] ips = (AbstractIpDto[]) input; + LinksDto refs = new LinksDto(); + + for (AbstractIpDto ip : ips) { + RESTLink selfLink = checkNotNull(LinkUtils.getSelfLink(ip), "AbstractIpDto must have an edit or self link"); + if (refs.searchLinkByHref(selfLink.getHref()) == null) { + RESTLink ref = new RESTLink(selfLink.getTitle(), selfLink.getHref()); + ref.setType(selfLink.getType()); + refs.addLink(ref); + } + } + + return super.bindToRequest(request, refs); + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/cloud/BindMoveVolumeToPath.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/cloud/BindMoveVolumeToPath.java new file mode 100644 index 0000000000..f11d190227 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/cloud/BindMoveVolumeToPath.java @@ -0,0 +1,49 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.binders.cloud; + +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; + +import org.jclouds.abiquo.binders.BindToPath; +import org.jclouds.rest.internal.GeneratedHttpRequest; + +import com.abiquo.model.rest.RESTLink; +import com.abiquo.server.core.infrastructure.storage.VolumeManagementDto; + +/** + * Binds the move volume action to the request endpoint. + * + * @author Ignasi Barrera + */ +public class BindMoveVolumeToPath extends BindToPath { + + @Override + protected String getNewEndpoint(final GeneratedHttpRequest gRequest, final Object input) { + checkArgument(checkNotNull(input, "input") instanceof VolumeManagementDto, + "this binder is only valid for VolumeManagementDto objects"); + + VolumeManagementDto volume = (VolumeManagementDto) input; + RESTLink editLink = checkNotNull(volume.getEditLink(), "VolumeManagementDto must have an edit link"); + + return editLink.getHref() + "/action/move"; + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/cloud/BindNetworkConfigurationRefToPayload.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/cloud/BindNetworkConfigurationRefToPayload.java new file mode 100644 index 0000000000..3ffd9905cd --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/cloud/BindNetworkConfigurationRefToPayload.java @@ -0,0 +1,73 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.binders.cloud; + +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 javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.http.HttpRequest; +import org.jclouds.rest.binders.BindToXMLPayload; +import org.jclouds.rest.internal.GeneratedHttpRequest; +import org.jclouds.xml.XMLParser; + +import com.abiquo.model.rest.RESTLink; +import com.abiquo.model.transport.LinksDto; +import com.abiquo.server.core.cloud.VirtualMachineDto; +import com.abiquo.server.core.infrastructure.network.VLANNetworkDto; +import com.google.common.base.Predicates; +import com.google.common.collect.Iterables; + +/** + * Bind multiple objects to the payload of the request as a list of links. + * + * @author Ignasi Barrera + */ +@Singleton +public class BindNetworkConfigurationRefToPayload extends BindToXMLPayload { + @Inject + public BindNetworkConfigurationRefToPayload(final XMLParser xmlParser) { + super(xmlParser); + } + + @Override + public R bindToRequest(final R request, final Object input) { + checkArgument(checkNotNull(request, "request") instanceof GeneratedHttpRequest, + "this binder is only valid for GeneratedHttpRequests"); + checkArgument(checkNotNull(input, "input") instanceof VLANNetworkDto, + "this binder is only valid for VLANNetworkDto"); + GeneratedHttpRequest gRequest = (GeneratedHttpRequest) request; + checkState(gRequest.getArgs() != null, "args should be initialized at this point"); + + VLANNetworkDto network = (VLANNetworkDto) input; + VirtualMachineDto vm = (VirtualMachineDto) Iterables.find(gRequest.getArgs(), + Predicates.instanceOf(VirtualMachineDto.class)); + + RESTLink configLink = checkNotNull(vm.searchLink("configurations"), "missing required link"); + + LinksDto dto = new LinksDto(); + dto.addLink(new RESTLink("network_configuration", configLink.getHref() + "/" + network.getId())); + + return super.bindToRequest(request, dto); + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/cloud/BindNetworkRefToPayload.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/cloud/BindNetworkRefToPayload.java new file mode 100644 index 0000000000..5d9ede9580 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/cloud/BindNetworkRefToPayload.java @@ -0,0 +1,78 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.binders.cloud; + +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.http.HttpRequest; +import org.jclouds.rest.binders.BindToXMLPayload; +import org.jclouds.xml.XMLParser; + +import com.abiquo.model.rest.RESTLink; +import com.abiquo.model.transport.LinksDto; +import com.abiquo.server.core.infrastructure.network.VLANNetworkDto; + +/** + * Bind the link reference to an {@link VLANNetworkDto} object into the payload. + * + * @author Ignasi Barrera + */ +@Singleton +public class BindNetworkRefToPayload extends BindToXMLPayload { + @Inject + public BindNetworkRefToPayload(final XMLParser xmlParser) { + super(xmlParser); + } + + @Override + public R bindToRequest(final R request, final Object input) { + checkArgument(checkNotNull(input, "input") instanceof VLANNetworkDto, + "this binder is only valid for VLANNetworkDto objects"); + + VLANNetworkDto network = (VLANNetworkDto) input; + RESTLink editLink = checkNotNull(network.getEditLink(), "VLANNetworkDto must have an edit link"); + + LinksDto refs = new LinksDto(); + switch (network.getType()) { + case INTERNAL: + refs.addLink(new RESTLink("internalnetwork", editLink.getHref())); + break; + case EXTERNAL: + refs.addLink(new RESTLink("externalnetwork", editLink.getHref())); + break; + case PUBLIC: + refs.addLink(new RESTLink("publicnetwork", editLink.getHref())); + break; + case UNMANAGED: + refs.addLink(new RESTLink("unmanagednetwork", editLink.getHref())); + break; + default: + // TODO: EXTERNAL_UNMANAGED network type + throw new IllegalArgumentException("Unsupported network type"); + } + + return super.bindToRequest(request, refs); + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/cloud/BindUnmanagedIpRefToPayload.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/cloud/BindUnmanagedIpRefToPayload.java new file mode 100644 index 0000000000..7d039af54f --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/cloud/BindUnmanagedIpRefToPayload.java @@ -0,0 +1,65 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.binders.cloud; + +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.http.HttpRequest; +import org.jclouds.rest.binders.BindToXMLPayload; +import org.jclouds.xml.XMLParser; + +import com.abiquo.model.enumerator.NetworkType; +import com.abiquo.model.rest.RESTLink; +import com.abiquo.model.transport.LinksDto; +import com.abiquo.server.core.infrastructure.network.AbstractIpDto; +import com.abiquo.server.core.infrastructure.network.VLANNetworkDto; + +/** + * Bind the link reference to an {@link AbstractIpDto} object into the payload. + * + * @author Ignasi Barrera + */ +@Singleton +public class BindUnmanagedIpRefToPayload extends BindToXMLPayload { + @Inject + public BindUnmanagedIpRefToPayload(final XMLParser xmlParser) { + super(xmlParser); + } + + @Override + public R bindToRequest(final R request, final Object input) { + checkArgument(checkNotNull(input, "input") instanceof VLANNetworkDto, + "this binder is only valid for VLANNetworkDto objects"); + + VLANNetworkDto network = (VLANNetworkDto) input; + checkArgument(network.getType() == NetworkType.UNMANAGED, "this binder is only valid for UNMANAGED networks"); + + RESTLink ipsLink = checkNotNull(network.searchLink("ips"), "VLANNetworkDto must have an ips link"); + + LinksDto refs = new LinksDto(); + refs.addLink(new RESTLink("unmanagedip", ipsLink.getHref())); + + return super.bindToRequest(request, refs); + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/cloud/BindVirtualDatacenterRefToPayload.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/cloud/BindVirtualDatacenterRefToPayload.java new file mode 100644 index 0000000000..15a8236d97 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/cloud/BindVirtualDatacenterRefToPayload.java @@ -0,0 +1,63 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.binders.cloud; + +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.http.HttpRequest; +import org.jclouds.rest.binders.BindToXMLPayload; +import org.jclouds.xml.XMLParser; + +import com.abiquo.model.rest.RESTLink; +import com.abiquo.model.transport.LinksDto; +import com.abiquo.server.core.cloud.VirtualDatacenterDto; +import com.abiquo.server.core.infrastructure.storage.VolumeManagementDto; + +/** + * Bind multiple {@link VolumeManagementDto} objects to the payload of the + * request as a list of links. + * + * @author Ignasi Barrera + */ +@Singleton +public class BindVirtualDatacenterRefToPayload extends BindToXMLPayload { + @Inject + public BindVirtualDatacenterRefToPayload(final XMLParser xmlParser) { + super(xmlParser); + } + + @Override + public R bindToRequest(final R request, final Object input) { + checkArgument(checkNotNull(input, "input") instanceof VirtualDatacenterDto, + "this binder is only valid for VirtualDatacenterDto objects"); + + VirtualDatacenterDto vdc = (VirtualDatacenterDto) input; + RESTLink editLink = checkNotNull(vdc.getEditLink(), "VirtualDatacenterDto must have an edit link"); + LinksDto refs = new LinksDto(); + refs.addLink(new RESTLink("virtualdatacenter", editLink.getHref())); + + return super.bindToRequest(request, refs); + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/cloud/BindVolumeRefsToPayload.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/cloud/BindVolumeRefsToPayload.java new file mode 100644 index 0000000000..2ecb289b4a --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/cloud/BindVolumeRefsToPayload.java @@ -0,0 +1,48 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.binders.cloud; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.abiquo.binders.BindRefsToPayload; +import org.jclouds.xml.XMLParser; + +import com.abiquo.server.core.infrastructure.storage.VolumeManagementDto; + +/** + * Bind multiple {@link VolumeManagementDto} objects to the payload of the + * request as a list of links. + * + * @author Ignasi Barrera + */ +@Singleton +public class BindVolumeRefsToPayload extends BindRefsToPayload { + @Inject + public BindVolumeRefsToPayload(final XMLParser xmlParser) { + super(xmlParser); + } + + @Override + protected String getRelToUse(final Object input) { + return "volume"; + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/infrastructure/AppendMachineIdToPath.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/infrastructure/AppendMachineIdToPath.java new file mode 100644 index 0000000000..f24c92cd50 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/infrastructure/AppendMachineIdToPath.java @@ -0,0 +1,50 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.binders.infrastructure; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.abiquo.binders.AppendToPath; +import org.jclouds.abiquo.domain.infrastructure.Machine; +import org.jclouds.abiquo.functions.infrastructure.ParseMachineId; +import org.jclouds.http.HttpRequest; + +/** + * Append the {@link Machine} id to the request URI. + * + * @author Ignasi Barrera + */ +@Singleton +public class AppendMachineIdToPath extends AppendToPath { + private ParseMachineId parser; + + @Inject + public AppendMachineIdToPath(final ParseMachineId parser) { + super(); + this.parser = parser; + } + + @Override + protected String getValue(final R request, final Object input) { + return parser.apply(input); + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/infrastructure/AppendRemoteServiceTypeToPath.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/infrastructure/AppendRemoteServiceTypeToPath.java new file mode 100644 index 0000000000..77cd04de57 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/infrastructure/AppendRemoteServiceTypeToPath.java @@ -0,0 +1,52 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.binders.infrastructure; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.abiquo.binders.AppendToPath; +import org.jclouds.abiquo.functions.infrastructure.ParseRemoteServiceType; +import org.jclouds.http.HttpRequest; + +/** + * Append the {@link RemoteServiceType} service to the request URI. + *

+ * This method assumes that the input object is a {@link RemoteServiceType} + * enumeration. + * + * @author Ignasi Barrera + */ +@Singleton +public class AppendRemoteServiceTypeToPath extends AppendToPath { + private ParseRemoteServiceType parser; + + @Inject + public AppendRemoteServiceTypeToPath(final ParseRemoteServiceType parser) { + super(); + this.parser = parser; + } + + @Override + protected String getValue(final R request, final Object input) { + return parser.apply(input); + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/infrastructure/BindSupportedDevicesLinkToPath.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/infrastructure/BindSupportedDevicesLinkToPath.java new file mode 100644 index 0000000000..e35dff8c23 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/infrastructure/BindSupportedDevicesLinkToPath.java @@ -0,0 +1,40 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.binders.infrastructure; + +import javax.inject.Singleton; + +import org.jclouds.abiquo.binders.BindToPath; +import org.jclouds.rest.internal.GeneratedHttpRequest; + +/** + * Binds the given link to the uri appends the supported devices action path. + * + * @author Ignasi Barrera + */ +@Singleton +public class BindSupportedDevicesLinkToPath extends BindToPath { + + @Override + protected String getNewEndpoint(final GeneratedHttpRequest gRequest, final Object input) { + return super.getNewEndpoint(gRequest, input) + "/action/supported"; + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/infrastructure/ucs/BindLogicServerParameters.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/infrastructure/ucs/BindLogicServerParameters.java new file mode 100644 index 0000000000..fc405ad20b --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/infrastructure/ucs/BindLogicServerParameters.java @@ -0,0 +1,51 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.binders.infrastructure.ucs; + +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; + +import javax.inject.Singleton; + +import org.jclouds.http.HttpRequest; +import org.jclouds.rest.Binder; + +import com.abiquo.server.core.infrastructure.LogicServerDto; + +/** + * Binds logic server query parameters to request. This method assumes that the + * input object is a {@link LogicServerDto}. + * + * @author Francesc Montserrat + * @author Ignasi Barrera + */ +@Singleton +public class BindLogicServerParameters implements Binder { + @SuppressWarnings("unchecked") + @Override + public R bindToRequest(final R request, final Object input) { + checkArgument(checkNotNull(input, "input") instanceof LogicServerDto, + "this binder is only valid for LogicServerDto objects"); + + LogicServerDto server = (LogicServerDto) input; + + return (R) request.toBuilder().addQueryParam("lsName", server.getName()).build(); + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/infrastructure/ucs/BindOrganizationParameters.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/infrastructure/ucs/BindOrganizationParameters.java new file mode 100644 index 0000000000..2a56a43923 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/binders/infrastructure/ucs/BindOrganizationParameters.java @@ -0,0 +1,52 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.binders.infrastructure.ucs; + +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; + +import javax.inject.Singleton; + +import org.jclouds.http.HttpRequest; +import org.jclouds.rest.Binder; + +import com.abiquo.server.core.infrastructure.OrganizationDto; + +/** + * Binds organization query parameters to request. This method assumes that the + * input object is a {@link OrganizationDto}. + * + * @author Francesc Montserrat + * @author Ignasi Barrera + */ +@Singleton +public class BindOrganizationParameters implements Binder { + + @SuppressWarnings("unchecked") + @Override + public R bindToRequest(final R request, final Object input) { + checkArgument(checkNotNull(input, "input") instanceof OrganizationDto, + "this binder is only valid for OrganizationDto objects"); + + OrganizationDto org = (OrganizationDto) input; + + return (R) request.toBuilder().addQueryParam("org", org.getDn()).build(); + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/compute/config/AbiquoComputeServiceContextModule.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/compute/config/AbiquoComputeServiceContextModule.java new file mode 100644 index 0000000000..fe72c8d88e --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/compute/config/AbiquoComputeServiceContextModule.java @@ -0,0 +1,79 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.compute.config; + +import org.jclouds.abiquo.compute.functions.DatacenterToLocation; +import org.jclouds.abiquo.compute.functions.VirtualDatacenterToLocation; +import org.jclouds.abiquo.compute.functions.VirtualMachineTemplateToImage; +import org.jclouds.abiquo.compute.functions.VirtualMachineTemplateInVirtualDatacenterToHardware; +import org.jclouds.abiquo.compute.functions.VirtualMachineToNodeMetadata; +import org.jclouds.abiquo.compute.options.AbiquoTemplateOptions; +import org.jclouds.abiquo.compute.strategy.AbiquoComputeServiceAdapter; +import org.jclouds.abiquo.domain.cloud.VirtualDatacenter; +import org.jclouds.abiquo.domain.cloud.VirtualMachine; +import org.jclouds.abiquo.domain.cloud.VirtualMachineTemplate; +import org.jclouds.abiquo.domain.cloud.VirtualMachineTemplateInVirtualDatacenter; +import org.jclouds.abiquo.domain.infrastructure.Datacenter; +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.options.TemplateOptions; +import org.jclouds.domain.Location; +import org.jclouds.location.suppliers.ImplicitLocationSupplier; +import org.jclouds.location.suppliers.implicit.OnlyLocationOrFirstZone; + +import com.google.common.base.Function; +import com.google.inject.Scopes; +import com.google.inject.TypeLiteral; + +/** + * Abiquo Compute service configuration module. + * + * @author Ignasi Barrera + */ +public class AbiquoComputeServiceContextModule + extends + ComputeServiceAdapterContextModule { + + @Override + protected void configure() { + super.configure(); + bind( + new TypeLiteral>() { + }).to(AbiquoComputeServiceAdapter.class); + bind(new TypeLiteral>() { + }).to(VirtualMachineToNodeMetadata.class); + bind(new TypeLiteral>() { + }).to(VirtualMachineTemplateToImage.class); + bind(new TypeLiteral>() { + }).to(VirtualMachineTemplateInVirtualDatacenterToHardware.class); + bind(new TypeLiteral>() { + }).to(DatacenterToLocation.class); + bind(new TypeLiteral>() { + }).to(VirtualDatacenterToLocation.class); + bind(ImplicitLocationSupplier.class).to(OnlyLocationOrFirstZone.class).in(Scopes.SINGLETON); + bind(TemplateOptions.class).to(AbiquoTemplateOptions.class); + install(new LocationsFromComputeServiceAdapterModule() { + }); + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/compute/functions/DatacenterToLocation.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/compute/functions/DatacenterToLocation.java new file mode 100644 index 0000000000..73e0ec53ff --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/compute/functions/DatacenterToLocation.java @@ -0,0 +1,56 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.compute.functions; + +import javax.inject.Singleton; + +import org.jclouds.abiquo.domain.infrastructure.Datacenter; +import org.jclouds.domain.Location; +import org.jclouds.domain.LocationBuilder; +import org.jclouds.domain.LocationScope; + +import com.google.common.base.Function; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; + +/** + * Converts a {@link Datacenter} to a {@link Location} one. + *

+ * Physical datacenters will be considered regions. + * + * @author Ignasi Barrera + */ +@Singleton +public class DatacenterToLocation implements Function { + + @Override + public Location apply(final Datacenter datacenter) { + LocationBuilder builder = new LocationBuilder(); + builder.id(datacenter.getId().toString()); + builder.description(datacenter.getName() + " [" + datacenter.getLocation() + "]"); + builder.metadata(ImmutableMap. of()); + builder.scope(LocationScope.REGION); + builder.iso3166Codes(ImmutableSet. of()); + + builder.parent(new LocationBuilder().scope(LocationScope.PROVIDER).id("abiquo").description("abiquo").build()); + + return builder.build(); + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/compute/functions/VirtualDatacenterToLocation.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/compute/functions/VirtualDatacenterToLocation.java new file mode 100644 index 0000000000..aca53ea8dd --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/compute/functions/VirtualDatacenterToLocation.java @@ -0,0 +1,78 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.compute.functions; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.Map; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.abiquo.domain.cloud.VirtualDatacenter; +import org.jclouds.abiquo.domain.infrastructure.Datacenter; +import org.jclouds.abiquo.reference.rest.ParentLinkName; +import org.jclouds.collect.Memoized; +import org.jclouds.domain.Location; +import org.jclouds.domain.LocationBuilder; +import org.jclouds.domain.LocationScope; + +import com.google.common.base.Function; +import com.google.common.base.Supplier; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; + +/** + * Converts a {@link VirtualDatacenter} to a {@link Location} one. + *

+ * Virtual datacenters will be considered zones, since images will be deployed + * in a virtual datacenter. Each zone will be scoped into a physical datacenter + * (region). + * + * @author Ignasi Barrera + */ +@Singleton +public class VirtualDatacenterToLocation implements Function { + private final Function datacenterToLocation; + + private final Supplier> regionMap; + + @Inject + public VirtualDatacenterToLocation(final Function datacenterToLocation, + @Memoized final Supplier> regionMap) { + this.datacenterToLocation = checkNotNull(datacenterToLocation, "datacenterToLocation"); + this.regionMap = checkNotNull(regionMap, "regionMap"); + } + + @Override + public Location apply(final VirtualDatacenter vdc) { + LocationBuilder builder = new LocationBuilder(); + builder.id(vdc.getId().toString()); + builder.description(vdc.getName()); + builder.metadata(ImmutableMap. of()); + builder.scope(LocationScope.ZONE); + builder.iso3166Codes(ImmutableSet. of()); + + Datacenter parent = regionMap.get().get(vdc.unwrap().getIdFromLink(ParentLinkName.DATACENTER)); + builder.parent(datacenterToLocation.apply(parent)); + + return builder.build(); + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/compute/functions/VirtualMachineStateToNodeState.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/compute/functions/VirtualMachineStateToNodeState.java new file mode 100644 index 0000000000..2ab7e4c272 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/compute/functions/VirtualMachineStateToNodeState.java @@ -0,0 +1,55 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.compute.functions; + +import javax.inject.Singleton; + +import org.jclouds.compute.domain.NodeMetadata.Status; + +import com.abiquo.server.core.cloud.VirtualMachineState; +import com.google.common.base.Function; + +/** + * Converts a {@link VirtualMachineState} object to a {@link Status} one. + * + * @author Ignasi Barrera + */ +@Singleton +public class VirtualMachineStateToNodeState implements Function { + + @Override + public Status apply(final VirtualMachineState state) { + switch (state) { + case ALLOCATED: + case LOCKED: + case CONFIGURED: + case NOT_ALLOCATED: + return Status.PENDING; + case ON: + return Status.RUNNING; + case OFF: + case PAUSED: + return Status.SUSPENDED; + case UNKNOWN: + default: + return Status.UNRECOGNIZED; + } + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/compute/functions/VirtualMachineTemplateInVirtualDatacenterToHardware.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/compute/functions/VirtualMachineTemplateInVirtualDatacenterToHardware.java new file mode 100644 index 0000000000..401b485479 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/compute/functions/VirtualMachineTemplateInVirtualDatacenterToHardware.java @@ -0,0 +1,96 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.compute.functions; + +import static com.google.common.base.Preconditions.checkNotNull; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.abiquo.domain.cloud.VirtualDatacenter; +import org.jclouds.abiquo.domain.cloud.VirtualMachineTemplate; +import org.jclouds.abiquo.domain.cloud.VirtualMachineTemplateInVirtualDatacenter; +import org.jclouds.compute.domain.Hardware; +import org.jclouds.compute.domain.HardwareBuilder; +import org.jclouds.compute.domain.Image; +import org.jclouds.compute.domain.Processor; +import org.jclouds.compute.domain.Volume; +import org.jclouds.compute.domain.VolumeBuilder; +import org.jclouds.compute.predicates.ImagePredicates; +import org.jclouds.domain.Location; + +import com.google.common.base.Function; + +/** + * Transforms a {@link VirtualMachineTemplate} into an {@link Hardware}. + *

+ * Each {@link Image} ({@link VirtualMachineTemplate}) will have one + * {@link Hardware} entity for each zone (scoped to a virtualization technology) + * supported by the image. + * + * @author Ignasi Barrera + */ +@Singleton +public class VirtualMachineTemplateInVirtualDatacenterToHardware implements + Function { + /** The default core speed, 2.0Ghz. */ + public static final double DEFAULT_CORE_SPEED = 2.0; + + private final Function virtualDatacenterToLocation; + + @Inject + public VirtualMachineTemplateInVirtualDatacenterToHardware( + final Function virtualDatacenterToLocation) { + this.virtualDatacenterToLocation = checkNotNull(virtualDatacenterToLocation, "virtualDatacenterToLocation"); + } + + @Override + public Hardware apply(final VirtualMachineTemplateInVirtualDatacenter templateInVirtualDatacenter) { + VirtualMachineTemplate template = templateInVirtualDatacenter.getTemplate(); + VirtualDatacenter virtualDatacenter = templateInVirtualDatacenter.getZone(); + + HardwareBuilder builder = new HardwareBuilder(); + builder.providerId(template.getId().toString()); + builder.id(template.getId().toString() + "/" + virtualDatacenter.getId()); + builder.uri(template.getURI()); + + builder.name(template.getName()); + builder.processor(new Processor(template.getCpuRequired(), DEFAULT_CORE_SPEED)); + builder.ram(template.getRamRequired()); + + // Location information + builder.location(virtualDatacenterToLocation.apply(virtualDatacenter)); + builder.hypervisor(virtualDatacenter.getHypervisorType().name()); + builder.supportsImage(ImagePredicates.idEquals(template.getId().toString())); + + VolumeBuilder volumeBuilder = new VolumeBuilder(); + volumeBuilder.bootDevice(true); + volumeBuilder.size(toGb(template.getHdRequired())); + volumeBuilder.type(Volume.Type.LOCAL); + volumeBuilder.durable(false); + builder.volume(volumeBuilder.build()); + + return builder.build(); + } + + private static float toGb(final long bytes) { + return bytes / 1024 / 1024 / (float) 1024; + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/compute/functions/VirtualMachineTemplateToImage.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/compute/functions/VirtualMachineTemplateToImage.java new file mode 100644 index 0000000000..7eb598d398 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/compute/functions/VirtualMachineTemplateToImage.java @@ -0,0 +1,91 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.compute.functions; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.net.URI; +import java.util.Map; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.abiquo.domain.cloud.VirtualMachineTemplate; +import org.jclouds.abiquo.domain.infrastructure.Datacenter; +import org.jclouds.abiquo.reference.rest.ParentLinkName; +import org.jclouds.collect.Memoized; +import org.jclouds.compute.domain.Image; +import org.jclouds.compute.domain.Image.Status; +import org.jclouds.compute.domain.ImageBuilder; +import org.jclouds.compute.domain.OperatingSystem; +import org.jclouds.domain.Location; + +import com.abiquo.model.rest.RESTLink; +import com.google.common.base.Function; +import com.google.common.base.Supplier; + +/** + * Transforms a {@link VirtualMachineTemplate} into an {@link Image}. + *

+ * Images are scoped to a region (physical datacenter). + * + * @author Ignasi Barrera + */ +@Singleton +public class VirtualMachineTemplateToImage implements Function { + private final Function datacenterToLocation; + + private final Supplier> regionMap; + + @Inject + public VirtualMachineTemplateToImage(final Function datacenterToLocation, + @Memoized final Supplier> reginoMap) { + this.datacenterToLocation = checkNotNull(datacenterToLocation, "datacenterToLocation"); + this.regionMap = checkNotNull(reginoMap, "reginoMap"); + } + + @Override + public Image apply(final VirtualMachineTemplate template) { + ImageBuilder builder = new ImageBuilder(); + builder.ids(template.getId().toString()); + builder.name(template.getName()); + builder.description(template.getDescription()); + + // Location information + Datacenter region = regionMap.get().get(template.unwrap().getIdFromLink(ParentLinkName.DATACENTER)); + builder.location(datacenterToLocation.apply(region)); + + // Only conversions have a status + builder.status(Status.AVAILABLE); + builder.backendStatus(Status.AVAILABLE.name()); // Abiquo images do not + // have a status + + RESTLink downloadLink = template.unwrap().searchLink("diskfile"); + builder.uri(downloadLink == null ? null : URI.create(downloadLink.getHref())); + + // TODO: Operating system not implemented in Abiquo Templates + // TODO: Image credentials still not present in Abiquo template metadata + // Will be added in Abiquo 2.4: + // http://jira.abiquo.com/browse/ABICLOUDPREMIUM-3647 + builder.operatingSystem(OperatingSystem.builder().description(template.getName()).build()); + + return builder.build(); + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/compute/functions/VirtualMachineToNodeMetadata.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/compute/functions/VirtualMachineToNodeMetadata.java new file mode 100644 index 0000000000..04fd623415 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/compute/functions/VirtualMachineToNodeMetadata.java @@ -0,0 +1,141 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.compute.functions; + +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.collect.Iterables.filter; +import static com.google.common.collect.Iterables.transform; + +import java.util.List; + +import javax.annotation.Resource; +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.abiquo.domain.cloud.VirtualDatacenter; +import org.jclouds.abiquo.domain.cloud.VirtualMachine; +import org.jclouds.abiquo.domain.cloud.VirtualMachineTemplate; +import org.jclouds.abiquo.domain.cloud.VirtualMachineTemplateInVirtualDatacenter; +import org.jclouds.abiquo.domain.network.Ip; +import org.jclouds.abiquo.domain.network.PrivateIp; +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.Processor; +import org.jclouds.domain.Location; +import org.jclouds.logging.Logger; + +import com.abiquo.server.core.cloud.VirtualMachineState; +import com.google.common.base.Function; +import com.google.common.base.Predicates; +import com.google.common.collect.Lists; + +/** + * Links a {@link VirtualMachine} object to a {@link NodeMetadata} one. + * + * @author Ignasi Barrera + */ +@Singleton +public class VirtualMachineToNodeMetadata implements Function { + @Resource + protected Logger logger = Logger.NULL; + + private final VirtualMachineTemplateToImage virtualMachineTemplateToImage; + + private final VirtualMachineTemplateInVirtualDatacenterToHardware virtualMachineTemplateToHardware; + + private final VirtualMachineStateToNodeState virtualMachineStateToNodeState; + + private final Function virtualDatacenterToLocation; + + @Inject + public VirtualMachineToNodeMetadata(final VirtualMachineTemplateToImage virtualMachineTemplateToImage, + final VirtualMachineTemplateInVirtualDatacenterToHardware virtualMachineTemplateToHardware, + final VirtualMachineStateToNodeState virtualMachineStateToNodeState, + final Function virtualDatacenterToLocation) { + this.virtualMachineTemplateToImage = checkNotNull(virtualMachineTemplateToImage, "virtualMachineTemplateToImage"); + this.virtualMachineTemplateToHardware = checkNotNull(virtualMachineTemplateToHardware, + "virtualMachineTemplateToHardware"); + this.virtualMachineStateToNodeState = checkNotNull(virtualMachineStateToNodeState, + "virtualMachineStateToNodeState"); + this.virtualDatacenterToLocation = checkNotNull(virtualDatacenterToLocation, "virtualDatacenterToLocation"); + } + + @Override + public NodeMetadata apply(final VirtualMachine vm) { + NodeMetadataBuilder builder = new NodeMetadataBuilder(); + builder.ids(vm.getId().toString()); + builder.uri(vm.getURI()); + builder.name(vm.getNameLabel()); + builder.group(vm.getVirtualAppliance().getName()); + + // TODO: Node credentials still not present in Abiquo template metadata + // Will be added in Abiquo 2.4: + // http://jira.abiquo.com/browse/ABICLOUDPREMIUM-3647 + + // Location details + VirtualDatacenter vdc = vm.getVirtualDatacenter(); + builder.location(virtualDatacenterToLocation.apply(vdc)); + + // Image details + VirtualMachineTemplate template = vm.getTemplate(); + Image image = virtualMachineTemplateToImage.apply(template); + builder.imageId(image.getId().toString()); + builder.operatingSystem(image.getOperatingSystem()); + + // Hardware details + Hardware defaultHardware = virtualMachineTemplateToHardware.apply(new VirtualMachineTemplateInVirtualDatacenter( + template, vdc)); + + Hardware hardware = HardwareBuilder + .fromHardware(defaultHardware) + .ram(vm.getRam()) + .processors( + Lists.newArrayList(new Processor(vm.getCpu(), + VirtualMachineTemplateInVirtualDatacenterToHardware.DEFAULT_CORE_SPEED))) // + .build(); + + builder.hardware(hardware); + + // Networking configuration + List> nics = vm.listAttachedNics(); + builder.privateAddresses(ips(filter(nics, Predicates.instanceOf(PrivateIp.class)))); + builder.publicAddresses(ips(filter(nics, Predicates.not(Predicates.instanceOf(PrivateIp.class))))); + + // Node state + VirtualMachineState state = vm.getState(); + builder.status(virtualMachineStateToNodeState.apply(state)); + builder.backendStatus(state.name()); + + return builder.build(); + } + + private static Iterable ips(final Iterable> nics) { + return transform(nics, new Function, String>() { + @Override + public String apply(final Ip nic) { + return nic.getIp(); + } + }); + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/compute/options/AbiquoTemplateOptions.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/compute/options/AbiquoTemplateOptions.java new file mode 100644 index 0000000000..00fd6f832e --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/compute/options/AbiquoTemplateOptions.java @@ -0,0 +1,129 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.compute.options; + +import org.jclouds.compute.ComputeService; +import org.jclouds.compute.options.TemplateOptions; + +/** + * Contains options supported by the + * {@link ComputeService#createNodesInGroup(String, int, TemplateOptions)} and + * {@link ComputeService#createNodesInGroup(String, int, TemplateOptions)} + * operations on the Abiquo provider. + * + * @author Ignasi Barrera + */ +public class AbiquoTemplateOptions extends TemplateOptions implements Cloneable { + public static final AbiquoTemplateOptions NONE = new AbiquoTemplateOptions(); + + private Integer overrideCores; + + private Integer overrideRam; + + private String vncPassword; + + @Override + public TemplateOptions clone() { + AbiquoTemplateOptions options = new AbiquoTemplateOptions(); + copyTo(options); + return options; + } + + @Override + public void copyTo(final TemplateOptions to) { + super.copyTo(to); + if (to instanceof AbiquoTemplateOptions) { + AbiquoTemplateOptions options = AbiquoTemplateOptions.class.cast(to); + options.overrideCores(overrideCores); + options.overrideRam(overrideRam); + options.vncPassword(vncPassword); + } + } + + /** + * Override the number of cores set by the hardware profile. + * + * @return The template options with the number of cores. + */ + public AbiquoTemplateOptions overrideCores(final Integer overrideCores) { + this.overrideCores = overrideCores; + return this; + } + + public Integer getOverrideCores() { + return overrideCores; + } + + /** + * Override the amount of ram set by the hardware profile. + * + * @return The template options with the amount of ram. + */ + public AbiquoTemplateOptions overrideRam(final Integer overrideRam) { + this.overrideRam = overrideRam; + return this; + } + + public Integer getOverrideRam() { + return overrideRam; + } + + /** + * Set the VNC password to access the virtual machine. + *

+ * By default virtual machines does not have VNC access password protected. + * + * @return The template options with the VNC password. + */ + public AbiquoTemplateOptions vncPassword(final String vncPassword) { + this.vncPassword = vncPassword; + return this; + } + + public String getVncPassword() { + return vncPassword; + } + + public static class Builder { + /** + * @see AbiquoTemplateOptions#overrideCores(int) + */ + public static AbiquoTemplateOptions overrideCores(final Integer overrideCores) { + AbiquoTemplateOptions options = new AbiquoTemplateOptions(); + return options.overrideCores(overrideCores); + } + + /** + * @see AbiquoTemplateOptions#overrideRam(int) + */ + public static AbiquoTemplateOptions overrideRam(final Integer overrideRam) { + AbiquoTemplateOptions options = new AbiquoTemplateOptions(); + return options.overrideRam(overrideRam); + } + + /** + * @see AbiquoTemplateOptions#vncPassword(String) + */ + public static AbiquoTemplateOptions vncPassword(final String vncPassword) { + AbiquoTemplateOptions options = new AbiquoTemplateOptions(); + return options.vncPassword(vncPassword); + } + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/compute/strategy/AbiquoComputeServiceAdapter.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/compute/strategy/AbiquoComputeServiceAdapter.java new file mode 100644 index 0000000000..a58cc3d4ec --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/compute/strategy/AbiquoComputeServiceAdapter.java @@ -0,0 +1,260 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.compute.strategy; + +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.collect.Iterables.concat; +import static com.google.common.collect.Iterables.transform; + +import java.util.List; +import java.util.Map; + +import javax.annotation.Resource; +import javax.inject.Named; +import javax.inject.Singleton; + +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.compute.options.AbiquoTemplateOptions; +import org.jclouds.abiquo.domain.cloud.VirtualAppliance; +import org.jclouds.abiquo.domain.cloud.VirtualDatacenter; +import org.jclouds.abiquo.domain.cloud.VirtualMachine; +import org.jclouds.abiquo.domain.cloud.VirtualMachineTemplate; +import org.jclouds.abiquo.domain.cloud.VirtualMachineTemplateInVirtualDatacenter; +import org.jclouds.abiquo.domain.enterprise.Enterprise; +import org.jclouds.abiquo.domain.infrastructure.Datacenter; +import org.jclouds.abiquo.domain.network.PublicIp; +import org.jclouds.abiquo.features.services.AdministrationService; +import org.jclouds.abiquo.features.services.CloudService; +import org.jclouds.abiquo.features.services.MonitoringService; +import org.jclouds.abiquo.monitor.VirtualMachineMonitor; +import org.jclouds.abiquo.predicates.cloud.VirtualAppliancePredicates; +import org.jclouds.abiquo.predicates.cloud.VirtualMachineTemplatePredicates; +import org.jclouds.abiquo.predicates.network.IpPredicates; +import org.jclouds.collect.Memoized; +import org.jclouds.compute.ComputeService; +import org.jclouds.compute.ComputeServiceAdapter; +import org.jclouds.compute.domain.Hardware; +import org.jclouds.compute.domain.Processor; +import org.jclouds.compute.domain.Template; +import org.jclouds.compute.reference.ComputeServiceConstants; +import org.jclouds.logging.Logger; +import org.jclouds.rest.RestContext; + +import com.abiquo.server.core.cloud.VirtualMachineState; +import com.google.common.base.Function; +import com.google.common.base.Predicate; +import com.google.common.base.Supplier; +import com.google.common.collect.Lists; +import com.google.inject.Inject; + +/** + * Defines the connection between the {@link AbiquoApi} implementation and the + * jclouds {@link ComputeService}. + * + * @author Ignasi Barrera + */ +@Singleton +public class AbiquoComputeServiceAdapter + implements + ComputeServiceAdapter { + @Resource + @Named(ComputeServiceConstants.COMPUTE_LOGGER) + protected Logger logger = Logger.NULL; + + private final RestContext context; + + private final AdministrationService adminService; + + private final CloudService cloudService; + + private final MonitoringService monitoringService; + + private final FindCompatibleVirtualDatacenters compatibleVirtualDatacenters; + + private final Supplier> regionMap; + + @Inject + public AbiquoComputeServiceAdapter(final RestContext context, + final AdministrationService adminService, final CloudService cloudService, + final MonitoringService monitoringService, + final FindCompatibleVirtualDatacenters compatibleVirtualDatacenters, + @Memoized final Supplier> regionMap) { + this.context = checkNotNull(context, "context"); + this.adminService = checkNotNull(adminService, "adminService"); + this.cloudService = checkNotNull(cloudService, "cloudService"); + this.monitoringService = checkNotNull(monitoringService, "monitoringService"); + this.compatibleVirtualDatacenters = checkNotNull(compatibleVirtualDatacenters, "compatibleVirtualDatacenters"); + this.regionMap = checkNotNull(regionMap, "regionMap"); + } + + @Override + public NodeAndInitialCredentials createNodeWithGroupEncodedIntoName(final String tag, + final String name, final Template template) { + AbiquoTemplateOptions options = template.getOptions().as(AbiquoTemplateOptions.class); + Enterprise enterprise = adminService.getCurrentEnterprise(); + + // Get the region where the template is available + Datacenter datacenter = regionMap.get().get(Integer.valueOf(template.getImage().getLocation().getId())); + + // Load the template + VirtualMachineTemplate virtualMachineTemplate = enterprise.getTemplateInRepository(datacenter, + Integer.valueOf(template.getImage().getId())); + + // Get the zone where the template will be deployed + VirtualDatacenter vdc = cloudService.getVirtualDatacenter(Integer.valueOf(template.getHardware().getLocation() + .getId())); + + // Load the virtual appliance or create it if it does not exist + VirtualAppliance vapp = vdc.findVirtualAppliance(VirtualAppliancePredicates.name(tag)); + if (vapp == null) { + vapp = VirtualAppliance.builder(context, vdc).name(tag).build(); + vapp.save(); + } + + Integer overrideCores = options.getOverrideCores(); + Integer overrideRam = options.getOverrideRam(); + + VirtualMachine vm = VirtualMachine.builder(context, vapp, virtualMachineTemplate) // + .nameLabel(name) // + .cpu(overrideCores != null ? overrideCores : totalCores(template.getHardware())) // + .ram(overrideRam != null ? overrideRam : template.getHardware().getRam()) // + .password(options.getVncPassword()) // Can be null + .build(); + + vm.save(); + + // Once the virtual machine is created, override the default network + // settings if needed + // If no public ip is available in the virtual datacenter, the virtual + // machine will be assigned by default an ip address in the default + // private VLAN for the virtual datacenter + PublicIp publicIp = vdc.findPurchasedPublicIp(IpPredicates. notUsed()); + if (publicIp != null) { + List ips = Lists.newArrayList(); + ips.add(publicIp); + vm.setNics(ips); + } + + // This is an async operation, but jclouds already waits until the node is + // RUNNING, so there is no need to block here + vm.deploy(); + + return new NodeAndInitialCredentials(vm, vm.getId().toString(), null); + } + + @Override + public Iterable listHardwareProfiles() { + // In Abiquo, images are scoped to a region (physical datacenter), and + // hardware profiles are scoped to a zone (a virtual datacenter in the + // region, with a concrete virtualization technology) + + return concat(transform(listImages(), + new Function>() { + @Override + public Iterable apply(final VirtualMachineTemplate template) { + Iterable compatibleZones = compatibleVirtualDatacenters.execute(template); + + return transform(compatibleZones, + new Function() { + @Override + public VirtualMachineTemplateInVirtualDatacenter apply(final VirtualDatacenter vdc) { + return new VirtualMachineTemplateInVirtualDatacenter(template, vdc); + } + }); + } + })); + } + + @Override + public Iterable listImages() { + Enterprise enterprise = adminService.getCurrentEnterprise(); + return enterprise.listTemplates(); + } + + @Override + public VirtualMachineTemplate getImage(final String id) { + Enterprise enterprise = adminService.getCurrentEnterprise(); + return enterprise.findTemplate(VirtualMachineTemplatePredicates.id(Integer.valueOf(id))); + } + + @Override + public Iterable listLocations() { + return cloudService.listVirtualDatacenters(); + } + + @Override + public VirtualMachine getNode(final String id) { + return cloudService.findVirtualMachine(vmId(id)); + } + + @Override + public void destroyNode(final String id) { + VirtualMachine vm = getNode(id); + vm.delete(); + } + + @Override + public void rebootNode(final String id) { + VirtualMachineMonitor monitor = monitoringService.getVirtualMachineMonitor(); + VirtualMachine vm = getNode(id); + vm.reboot(); + monitor.awaitState(VirtualMachineState.ON, vm); + } + + @Override + public void resumeNode(final String id) { + VirtualMachineMonitor monitor = monitoringService.getVirtualMachineMonitor(); + VirtualMachine vm = getNode(id); + vm.changeState(VirtualMachineState.ON); + monitor.awaitState(VirtualMachineState.ON, vm); + } + + @Override + public void suspendNode(final String id) { + VirtualMachineMonitor monitor = monitoringService.getVirtualMachineMonitor(); + VirtualMachine vm = getNode(id); + vm.changeState(VirtualMachineState.PAUSED); + monitor.awaitState(VirtualMachineState.PAUSED, vm); + } + + @Override + public Iterable listNodes() { + return cloudService.listVirtualMachines(); + } + + private static Predicate vmId(final String id) { + return new Predicate() { + @Override + public boolean apply(final VirtualMachine input) { + return Integer.valueOf(id).equals(input.getId()); + } + }; + } + + private static int totalCores(final Hardware hardware) { + double cores = 0; + for (Processor processor : hardware.getProcessors()) { + cores += processor.getCores(); + } + return Double.valueOf(cores).intValue(); + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/compute/strategy/FindCompatibleVirtualDatacenters.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/compute/strategy/FindCompatibleVirtualDatacenters.java new file mode 100644 index 0000000000..a80bb5391e --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/compute/strategy/FindCompatibleVirtualDatacenters.java @@ -0,0 +1,37 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.compute.strategy; + +import org.jclouds.abiquo.compute.strategy.internal.FindCompatibleVirtualDatacentersForImageAndConversions; +import org.jclouds.abiquo.domain.cloud.VirtualDatacenter; +import org.jclouds.abiquo.domain.cloud.VirtualMachineTemplate; + +import com.google.inject.ImplementedBy; + +/** + * Finds all virtual datacenters where the given {@link VirtualMachineTemplate} + * can be deployed. + * + * @author Ignasi Barrera + */ +@ImplementedBy(FindCompatibleVirtualDatacentersForImageAndConversions.class) +public interface FindCompatibleVirtualDatacenters { + Iterable execute(VirtualMachineTemplate template); +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/compute/strategy/internal/FindCompatibleVirtualDatacentersForImageAndConversions.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/compute/strategy/internal/FindCompatibleVirtualDatacentersForImageAndConversions.java new file mode 100644 index 0000000000..d5eecd7b6e --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/compute/strategy/internal/FindCompatibleVirtualDatacentersForImageAndConversions.java @@ -0,0 +1,79 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.abiquo.compute.strategy.internal; + +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.collect.Iterables.filter; +import static org.jclouds.abiquo.domain.DomainWrapper.wrap; +import static org.jclouds.abiquo.predicates.cloud.VirtualDatacenterPredicates.compatibleWithTemplateOrConversions; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.compute.strategy.FindCompatibleVirtualDatacenters; +import org.jclouds.abiquo.domain.cloud.VirtualDatacenter; +import org.jclouds.abiquo.domain.cloud.VirtualMachineTemplate; +import org.jclouds.abiquo.domain.infrastructure.Datacenter; +import org.jclouds.abiquo.features.services.CloudService; +import org.jclouds.abiquo.predicates.cloud.VirtualDatacenterPredicates; +import org.jclouds.abiquo.reference.rest.ParentLinkName; +import org.jclouds.rest.RestContext; + +import com.abiquo.server.core.infrastructure.DatacenterDto; + +/** + * Default implementation for the {@link FindCompatibleVirtualDatacenters} + * strategy. + *

+ * This strategy assumes that the datacenter will have different hypervisor + * technologies, and images will have conversions to each of them. + * + * @author Ignasi Barrera + */ +@Singleton +public class FindCompatibleVirtualDatacentersForImageAndConversions implements FindCompatibleVirtualDatacenters { + private final RestContext context; + + private final CloudService cloudService; + + @Inject + public FindCompatibleVirtualDatacentersForImageAndConversions(final RestContext context, + final CloudService cloudService) { + this.context = checkNotNull(context, "context"); + this.cloudService = checkNotNull(cloudService, "cloudService"); + } + + @Override + public Iterable execute(final VirtualMachineTemplate template) { + // Build the transport object with the available information to avoid + // making an unnecessary call to the target API (we only need the id of + // the datacenter, and it is present in the link). + DatacenterDto datacenterDto = new DatacenterDto(); + datacenterDto.setId(template.unwrap().getIdFromLink(ParentLinkName.DATACENTER_REPOSITORY)); + Datacenter datacenter = wrap(context, Datacenter.class, datacenterDto); + + Iterable vdcs = cloudService.listVirtualDatacenters(VirtualDatacenterPredicates + .datacenter(datacenter)); + + return filter(vdcs, compatibleWithTemplateOrConversions(template)); + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/compute/strategy/internal/FindCompatibleVirtualDatacentersForImageBaseFormat.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/compute/strategy/internal/FindCompatibleVirtualDatacentersForImageBaseFormat.java new file mode 100644 index 0000000000..862bb0bbd2 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/compute/strategy/internal/FindCompatibleVirtualDatacentersForImageBaseFormat.java @@ -0,0 +1,89 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.abiquo.compute.strategy.internal; + +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.collect.Iterables.filter; +import static org.jclouds.abiquo.domain.DomainWrapper.wrap; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.compute.strategy.FindCompatibleVirtualDatacenters; +import org.jclouds.abiquo.domain.cloud.VirtualDatacenter; +import org.jclouds.abiquo.domain.cloud.VirtualMachineTemplate; +import org.jclouds.abiquo.domain.infrastructure.Datacenter; +import org.jclouds.abiquo.features.services.CloudService; +import org.jclouds.abiquo.predicates.cloud.VirtualDatacenterPredicates; +import org.jclouds.abiquo.reference.rest.ParentLinkName; +import org.jclouds.rest.RestContext; + +import com.abiquo.model.enumerator.HypervisorType; +import com.abiquo.server.core.infrastructure.DatacenterDto; +import com.google.common.base.Predicate; + +/** + * Implementation for the {@link FindCompatibleVirtualDatacenters} strategy to + * be used in homogeneous datacenters. + *

+ * For providers that only have one hypervisor technology in the physical + * datacenter and use compatible images, there is no need to check if the images + * have conversions to other formats. + *

+ * This strategy will only consider the base disk format of the image. + * + * @author Ignasi Barrera + */ +@Singleton +public class FindCompatibleVirtualDatacentersForImageBaseFormat implements FindCompatibleVirtualDatacenters { + private final RestContext context; + + private final CloudService cloudService; + + @Inject + public FindCompatibleVirtualDatacentersForImageBaseFormat(final RestContext context, + final CloudService cloudService) { + this.context = checkNotNull(context, "context"); + this.cloudService = checkNotNull(cloudService, "cloudService"); + } + + @Override + public Iterable execute(final VirtualMachineTemplate template) { + // Build the transport object with the available information to avoid + // making an unnecessary call to the target API (we only need the id of + // the datacenter, and it is present in the link). + DatacenterDto datacenterDto = new DatacenterDto(); + datacenterDto.setId(template.unwrap().getIdFromLink(ParentLinkName.DATACENTER_REPOSITORY)); + Datacenter datacenter = wrap(context, Datacenter.class, datacenterDto); + + Iterable vdcs = cloudService.listVirtualDatacenters(VirtualDatacenterPredicates + .datacenter(datacenter)); + + return filter(vdcs, new Predicate() { + @Override + public boolean apply(final VirtualDatacenter vdc) { + HypervisorType type = vdc.getHypervisorType(); + return type.isCompatible(template.getDiskFormatType()); + } + }); + } + +} diff --git a/demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/paas/reference/PaasConstants.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/config/AbiquoEdition.java similarity index 72% rename from demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/paas/reference/PaasConstants.java rename to labs/abiquo/src/main/java/org/jclouds/abiquo/config/AbiquoEdition.java index 8af7021bd2..158b0f5f60 100644 --- a/demos/tweetstore/heroku-tweetstore/src/main/java/org/jclouds/demo/paas/reference/PaasConstants.java +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/config/AbiquoEdition.java @@ -7,7 +7,7 @@ * "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 + * 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 @@ -16,13 +16,14 @@ * specific language governing permissions and limitations * under the License. */ -package org.jclouds.demo.paas.reference; + +package org.jclouds.abiquo.config; /** - * Configuration properties and constants used in PaaS applications. + * The Abiquo Edition (Community or Enterprise). * - * @author Andrew Phillips + * @author Francesc Montserrat */ -public interface PaasConstants { - static final String PROPERTY_PLATFORM_BASE_URL = "jclouds.paas.baseurl"; +public enum AbiquoEdition { + ENTERPRISE, COMMUNITY; } diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/config/AbiquoProperties.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/config/AbiquoProperties.java new file mode 100644 index 0000000000..ab04c893f3 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/config/AbiquoProperties.java @@ -0,0 +1,44 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.config; + +import org.jclouds.abiquo.features.services.MonitoringService; + +/** + * Configuration properties and constants used in Abiquo connections. + * + * @author Ignasi Barrera + */ +public interface AbiquoProperties { + /** + * Boolean property indicating if the provided credential is an api token. + *

+ * Default value: false + */ + public static final String CREDENTIAL_IS_TOKEN = "abiquo.credential-is-token"; + + /** + * The delay (in ms) used between requests by the {@link MonitoringService} + * when monitoring asynchronous task state. + *

+ * Default value: 5000 ms + */ + public static final String ASYNC_TASK_MONITOR_DELAY = "abiquo.monitor-delay"; +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/config/AbiquoRestClientModule.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/config/AbiquoRestClientModule.java new file mode 100644 index 0000000000..c5baf05f9c --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/config/AbiquoRestClientModule.java @@ -0,0 +1,185 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.config; + +import static org.jclouds.Constants.PROPERTY_SESSION_INTERVAL; +import static org.jclouds.abiquo.domain.DomainWrapper.wrap; + +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; + +import javax.inject.Named; + +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.domain.enterprise.Enterprise; +import org.jclouds.abiquo.domain.enterprise.User; +import org.jclouds.abiquo.domain.infrastructure.Datacenter; +import org.jclouds.abiquo.features.AdminApi; +import org.jclouds.abiquo.features.AdminAsyncApi; +import org.jclouds.abiquo.features.CloudApi; +import org.jclouds.abiquo.features.CloudAsyncApi; +import org.jclouds.abiquo.features.ConfigApi; +import org.jclouds.abiquo.features.ConfigAsyncApi; +import org.jclouds.abiquo.features.EnterpriseApi; +import org.jclouds.abiquo.features.EnterpriseAsyncApi; +import org.jclouds.abiquo.features.EventApi; +import org.jclouds.abiquo.features.EventAsyncApi; +import org.jclouds.abiquo.features.InfrastructureApi; +import org.jclouds.abiquo.features.InfrastructureAsyncApi; +import org.jclouds.abiquo.features.PricingApi; +import org.jclouds.abiquo.features.PricingAsyncApi; +import org.jclouds.abiquo.features.TaskApi; +import org.jclouds.abiquo.features.TaskAsyncApi; +import org.jclouds.abiquo.features.VirtualMachineTemplateApi; +import org.jclouds.abiquo.features.VirtualMachineTemplateAsyncApi; +import org.jclouds.abiquo.handlers.AbiquoErrorHandler; +import org.jclouds.abiquo.rest.internal.AbiquoHttpAsyncClient; +import org.jclouds.abiquo.rest.internal.AbiquoHttpClient; +import org.jclouds.abiquo.rest.internal.ExtendedUtils; +import org.jclouds.collect.Memoized; +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.rest.AuthorizationException; +import org.jclouds.rest.ConfiguresRestClient; +import org.jclouds.rest.RestContext; +import org.jclouds.rest.Utils; +import org.jclouds.rest.config.BinderUtils; +import org.jclouds.rest.config.RestClientModule; +import org.jclouds.rest.suppliers.MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier; +import org.jclouds.util.Suppliers2; + +import com.google.common.base.Function; +import com.google.common.base.Supplier; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Maps; +import com.google.inject.Provides; +import com.google.inject.Singleton; + +/** + * Configures the Abiquo connection. + * + * @author Ignasi Barrera + */ +@ConfiguresRestClient +public class AbiquoRestClientModule extends RestClientModule { + public static final Map, Class> DELEGATE_MAP = ImmutableMap., Class> builder() // + .put(InfrastructureApi.class, InfrastructureAsyncApi.class) // + .put(EnterpriseApi.class, EnterpriseAsyncApi.class) // + .put(AdminApi.class, AdminAsyncApi.class) // + .put(ConfigApi.class, ConfigAsyncApi.class) // + .put(CloudApi.class, CloudAsyncApi.class) // + .put(VirtualMachineTemplateApi.class, VirtualMachineTemplateAsyncApi.class) // + .put(TaskApi.class, TaskAsyncApi.class) // + .put(EventApi.class, EventAsyncApi.class) // + .put(PricingApi.class, PricingAsyncApi.class) // + .build(); + + public AbiquoRestClientModule() { + super(DELEGATE_MAP); + } + + @Override + protected void bindAsyncClient() { + super.bindAsyncClient(); + BinderUtils.bindAsyncClient(binder(), AbiquoHttpAsyncClient.class); + } + + @Override + protected void bindClient() { + super.bindClient(); + BinderUtils.bindClient(binder(), AbiquoHttpClient.class, AbiquoHttpAsyncClient.class, + ImmutableMap., Class> of(AbiquoHttpClient.class, AbiquoHttpAsyncClient.class)); + } + + @Override + protected void configure() { + super.configure(); + bind(Utils.class).to(ExtendedUtils.class); + } + + @Override + protected void bindErrorHandlers() { + bind(HttpErrorHandler.class).annotatedWith(Redirection.class).to(AbiquoErrorHandler.class); + bind(HttpErrorHandler.class).annotatedWith(ClientError.class).to(AbiquoErrorHandler.class); + bind(HttpErrorHandler.class).annotatedWith(ServerError.class).to(AbiquoErrorHandler.class); + } + + @Provides + @Singleton + @Memoized + public Supplier getCurrentUser(final AtomicReference authException, + @Named(PROPERTY_SESSION_INTERVAL) final long seconds, final RestContext context) { + return MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier.create(authException, new Supplier() { + @Override + public User get() { + return wrap(context, User.class, context.getApi().getAdminApi().getCurrentUser()); + } + }, seconds, TimeUnit.SECONDS); + } + + @Provides + @Singleton + @Memoized + public Supplier getCurrentEnterprise(final AtomicReference authException, + @Named(PROPERTY_SESSION_INTERVAL) final long seconds, final @Memoized Supplier currentUser) { + return MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier.create(authException, + new Supplier() { + @Override + public Enterprise get() { + return currentUser.get().getEnterprise(); + } + }, seconds, TimeUnit.SECONDS); + } + + @Provides + @Singleton + @Memoized + public Supplier> getAvailableRegionsIndexedById( + final AtomicReference authException, + @Named(PROPERTY_SESSION_INTERVAL) final long seconds, @Memoized final Supplier currentEnterprise) { + Supplier> availableRegionsMapSupplier = Suppliers2.compose( + new Function, Map>() { + @Override + public Map apply(final List datacenters) { + // Index available regions by id + return Maps.uniqueIndex(datacenters, new Function() { + @Override + public Integer apply(final Datacenter input) { + return input.getId(); + } + }); + } + }, new Supplier>() { + @Override + public List get() { + // Get the list of regions available for the user's tenant + return currentEnterprise.get().listAllowedDatacenters(); + } + }); + + return MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier.create(authException, + availableRegionsMapSupplier, seconds, TimeUnit.SECONDS); + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/DomainWithLimitsWrapper.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/DomainWithLimitsWrapper.java new file mode 100644 index 0000000000..82cddcd393 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/DomainWithLimitsWrapper.java @@ -0,0 +1,161 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain; + +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.rest.RestContext; + +import com.abiquo.model.transport.SingleResourceWithLimitsDto; + +/** + * This class is used to decorate transport objects that have limits with high + * level functionality. + * + * @author Ignasi Barrera + */ +public abstract class DomainWithLimitsWrapper extends DomainWrapper { + + protected DomainWithLimitsWrapper(final RestContext context, final T target) { + super(context, target); + } + + // Delegate methods + + public int getCpuCountHardLimit() { + return target.getCpuCountHardLimit(); + } + + public int getCpuCountSoftLimit() { + return target.getCpuCountSoftLimit(); + } + + public long getHdHardLimitInMb() { + return target.getHdHardLimitInMb(); + } + + public long getHdSoftLimitInMb() { + return target.getHdSoftLimitInMb(); + } + + public long getPublicIpsHard() { + return target.getPublicIpsHard(); + } + + public long getPublicIpsSoft() { + return target.getPublicIpsSoft(); + } + + public int getRamHardLimitInMb() { + return target.getRamHardLimitInMb(); + } + + public int getRamSoftLimitInMb() { + return target.getRamSoftLimitInMb(); + } + + public long getStorageHard() { + return target.getStorageHard(); + } + + public long getStorageSoft() { + return target.getStorageSoft(); + } + + public long getVlansHard() { + return target.getVlansHard(); + } + + public long getVlansSoft() { + return target.getVlansSoft(); + } + + public void setCpuCountHardLimit(final int cpuCountHardLimit) { + target.setCpuCountHardLimit(cpuCountHardLimit); + } + + public void setCpuCountLimits(final int softLimit, final int hardLimit) { + target.setCpuCountLimits(softLimit, hardLimit); + } + + public void setCpuCountSoftLimit(final int cpuCountSoftLimit) { + target.setCpuCountSoftLimit(cpuCountSoftLimit); + } + + public void setHdHardLimitInMb(final long hdHardLimitInMb) { + target.setHdHardLimitInMb(hdHardLimitInMb); + } + + public void setHdLimitsInMb(final long softLimit, final long hardLimit) { + target.setHdLimitsInMb(softLimit, hardLimit); + } + + public void setHdSoftLimitInMb(final long hdSoftLimitInMb) { + target.setHdSoftLimitInMb(hdSoftLimitInMb); + } + + public void setPublicIPLimits(final long softLimit, final long hardLimit) { + target.setPublicIPLimits(softLimit, hardLimit); + } + + public void setPublicIpsHard(final long publicIpsHard) { + target.setPublicIpsHard(publicIpsHard); + } + + public void setPublicIpsSoft(final long publicIpsSoft) { + target.setPublicIpsSoft(publicIpsSoft); + } + + public void setRamHardLimitInMb(final int ramHardLimitInMb) { + target.setRamHardLimitInMb(ramHardLimitInMb); + } + + public void setRamLimitsInMb(final int softLimit, final int hardLimit) { + target.setRamLimitsInMb(softLimit, hardLimit); + } + + public void setRamSoftLimitInMb(final int ramSoftLimitInMb) { + target.setRamSoftLimitInMb(ramSoftLimitInMb); + } + + public void setStorageHard(final long storageHard) { + target.setStorageHard(storageHard); + } + + public void setStorageLimits(final long softLimit, final long hardLimit) { + target.setStorageLimits(softLimit, hardLimit); + } + + public void setStorageSoft(final long storageSoft) { + target.setStorageSoft(storageSoft); + } + + public void setVlansHard(final long vlansHard) { + target.setVlansHard(vlansHard); + } + + public void setVlansLimits(final long softLimit, final long hardLimit) { + target.setVlansLimits(softLimit, hardLimit); + } + + public void setVlansSoft(final long vlansSoft) { + target.setVlansSoft(vlansSoft); + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/DomainWithTasksWrapper.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/DomainWithTasksWrapper.java new file mode 100644 index 0000000000..26383ea14b --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/DomainWithTasksWrapper.java @@ -0,0 +1,75 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain; + +import static com.google.common.collect.Iterables.filter; + +import java.util.Collections; +import java.util.List; + +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.domain.task.AsyncTask; +import org.jclouds.rest.RestContext; + +import com.abiquo.model.transport.SingleResourceTransportDto; +import com.abiquo.server.core.task.TaskDto; +import com.abiquo.server.core.task.TasksDto; +import com.google.common.base.Predicate; +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; +import com.google.common.collect.Ordering; +import com.google.common.primitives.Longs; + +/** + * This class is used to decorate transport objects that are owners of some + * {@link TaskDto} + * + * @author Ignasi Barrera + */ +public abstract class DomainWithTasksWrapper extends DomainWrapper { + + protected DomainWithTasksWrapper(final RestContext context, final T target) { + super(context, target); + } + + public List listTasks() { + TasksDto result = context.getApi().getTaskApi().listTasks(target); + List tasks = wrap(context, AsyncTask.class, result.getCollection()); + + // Return the most recent task first + Collections.sort(tasks, new Ordering() { + @Override + public int compare(final AsyncTask left, final AsyncTask right) { + return Longs.compare(left.getTimestamp(), right.getTimestamp()); + } + }.reverse()); + + return tasks; + } + + public List listTasks(final Predicate filter) { + return Lists.newLinkedList(filter(listTasks(), filter)); + } + + public AsyncTask findTask(final Predicate filter) { + return Iterables.getFirst(filter(listTasks(), filter), null); + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/DomainWrapper.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/DomainWrapper.java new file mode 100644 index 0000000000..baca65bc4a --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/DomainWrapper.java @@ -0,0 +1,216 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain; + +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.collect.Iterables.transform; + +import java.lang.reflect.Constructor; +import java.net.URI; +import java.util.ArrayList; +import java.util.List; + +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.domain.exception.WrapperException; +import org.jclouds.abiquo.domain.task.AsyncTask; +import org.jclouds.abiquo.domain.util.LinkUtils; +import org.jclouds.abiquo.reference.ValidationErrors; +import org.jclouds.rest.RestContext; + +import com.abiquo.model.rest.RESTLink; +import com.abiquo.model.transport.AcceptedRequestDto; +import com.abiquo.model.transport.SingleResourceTransportDto; +import com.abiquo.model.transport.WrapperDto; +import com.abiquo.server.core.task.TaskDto; +import com.google.common.base.Function; +import com.google.common.collect.Lists; + +/** + * This class is used to decorate transport objects with high level + * functionality. + * + * @author Francesc Montserrat + * @author Ignasi Barrera + */ +public abstract class DomainWrapper { + /** The rest context. */ + protected RestContext context; + + /** The wrapped object. */ + protected T target; + + protected DomainWrapper(final RestContext context, final T target) { + super(); + this.context = checkNotNull(context, "context"); + this.target = checkNotNull(target, "target"); + } + + /** + * Returns the URI that identifies the transport object + * + * @return The URI identifying the transport object + */ + public URI getURI() { + RESTLink link = LinkUtils.getSelfLink(target); + return link == null ? null : URI.create(link.getHref()); + } + + /** + * Returns the wrapped object. + */ + public T unwrap() { + return target; + } + + /** + * Read the ID of the parent resource from the given link. + * + * @param parentLinkRel + * The link to the parent resource. + * @return The ID of the parent resource. + */ + protected Integer getParentId(final String parentLinkRel) { + return target.getIdFromLink(parentLinkRel); + } + + /** + * Wraps an object in the given wrapper class. + */ + public static > W wrap( + final RestContext context, final Class wrapperClass, final T target) { + if (target == null) { + return null; + } + + try { + Constructor cons = wrapperClass.getDeclaredConstructor(RestContext.class, target.getClass()); + if (!cons.isAccessible()) { + cons.setAccessible(true); + } + return cons.newInstance(context, target); + } catch (Exception ex) { + throw new WrapperException(wrapperClass, target, ex); + } + } + + /** + * Wrap a collection of objects to the given wrapper class. + */ + public static > List wrap( + final RestContext context, final Class wrapperClass, final Iterable targets) { + if (targets == null) { + return null; + } + + return Lists.newLinkedList(transform(targets, new Function() { + @Override + public W apply(final T input) { + return wrap(context, wrapperClass, input); + } + })); + } + + /** + * Unwrap a collection of objects. + */ + public static > List unwrap( + final Iterable targets) { + return Lists.newLinkedList(transform(targets, new Function() { + @Override + public T apply(final W input) { + return input.unwrap(); + } + })); + } + + /** + * Update or creates a link of "target" with the uri of a link from "source". + */ + protected void updateLink( + final T1 target, final String targetLinkRel, final T2 source, final String sourceLinkRel) { + RESTLink parent = null; + + checkNotNull(source.searchLink(sourceLinkRel), ValidationErrors.MISSING_REQUIRED_LINK); + + // Insert + if ((parent = target.searchLink(targetLinkRel)) == null) { + target.addLink(new RESTLink(targetLinkRel, source.searchLink(sourceLinkRel).getHref())); + } + // Replace + else { + parent.setHref(source.searchLink(sourceLinkRel).getHref()); + } + } + + /** + * Join a collection of {@link WrapperDto} objects in a single collection + * with all the elements of each wrapper object. + */ + public static Iterable join( + final Iterable> collection) { + List dtos = Lists.newLinkedList(); + for (WrapperDto wrapper : collection) { + dtos.addAll(wrapper.getCollection()); + } + return dtos; + } + + /** + * Utility method to get an {@link AsyncTask} given an + * {@link AcceptedRequestDto}. + * + * @param acceptedRequest + * The accepted request dto. + * @return The async task. + */ + protected AsyncTask getTask(final AcceptedRequestDto acceptedRequest) { + RESTLink taskLink = acceptedRequest.getStatusLink(); + checkNotNull(taskLink, ValidationErrors.MISSING_REQUIRED_LINK + AsyncTask.class); + + // This will return null on untrackable tasks + TaskDto task = context.getApi().getTaskApi().getTask(taskLink); + return wrap(context, AsyncTask.class, task); + } + + /** + * Utility method to get all {@link AsyncTask} related to an + * {@link AcceptedRequestDto}. + * + * @param acceptedRequest + * The accepted request dto. + * @return The async task array. + */ + protected AsyncTask[] getTasks(final AcceptedRequestDto acceptedRequest) { + List tasks = new ArrayList(); + + for (RESTLink link : acceptedRequest.getLinks()) { + // This will return null on untrackable tasks + TaskDto task = context.getApi().getTaskApi().getTask(link); + if (task != null) { + tasks.add(wrap(context, AsyncTask.class, task)); + } + } + + AsyncTask[] taskArr = new AsyncTask[tasks.size()]; + return tasks.toArray(taskArr); + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/builder/LimitsBuilder.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/builder/LimitsBuilder.java new file mode 100644 index 0000000000..013e0a3c8c --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/builder/LimitsBuilder.java @@ -0,0 +1,98 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.builder; + +/** + * Base class for all builders that represent limits. + * + * @author Ignasi Barrera + * @param + * The type of the target builder. + */ +public abstract class LimitsBuilder> { + /** The default limits for enterprises (unlimited). */ + protected static final int DEFAULT_LIMITS = 0; + + protected Integer ramSoftLimitInMb = DEFAULT_LIMITS; + + protected Integer ramHardLimitInMb = DEFAULT_LIMITS; + + protected Integer cpuCountSoftLimit = DEFAULT_LIMITS; + + protected Integer cpuCountHardLimit = DEFAULT_LIMITS; + + protected Long hdSoftLimitInMb = Long.valueOf(DEFAULT_LIMITS); + + protected Long hdHardLimitInMb = Long.valueOf(DEFAULT_LIMITS); + + protected Long storageSoft = Long.valueOf(DEFAULT_LIMITS); + + protected Long storageHard = Long.valueOf(DEFAULT_LIMITS); + + protected Long vlansSoft = Long.valueOf(DEFAULT_LIMITS); + + protected Long vlansHard = Long.valueOf(DEFAULT_LIMITS); + + protected Long publicIpsSoft = Long.valueOf(DEFAULT_LIMITS); + + protected Long publicIpsHard = Long.valueOf(DEFAULT_LIMITS); + + @SuppressWarnings("unchecked") + public T ramLimits(final int soft, final int hard) { + this.ramSoftLimitInMb = soft; + this.ramHardLimitInMb = hard; + return (T) this; + } + + @SuppressWarnings("unchecked") + public T cpuCountLimits(final int soft, final int hard) { + this.cpuCountSoftLimit = soft; + this.cpuCountHardLimit = hard; + return (T) this; + } + + @SuppressWarnings("unchecked") + public T hdLimitsInMb(final long soft, final long hard) { + this.hdSoftLimitInMb = soft; + this.hdHardLimitInMb = hard; + return (T) this; + } + + @SuppressWarnings("unchecked") + public T storageLimits(final long soft, final long hard) { + this.storageSoft = soft; + this.storageHard = hard; + return (T) this; + } + + @SuppressWarnings("unchecked") + public T vlansLimits(final long soft, final long hard) { + this.vlansSoft = soft; + this.vlansHard = hard; + return (T) this; + } + + @SuppressWarnings("unchecked") + public T publicIpsLimits(final long soft, final long hard) { + this.publicIpsSoft = soft; + this.publicIpsHard = hard; + return (T) this; + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/cloud/Conversion.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/cloud/Conversion.java new file mode 100644 index 0000000000..5564352624 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/cloud/Conversion.java @@ -0,0 +1,145 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.cloud; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.Date; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.domain.DomainWithTasksWrapper; +import org.jclouds.abiquo.domain.task.AsyncTask; +import org.jclouds.abiquo.reference.ValidationErrors; +import org.jclouds.abiquo.reference.rest.ParentLinkName; +import org.jclouds.abiquo.rest.internal.ExtendedUtils; +import org.jclouds.http.HttpResponse; +import org.jclouds.http.functions.ParseXMLWithJAXB; +import org.jclouds.rest.RestContext; + +import com.abiquo.model.enumerator.ConversionState; +import com.abiquo.model.enumerator.DiskFormatType; +import com.abiquo.model.rest.RESTLink; +import com.abiquo.server.core.appslibrary.ConversionDto; +import com.abiquo.server.core.appslibrary.VirtualMachineTemplateDto; +import com.google.inject.TypeLiteral; + +/** + * Adds high level functionality to {@link ConversionDto}. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + * @see API: + * http://community.abiquo.com/display/ABI20/Conversion+Resource + */ +public class Conversion extends DomainWithTasksWrapper { + /** + * Constructor to be used only by the builder. + */ + protected Conversion(final RestContext context, final ConversionDto target) { + super(context, target); + } + + // Domain methods + + public void refresh() { + RESTLink link = checkNotNull(target.searchLink("edit"), ValidationErrors.MISSING_REQUIRED_LINK + "edit"); + + ExtendedUtils utils = (ExtendedUtils) context.getUtils(); + HttpResponse response = checkNotNull(utils.getAbiquoHttpClient().get(link), "conversion"); + + ParseXMLWithJAXB parser = new ParseXMLWithJAXB(utils.getXml(), + TypeLiteral.get(ConversionDto.class)); + + target = parser.apply(response); + } + + // Parent access + + /** + * @see API: http://community.abiquo.com/display/ABI20/Virtual+Machine+Template+ + * Resource + */ + public VirtualMachineTemplate getVirtualMachineTemplate() { + RESTLink link = checkNotNull(target.searchLink(ParentLinkName.VIRTUAL_MACHINE_TEMPLATE), + ValidationErrors.MISSING_REQUIRED_LINK + " " + ParentLinkName.VIRTUAL_MACHINE_TEMPLATE); + + ExtendedUtils utils = (ExtendedUtils) context.getUtils(); + HttpResponse response = utils.getAbiquoHttpClient().get(link); + + ParseXMLWithJAXB parser = new ParseXMLWithJAXB( + utils.getXml(), TypeLiteral.get(VirtualMachineTemplateDto.class)); + + return wrap(context, VirtualMachineTemplate.class, parser.apply(response)); + } + + /** + * Starts a new BPM task to regenerate a failed conversion. + * + * @see API: http://community.abiquo.com/display/ABI20/Conversion+Resource# + * ConversionResource- UpdateConversion + * @return The task reference to track its progress + */ + public AsyncTask restartFailedConversion() { + return getVirtualMachineTemplate().requestConversion(getTargetFormat()); + } + + // Delegate methods + + public String getSourcePath() { + return target.getSourcePath(); + } + + public ConversionState getState() { + return target.getState(); + } + + public String getTargetPath() { + return target.getTargetPath(); + } + + public Long getTargetSizeInBytes() { + return target.getTargetSizeInBytes(); + } + + public DiskFormatType getSourceFormat() { + return target.getSourceFormat(); + } + + public DiskFormatType getTargetFormat() { + return target.getTargetFormat(); + } + + public Date getStartTimestamp() { + return target.getStartTimestamp(); + } + + @Override + public String toString() { + return "Conversion [sourcePath=" + getSourcePath() + ", sourceFormat=" + getSourceFormat() + ", targetPath=" + + getTargetPath() + ", targetFormat=" + getTargetFormat() + ", targetSizeInBytes=" + getTargetSizeInBytes() + + ", startTimestamp=" + getStartTimestamp() + ", state=" + getState() + "]"; + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/cloud/HardDisk.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/cloud/HardDisk.java new file mode 100644 index 0000000000..81d9af7072 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/cloud/HardDisk.java @@ -0,0 +1,164 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.cloud; + +import static com.google.common.base.Preconditions.checkNotNull; + +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.domain.DomainWrapper; +import org.jclouds.abiquo.reference.ValidationErrors; +import org.jclouds.abiquo.reference.rest.ParentLinkName; +import org.jclouds.rest.RestContext; + +import com.abiquo.server.core.cloud.VirtualDatacenterDto; +import com.abiquo.server.core.infrastructure.storage.DiskManagementDto; + +/** + * Represents a disk attached to a virtual machine. + *

+ * This disks will be created when a virtual machine is deployed, and will be + * destroyed when it is undeployed. If there is a need to use persistent + * storage, a persistent {@link Volume} should be used instead. + * + * @author Ignasi Barrera + * @see API: + * http://community.abiquo.com/display/ABI20/Hard+Disks+Resource + */ +public class HardDisk extends DomainWrapper { + /** The virtual datacenter where the hard disk belongs. */ + private VirtualDatacenter virtualDatacenter; + + /** + * Constructor to be used only by the builder. + */ + protected HardDisk(final RestContext context, final DiskManagementDto target) { + super(context, target); + } + + // Domain operations + + /** + * Creates the hard disk in the selected virtual datacenter. + *

+ * Once the hard disk has been created it can be attached to a virtual + * machine of the virtual datacenter. + */ + public void save() { + target = context.getApi().getCloudApi().createHardDisk(virtualDatacenter.unwrap(), target); + } + + /** + * Deletes the hard disk. + */ + public void delete() { + context.getApi().getCloudApi().deleteHardDisk(target); + target = null; + } + + // Parent access + + /** + * Gets the virtual datacenter where the hard disk belongs to. + * + * @see API: http://community.abiquo.com/display/ABI20/Virtual+Datacenter+ + * Resource# VirtualDatacenterResource-RetrieveaVirtualDatacenter + */ + public VirtualDatacenter getVirtualDatacenter() { + Integer virtualDatacenterId = target.getIdFromLink(ParentLinkName.VIRTUAL_DATACENTER); + VirtualDatacenterDto dto = context.getApi().getCloudApi().getVirtualDatacenter(virtualDatacenterId); + virtualDatacenter = wrap(context, VirtualDatacenter.class, dto); + return virtualDatacenter; + } + + // Builder + + public static Builder builder(final RestContext context, + final VirtualDatacenter virtualDatacenter) { + return new Builder(context, virtualDatacenter); + } + + public static class Builder { + private RestContext context; + + private Long sizeInMb; + + private VirtualDatacenter virtualDatacenter; + + public Builder(final RestContext context, final VirtualDatacenter virtualDatacenter) { + super(); + checkNotNull(virtualDatacenter, ValidationErrors.NULL_RESOURCE + VirtualDatacenter.class); + this.context = context; + this.virtualDatacenter = virtualDatacenter; + } + + public Builder sizeInMb(final long sizeInMb) { + this.sizeInMb = sizeInMb; + return this; + } + + public HardDisk build() { + DiskManagementDto dto = new DiskManagementDto(); + dto.setSizeInMb(sizeInMb); + + HardDisk hardDisk = new HardDisk(context, dto); + hardDisk.virtualDatacenter = virtualDatacenter; + + return hardDisk; + } + } + + // Delegate methods. Since a hard disk cannot be edited, setters are not + // visible + + /** + * Returns the id of the hard disk. + */ + public Integer getId() { + // TODO: DiskManagementDto does not have an id field + return target.getEditLink() == null ? null : target.getIdFromLink("edit"); + } + + /** + * Returns the size of the hard disk in MB. + */ + public Long getSizeInMb() { + return target.getSizeInMb(); + } + + /** + * Returns the sequence number of the hard disk. + *

+ * It will be computed when attaching the hard disk to a virtual machine and + * will determine the attachment order of the disk in the virtual machine. + */ + public Integer getSequence() { + return target.getSequence(); + } + + @Override + public String toString() { + return "HardDisk [id=" + getId() + ", sizeInMb=" + getSizeInMb() + ", sequence=" + getSequence() + "]"; + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/cloud/VirtualAppliance.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/cloud/VirtualAppliance.java new file mode 100644 index 0000000000..3d52dadf31 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/cloud/VirtualAppliance.java @@ -0,0 +1,382 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.cloud; + +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.collect.Iterables.filter; + +import java.util.List; + +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.domain.DomainWrapper; +import org.jclouds.abiquo.domain.cloud.options.VirtualMachineOptions; +import org.jclouds.abiquo.domain.enterprise.Enterprise; +import org.jclouds.abiquo.domain.task.AsyncTask; +import org.jclouds.abiquo.reference.ValidationErrors; +import org.jclouds.abiquo.reference.rest.ParentLinkName; +import org.jclouds.rest.RestContext; + +import com.abiquo.model.transport.AcceptedRequestDto; +import com.abiquo.server.core.cloud.VirtualApplianceDto; +import com.abiquo.server.core.cloud.VirtualApplianceState; +import com.abiquo.server.core.cloud.VirtualApplianceStateDto; +import com.abiquo.server.core.cloud.VirtualDatacenterDto; +import com.abiquo.server.core.cloud.VirtualMachineTaskDto; +import com.abiquo.server.core.cloud.VirtualMachineWithNodeExtendedDto; +import com.abiquo.server.core.cloud.VirtualMachinesWithNodeExtendedDto; +import com.abiquo.server.core.enterprise.EnterpriseDto; +import com.google.common.base.Predicate; +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; + +/** + * Represents a virtual appliance. + *

+ * A virtual appliance is a logic container for virtual machines that together + * make an appliance. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + * @see API: + * http://community.abiquo.com/display/ABI20/Virtual+Appliance+Resource + */ +public class VirtualAppliance extends DomainWrapper { + /** The virtual datacenter where the virtual appliance belongs. */ + private VirtualDatacenter virtualDatacenter; + + /** + * Constructor to be used only by the builder. + */ + protected VirtualAppliance(final RestContext context, final VirtualApplianceDto target) { + super(context, target); + } + + // Domain operations + + /** + * Deletes the virtual appliance. + */ + public void delete() { + context.getApi().getCloudApi().deleteVirtualAppliance(target); + target = null; + } + + /** + * Creates the virtual appliance in the selected virtual datacenter. + */ + public void save() { + target = context.getApi().getCloudApi().createVirtualAppliance(virtualDatacenter.unwrap(), target); + } + + /** + * Updates the virtual appliance information when some of its properties have + * changed. + */ + public void update() { + target = context.getApi().getCloudApi().updateVirtualAppliance(target); + } + + // Parent access + + /** + * Gets the virtual datacenter where the virtual appliance belongs to. + * + * @resturn The virtual datacenter where the virtual appliance belongs to. + * @see API: http://community.abiquo.com/display/ABI20/Virtual+Datacenter+ + * Resource# VirtualDatacenterResource-RetrieveaVirtualDatacenter + */ + public VirtualDatacenter getVirtualDatacenter() { + Integer virtualDatacenterId = target.getIdFromLink(ParentLinkName.VIRTUAL_DATACENTER); + VirtualDatacenterDto dto = context.getApi().getCloudApi().getVirtualDatacenter(virtualDatacenterId); + virtualDatacenter = wrap(context, VirtualDatacenter.class, dto); + return virtualDatacenter; + } + + /** + * Gets the enterprise where the virtual appliance belongs to. + * + * @return The enterprise where the virtual appliance belongs to. + * @see API: http://community.abiquo.com/display/ABI20/Enterprise+Resource# + * EnterpriseResource- RetrieveaEnterprise + */ + public Enterprise getEnterprise() { + Integer enterpriseId = target.getIdFromLink(ParentLinkName.ENTERPRISE); + EnterpriseDto dto = context.getApi().getEnterpriseApi().getEnterprise(enterpriseId); + return wrap(context, Enterprise.class, dto); + } + + /** + * Gets the current state of the virtual appliance. + * + * @return The current state of the virtual appliance. + */ + public VirtualApplianceState getState() { + VirtualApplianceStateDto stateDto = context.getApi().getCloudApi().getVirtualApplianceState(target); + return stateDto.getPower(); + } + + // Children access + + /** + * Gets the list of virtual machines in the virtual appliance. + * + * @return The list of virtual machines in the virtual appliance. + * @see API: http://community.abiquo.com/display/ABI18/Virtual+Machine+Resource# + * VirtualMachineResource -RetrievethelistofVirtualMachines. + */ + public List listVirtualMachines() { + return listVirtualMachines(VirtualMachineOptions.builder().disablePagination().build()); + } + + /** + * Gets the list of virtual machines in the virtual appliance. + * + * @return The list of virtual machines in the virtual appliance. + * @see API: http://community.abiquo.com/display/ABI18/Virtual+Machine+Resource# + * VirtualMachineResource -RetrievethelistofVirtualMachines. + */ + public List listVirtualMachines(final VirtualMachineOptions options) { + VirtualMachinesWithNodeExtendedDto vms = context.getApi().getCloudApi().listVirtualMachines(target, options); + return wrap(context, VirtualMachine.class, vms.getCollection()); + } + + /** + * Gets the list of virtual machines in the virtual appliance matching the + * given filter. + * + * @param filter + * The filter to apply. + * @return The list of virtual machines in the virtual appliance matching the + * given filter. + */ + public List listVirtualMachines(final Predicate filter) { + return Lists.newLinkedList(filter(listVirtualMachines(), filter)); + } + + /** + * Gets a single virtual machine in the virtual appliance matching the given + * filter. + * + * @param filter + * The filter to apply. + * @return The virtual machine or null if none matched the given + * filter. + */ + public VirtualMachine findVirtualMachine(final Predicate filter) { + return Iterables.getFirst(filter(listVirtualMachines(), filter), null); + } + + /** + * Gets a concrete virtual machine in the virtual appliance. + * + * @param id + * The id of the virtual machine. + * @return The requested virtual machine. + */ + public VirtualMachine getVirtualMachine(final Integer id) { + VirtualMachineWithNodeExtendedDto vm = context.getApi().getCloudApi().getVirtualMachine(target, id); + return wrap(context, VirtualMachine.class, vm); + } + + // Actions + + /** + * Deploys the virtual appliance. + *

+ * This method will start the deployment of all the virtual machines in the + * virtual appliance, and will return an {@link AsyncTask} reference for each + * deployment operation. The deployment will finish when all individual tasks + * finish. + * + * @return The list of tasks corresponding to the deploy process of each + * virtual machine in the appliance. + */ + public AsyncTask[] deploy() { + return deploy(false); + } + + /** + * Deploys the virtual appliance. + *

+ * This method will start the deployment of all the virtual machines in the + * virtual appliance, and will return an {@link AsyncTask} reference for each + * deploy operation. The deployment will finish when all individual tasks + * finish. + * + * @param forceEnterpriseSoftLimits + * Boolean indicating if the deployment must be executed even if + * the enterprise soft limits are reached. + * @return The list of tasks corresponding to the deploy process of each + * virtual machine in the appliance. + */ + public AsyncTask[] deploy(final boolean forceEnterpriseSoftLimits) { + VirtualMachineTaskDto force = new VirtualMachineTaskDto(); + force.setForceEnterpriseSoftLimits(forceEnterpriseSoftLimits); + + AcceptedRequestDto response = context.getApi().getCloudApi().deployVirtualAppliance(unwrap(), force); + + return getTasks(response); + } + + /** + * Undeploys the virtual appliance. + *

+ * This method will start the undeploy of all the virtual machines in the + * virtual appliance, and will return an {@link AsyncTask} reference for each + * undeploy operation. The undeploy will finish when all individual tasks + * finish. + * + * @return The list of tasks corresponding to the undeploy process of each + * virtual machine in the appliance. + */ + public AsyncTask[] undeploy() { + return undeploy(false); + } + + /** + * Undeploys the virtual appliance. + *

+ * This method will start the undeploy of all the virtual machines in the + * virtual appliance, and will return an {@link AsyncTask} reference for each + * undeploy operation. The undeploy will finish when all individual tasks + * finish. + * + * @param forceUndeploy + * Boolean flag to force the undeploy even if the virtual appliance + * contains imported virtual machines. + * @return The list of tasks corresponding to the undeploy process of each + * virtual machine in the appliance. + */ + public AsyncTask[] undeploy(final boolean forceUndeploy) { + VirtualMachineTaskDto force = new VirtualMachineTaskDto(); + force.setForceUndeploy(forceUndeploy); + + AcceptedRequestDto response = context.getApi().getCloudApi().undeployVirtualAppliance(unwrap(), force); + + return getTasks(response); + } + + /** + * Returns a String message with the price info of the virtual appliance. + * + * @return The price of the virtual appliance + */ + public String getPrice() { + return context.getApi().getCloudApi().getVirtualAppliancePrice(target); + } + + // Builder + + public static Builder builder(final RestContext context, + final VirtualDatacenter virtualDatacenter) { + return new Builder(context, virtualDatacenter); + } + + public static class Builder { + private RestContext context; + + private String name; + + private VirtualDatacenter virtualDatacenter; + + public Builder(final RestContext context, final VirtualDatacenter virtualDatacenter) { + super(); + checkNotNull(virtualDatacenter, ValidationErrors.NULL_RESOURCE + VirtualDatacenter.class); + this.virtualDatacenter = virtualDatacenter; + this.context = context; + } + + public Builder name(final String name) { + this.name = name; + return this; + } + + public Builder virtualDatacenter(final VirtualDatacenter virtualDatacenter) { + checkNotNull(virtualDatacenter, ValidationErrors.NULL_RESOURCE + VirtualDatacenter.class); + this.virtualDatacenter = virtualDatacenter; + return this; + } + + public VirtualAppliance build() { + VirtualApplianceDto dto = new VirtualApplianceDto(); + dto.setName(name); + + VirtualAppliance virtualAppliance = new VirtualAppliance(context, dto); + virtualAppliance.virtualDatacenter = virtualDatacenter; + + return virtualAppliance; + } + + public static Builder fromVirtualAppliance(final VirtualAppliance in) { + return VirtualAppliance.builder(in.context, in.virtualDatacenter).name(in.getName()); + } + } + + // Delegate methods + + public int getError() { + return target.getError(); + } + + public int getHighDisponibility() { + return target.getHighDisponibility(); + } + + public Integer getId() { + return target.getId(); + } + + public String getName() { + return target.getName(); + } + + public int getPublicApp() { + return target.getPublicApp(); + } + + public void setHighDisponibility(final int highDisponibility) { + target.setHighDisponibility(highDisponibility); + } + + public void setName(final String name) { + target.setName(name); + } + + public void setPublicApp(final int publicApp) { + target.setPublicApp(publicApp); + } + + @Override + public String toString() { + return "VirtualAppliance [id=" + getId() + ", name=" + getName() + "]"; + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/cloud/VirtualDatacenter.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/cloud/VirtualDatacenter.java new file mode 100644 index 0000000000..d43a61414f --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/cloud/VirtualDatacenter.java @@ -0,0 +1,629 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.cloud; + +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.collect.Iterables.filter; + +import java.util.List; + +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.domain.DomainWithLimitsWrapper; +import org.jclouds.abiquo.domain.builder.LimitsBuilder; +import org.jclouds.abiquo.domain.cloud.options.VirtualMachineTemplateOptions; +import org.jclouds.abiquo.domain.enterprise.Enterprise; +import org.jclouds.abiquo.domain.infrastructure.Datacenter; +import org.jclouds.abiquo.domain.infrastructure.Tier; +import org.jclouds.abiquo.domain.network.ExternalNetwork; +import org.jclouds.abiquo.domain.network.Network; +import org.jclouds.abiquo.domain.network.PrivateIp; +import org.jclouds.abiquo.domain.network.PrivateNetwork; +import org.jclouds.abiquo.domain.network.PublicIp; +import org.jclouds.abiquo.domain.network.options.IpOptions; +import org.jclouds.abiquo.predicates.infrastructure.DatacenterPredicates; +import org.jclouds.abiquo.reference.ValidationErrors; +import org.jclouds.abiquo.reference.rest.ParentLinkName; +import org.jclouds.rest.RestContext; + +import com.abiquo.model.enumerator.HypervisorType; +import com.abiquo.model.enumerator.NetworkType; +import com.abiquo.model.enumerator.StatefulInclusion; +import com.abiquo.server.core.appslibrary.VirtualMachineTemplatesDto; +import com.abiquo.server.core.cloud.VirtualApplianceDto; +import com.abiquo.server.core.cloud.VirtualAppliancesDto; +import com.abiquo.server.core.cloud.VirtualDatacenterDto; +import com.abiquo.server.core.infrastructure.network.PublicIpsDto; +import com.abiquo.server.core.infrastructure.network.VLANNetworkDto; +import com.abiquo.server.core.infrastructure.network.VLANNetworksDto; +import com.abiquo.server.core.infrastructure.storage.DiskManagementDto; +import com.abiquo.server.core.infrastructure.storage.DisksManagementDto; +import com.abiquo.server.core.infrastructure.storage.TierDto; +import com.abiquo.server.core.infrastructure.storage.TiersDto; +import com.abiquo.server.core.infrastructure.storage.VolumeManagementDto; +import com.abiquo.server.core.infrastructure.storage.VolumesManagementDto; +import com.google.common.base.Predicate; +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; + +/** + * Represents a virtual datacenter. + *

+ * Virtual datacenters expose a set of compute, storage and networking resources + * that can be consumed by the tenants. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + * @see API: + * http + * ://community.abiquo.com/display/ABI20/Virtual+Datacenter+Resource + */ +public class VirtualDatacenter extends DomainWithLimitsWrapper { + /** The enterprise where the rack belongs. */ + private Enterprise enterprise; + + /** The dataceter where the virtual datacenter will be deployed. */ + private Datacenter datacenter; + + /** + * Constructor to be used only by the builder. + */ + protected VirtualDatacenter(final RestContext context, final VirtualDatacenterDto target) { + super(context, target); + } + + // Domain operations + + /** + * Delete the virtual datacenter. + * + * @see API: http://community.abiquo.com/display/ABI20/Virtual+Datacenter+ + * Resource# + * VirtualDatacenterResource-DeleteanexistingVirtualDatacenter + */ + public void delete() { + context.getApi().getCloudApi().deleteVirtualDatacenter(target); + target = null; + } + + /** + * Creates the virtual datacenter. + * + * @see API: http://community.abiquo.com/display/ABI20/Virtual+Datacenter+ + * Resource# VirtualDatacenterResource-CreateanewVirtualDatacenter + */ + public void save() { + target = context.getApi().getCloudApi().createVirtualDatacenter(target, datacenter.unwrap(), enterprise.unwrap()); + } + + /** + * Updates the virtual datacenter information when some of its properties + * have changed. + * + * @see API: http://community.abiquo.com/display/ABI20/Virtual+Datacenter+ + * Resource# + * VirtualDatacenterResource-UpdatesanexistingVirtualDatacenter + */ + public void update() { + target = context.getApi().getCloudApi().updateVirtualDatacenter(target); + } + + // Parent access + + /** + * Gets the datacenter where this virtual datacenter is assigned. + * + * @return The datacenter where this virtual datacenter is assigned. + * @see API: http://community.abiquo.com/display/ABI20/Datacenter+Resource# + * DatacenterResource- RetrieveaDatacenter + */ + public Datacenter getDatacenter() { + Integer datacenterId = target.getIdFromLink(ParentLinkName.DATACENTER); + datacenter = getEnterprise().findAllowedDatacenter(DatacenterPredicates.id(datacenterId)); + return datacenter; + } + + /** + * Gets the enterprise that owns this virtual datacenter. + * + * @return The enterprise that owns this virtual datacenter. + * @see API: http://community.abiquo.com/display/ABI20/Enterprise+Resource# + * EnterpriseResource- RetrieveanEnterprise + */ + public Enterprise getEnterprise() { + Integer enterpriseId = target.getIdFromLink(ParentLinkName.ENTERPRISE); + enterprise = wrap(context, Enterprise.class, context.getApi().getEnterpriseApi().getEnterprise(enterpriseId)); + return enterprise; + } + + // Children access + + /** + * Lists all the virtual appliances in the virtual datacenter. + * + * @return The list of virtual appliances in the virtual datacenter. + * @see API: http://community.abiquo.com/display/ABI20/Virtual+Appliance+Resource + * # VirtualApplianceResource-RetrievethelistofVirtualAppliances + */ + public List listVirtualAppliances() { + VirtualAppliancesDto vapps = context.getApi().getCloudApi().listVirtualAppliances(target); + return wrap(context, VirtualAppliance.class, vapps.getCollection()); + } + + /** + * Lists all the virtual appliances in the virtual datacenter that match the + * given filter. + * + * @param filter + * The filter to apply. + * @return The list of virtual appliances in the virtual datacenter that + * match the given filter. + * @see API: http://community.abiquo.com/display/ABI20/Virtual+Appliance+Resource + * # VirtualApplianceResource-RetrievethelistofVirtualAppliances + */ + public List listVirtualAppliances(final Predicate filter) { + return Lists.newLinkedList(filter(listVirtualAppliances(), filter)); + } + + /** + * Gets the first virtual appliance in the virtual datacenter that match the + * given filter. + * + * @param filter + * The filter to apply. + * @return the first virtual appliance in the virtual datacenter that match + * the given filter or null if none is found. + * @see API: http://community.abiquo.com/display/ABI20/Virtual+Appliance+Resource + * # VirtualApplianceResource-RetrievethelistofVirtualAppliances + */ + public VirtualAppliance findVirtualAppliance(final Predicate filter) { + return Iterables.getFirst(filter(listVirtualAppliances(), filter), null); + } + + /** + * Gets the virtual appliance with the given id in the current virtual + * datacenter. + * + * @param id + * The id of the virtual appliance to get. + * @return The virtual appliance. + */ + public VirtualAppliance getVirtualAppliance(final Integer id) { + VirtualApplianceDto vapp = context.getApi().getCloudApi().getVirtualAppliance(target, id); + return wrap(context, VirtualAppliance.class, vapp); + } + + /** + * Lists the storage tiers that are available to the virtual datacenter. + * + * @return The list of storage tiers that are available to the virtual + * datacenter. + * @see API: http://community.abiquo.com/display/ABI20/Virtual+Datacenter+ + * Resource# VirtualDatacenterResource-Retrieveenabledtiers + */ + public List listStorageTiers() { + TiersDto tiers = context.getApi().getCloudApi().listStorageTiers(target); + return wrap(context, Tier.class, tiers.getCollection()); + } + + /** + * Lists the storage tiers that are available to the virtual datacenter and + * match the given filter. + * + * @param filter + * The filter to apply. + * @return The list of storage tiers that are available to the virtual + * datacenter and match the given filter. + * @see API: http://community.abiquo.com/display/ABI20/Virtual+Datacenter+ + * Resource# VirtualDatacenterResource-Retrieveenabledtiers + */ + public List listStorageTiers(final Predicate filter) { + return Lists.newLinkedList(filter(listStorageTiers(), filter)); + } + + /** + * Finds the first the storage tier that is available to the virtual + * datacenter and matches the given filter. + * + * @param filter + * The filter to apply. + * @return The first the storage tier that is available to the virtual + * datacenter and matches the given filter. + * @see API: http://community.abiquo.com/display/ABI20/Virtual+Datacenter+ + * Resource# VirtualDatacenterResource-Retrieveenabledtiers + */ + public Tier findStorageTier(final Predicate filter) { + return Iterables.getFirst(filter(listStorageTiers(), filter), null); + } + + /** + * Gets the storage tier with the given id from the current virtual + * datacenter. + * + * @param id + * The id of the storage tier. + * @return The sotrage tier. + */ + public Tier getStorageTier(final Integer id) { + TierDto tier = context.getApi().getCloudApi().getStorageTier(target, id); + return wrap(context, Tier.class, tier); + } + + /** + * Lists all persistent volumes in the virtual datacenter. + * + * @return The list of all persistent volumes in the virtual datacenter. + * @see API: http://community.abiquo.com/display/ABI20/Volume+Resource# + * VolumeResource- Retrievethelistofvolumes + */ + public List listVolumes() { + VolumesManagementDto volumes = context.getApi().getCloudApi().listVolumes(target); + return wrap(context, Volume.class, volumes.getCollection()); + } + + /** + * Lists all persistent volumes in the virtual datacenter that match the + * given filter. + * + * @param filter + * The filter to apply. + * @return The list of all persistent volumes in the virtual datacenter that + * match the given filter. + * @see API: http://community.abiquo.com/display/ABI20/Volume+Resource# + * VolumeResource- Retrievethelistofvolumes + */ + public List listVolumes(final Predicate filter) { + return Lists.newLinkedList(filter(listVolumes(), filter)); + } + + /** + * Finds the first persistent volume in the virtual datacenter that matches + * the given filter. + * + * @param filter + * The filter to apply. + * @return The first persistent volumes in the virtual datacenter that + * matches the given filter. + * @see API: http://community.abiquo.com/display/ABI20/Volume+Resource# + * VolumeResource- Retrievethelistofvolumes + */ + public Volume findVolume(final Predicate filter) { + return Iterables.getFirst(filter(listVolumes(), filter), null); + } + + public Volume getVolume(final Integer id) { + VolumeManagementDto volume = context.getApi().getCloudApi().getVolume(target, id); + return wrap(context, Volume.class, volume); + } + + /** + * @see API: http://community.abiquo.com/display/ABI20/Hard+Disks+Resource# + * HardDisksResource- GetthelistofHardDisksofaVirtualDatacenter + */ + public List listHardDisks() { + DisksManagementDto hardDisks = context.getApi().getCloudApi().listHardDisks(target); + return wrap(context, HardDisk.class, hardDisks.getCollection()); + } + + public List listHardDisks(final Predicate filter) { + return Lists.newLinkedList(filter(listHardDisks(), filter)); + } + + public HardDisk findHardDisk(final Predicate filter) { + return Iterables.getFirst(filter(listHardDisks(), filter), null); + } + + public HardDisk getHardDisk(final Integer id) { + DiskManagementDto hardDisk = context.getApi().getCloudApi().getHardDisk(target, id); + return wrap(context, HardDisk.class, hardDisk); + } + + /** + * @see API: http://community.abiquo.com/display/ABI20/Virtual+Datacenter+ + * Resource# + * VirtualDatacenterResource-GetdefaultVLANusedbydefaultinVirtualDatacenter + * + */ + public Network getDefaultNetwork() { + VLANNetworkDto network = context.getApi().getCloudApi().getDefaultNetwork(target); + return wrap(context, network.getType() == NetworkType.INTERNAL ? PrivateNetwork.class : ExternalNetwork.class, + network); + } + + /** + * @see API: http://community.abiquo.com/display/ABI20/Private+Network+Resource# + * PrivateNetworkResource -RetrievealistofPrivateNetworks + */ + public List listPrivateNetworks() { + VLANNetworksDto networks = context.getApi().getCloudApi().listPrivateNetworks(target); + return wrap(context, PrivateNetwork.class, networks.getCollection()); + } + + public List listPrivateNetworks(final Predicate> filter) { + return Lists.newLinkedList(filter(listPrivateNetworks(), filter)); + } + + public PrivateNetwork findPrivateNetwork(final Predicate> filter) { + return Iterables.getFirst(filter(listPrivateNetworks(), filter), null); + } + + public PrivateNetwork getPrivateNetwork(final Integer id) { + VLANNetworkDto network = context.getApi().getCloudApi().getPrivateNetwork(target, id); + return wrap(context, PrivateNetwork.class, network); + } + + /** + * TODO needs to be in the wiki + */ + public List listAvailableTemplates() { + VirtualMachineTemplatesDto templates = context.getApi().getCloudApi().listAvailableTemplates(target); + + return wrap(context, VirtualMachineTemplate.class, templates.getCollection()); + } + + public List listAvailableTemplates(final VirtualMachineTemplateOptions options) { + VirtualMachineTemplatesDto templates = context.getApi().getCloudApi().listAvailableTemplates(target, options); + + return wrap(context, VirtualMachineTemplate.class, templates.getCollection()); + } + + public List listAvailableTemplates(final Predicate filter) { + return Lists.newLinkedList(filter(listAvailableTemplates(), filter)); + } + + public VirtualMachineTemplate findAvailableTemplate(final Predicate filter) { + return Iterables.getFirst(filter(listAvailableTemplates(), filter), null); + } + + public VirtualMachineTemplate getAvailableTemplate(final Integer id) { + VirtualMachineTemplatesDto templates = context.getApi().getCloudApi() + .listAvailableTemplates(target, VirtualMachineTemplateOptions.builder().idTemplate(id).build()); + + return templates.getCollection().isEmpty() ? null : // + wrap(context, VirtualMachineTemplate.class, templates.getCollection().get(0)); + } + + public VirtualMachineTemplate getAvailablePersistentTemplate(final Integer id) { + VirtualMachineTemplatesDto templates = context + .getApi() + .getCloudApi() + .listAvailableTemplates(target, + VirtualMachineTemplateOptions.builder().idTemplate(id).persistent(StatefulInclusion.ALL).build()); + + return templates.getCollection().isEmpty() ? null : // + wrap(context, VirtualMachineTemplate.class, templates.getCollection().get(0)); + } + + /** + * @see API: http://community.abiquo.com/display/ABI20/Virtual+Datacenter+ + * Resource# + * VirtualDatacenterResource-ListofPublicIPstopurchasebyVirtualDatacenter + * + */ + public List listAvailablePublicIps() { + IpOptions options = IpOptions.builder().build(); + + PublicIpsDto ips = context.getApi().getCloudApi().listAvailablePublicIps(target, options); + + return wrap(context, PublicIp.class, ips.getCollection()); + } + + public List listAvailablePublicIps(final Predicate filter) { + return Lists.newLinkedList(filter(listAvailablePublicIps(), filter)); + } + + public PublicIp findAvailablePublicIp(final Predicate filter) { + return Iterables.getFirst(filter(listAvailablePublicIps(), filter), null); + } + + /** + * @see API: http://community.abiquo.com/display/ABI20/Virtual+Datacenter+ + * Resource# + * VirtualDatacenterResource-ListofpurchasedPublicIPsbyVirtualDatacenter + * + */ + public List listPurchasedPublicIps() { + IpOptions options = IpOptions.builder().build(); + + PublicIpsDto ips = context.getApi().getCloudApi().listPurchasedPublicIps(target, options); + + return wrap(context, PublicIp.class, ips.getCollection()); + } + + public List listPurchasedPublicIps(final Predicate filter) { + return Lists.newLinkedList(filter(listPurchasedPublicIps(), filter)); + } + + public PublicIp findPurchasedPublicIp(final Predicate filter) { + return Iterables.getFirst(filter(listPurchasedPublicIps(), filter), null); + } + + public void purchasePublicIp(final PublicIp ip) { + checkNotNull(ip.unwrap().searchLink("purchase"), ValidationErrors.MISSING_REQUIRED_LINK); + context.getApi().getCloudApi().purchasePublicIp(ip.unwrap()); + } + + public void releaseePublicIp(final PublicIp ip) { + checkNotNull(ip.unwrap().searchLink("release"), ValidationErrors.MISSING_REQUIRED_LINK); + context.getApi().getCloudApi().releasePublicIp(ip.unwrap()); + } + + // Actions + + public void setDefaultNetwork(final Network network) { + context.getApi().getCloudApi().setDefaultNetwork(target, network.unwrap()); + } + + // Builder + + public static Builder builder(final RestContext context, final Datacenter datacenter, + final Enterprise enterprise) { + return new Builder(context, datacenter, enterprise); + } + + public static class Builder extends LimitsBuilder { + private RestContext context; + + private String name; + + private HypervisorType hypervisorType; + + private Enterprise enterprise; + + private Datacenter datacenter; + + private PrivateNetwork network; + + public Builder(final RestContext context, final Datacenter datacenter, + final Enterprise enterprise) { + super(); + checkNotNull(datacenter, ValidationErrors.NULL_RESOURCE + Datacenter.class); + this.datacenter = datacenter; + checkNotNull(enterprise, ValidationErrors.NULL_RESOURCE + Enterprise.class); + this.enterprise = enterprise; + this.context = context; + } + + public Builder name(final String name) { + this.name = name; + return this; + } + + public Builder hypervisorType(final HypervisorType hypervisorType) { + this.hypervisorType = hypervisorType; + return this; + } + + public Builder datacenter(final Datacenter datacenter) { + checkNotNull(datacenter, ValidationErrors.NULL_RESOURCE + Datacenter.class); + this.datacenter = datacenter; + return this; + } + + public Builder enterprise(final Enterprise enterprise) { + checkNotNull(enterprise, ValidationErrors.NULL_RESOURCE + Enterprise.class); + this.enterprise = enterprise; + return this; + } + + public Builder network(final PrivateNetwork network) { + checkNotNull(network, ValidationErrors.NULL_RESOURCE + PrivateNetwork.class); + this.network = network; + return this; + } + + public VirtualDatacenter build() { + VirtualDatacenterDto dto = new VirtualDatacenterDto(); + dto.setName(name); + dto.setRamLimitsInMb(ramSoftLimitInMb, ramHardLimitInMb); + dto.setCpuCountLimits(cpuCountSoftLimit, cpuCountHardLimit); + dto.setHdLimitsInMb(hdSoftLimitInMb, hdHardLimitInMb); + dto.setStorageLimits(storageSoft, storageHard); + dto.setVlansLimits(vlansSoft, vlansHard); + dto.setPublicIPLimits(publicIpsSoft, publicIpsHard); + dto.setName(name); + dto.setHypervisorType(hypervisorType); + dto.setVlan(network.unwrap()); + + VirtualDatacenter virtualDatacenter = new VirtualDatacenter(context, dto); + virtualDatacenter.datacenter = datacenter; + virtualDatacenter.enterprise = enterprise; + + return virtualDatacenter; + } + + public static Builder fromVirtualDatacenter(final VirtualDatacenter in) { + return VirtualDatacenter.builder(in.context, in.datacenter, in.enterprise).name(in.getName()) + .ramLimits(in.getRamSoftLimitInMb(), in.getRamHardLimitInMb()) + .cpuCountLimits(in.getCpuCountSoftLimit(), in.getCpuCountHardLimit()) + .hdLimitsInMb(in.getHdSoftLimitInMb(), in.getHdHardLimitInMb()) + .storageLimits(in.getStorageSoft(), in.getStorageHard()) + .vlansLimits(in.getVlansSoft(), in.getVlansHard()) + .publicIpsLimits(in.getPublicIpsSoft(), in.getPublicIpsHard()).hypervisorType(in.getHypervisorType()); + } + } + + // Delegate methods + + public HypervisorType getHypervisorType() { + return target.getHypervisorType(); + } + + public Integer getId() { + return target.getId(); + } + + public String getName() { + return target.getName(); + } + + public void setHypervisorType(final HypervisorType hypervisorType) { + target.setHypervisorType(hypervisorType); + } + + public void setName(final String name) { + target.setName(name); + } + + @Override + public String toString() { + return "VirtualDatacenter [id=" + getId() + ", type=" + getHypervisorType() + ", name=" + getName() + "]"; + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/cloud/VirtualMachine.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/cloud/VirtualMachine.java new file mode 100644 index 0000000000..b29bc4da57 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/cloud/VirtualMachine.java @@ -0,0 +1,910 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.cloud; + +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.collect.Iterables.filter; + +import java.util.Arrays; +import java.util.List; + +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.domain.DomainWithTasksWrapper; +import org.jclouds.abiquo.domain.cloud.options.VirtualMachineOptions; +import org.jclouds.abiquo.domain.enterprise.Enterprise; +import org.jclouds.abiquo.domain.network.Ip; +import org.jclouds.abiquo.domain.network.Network; +import org.jclouds.abiquo.domain.network.UnmanagedNetwork; +import org.jclouds.abiquo.domain.task.AsyncTask; +import org.jclouds.abiquo.domain.util.LinkUtils; +import org.jclouds.abiquo.features.services.MonitoringService; +import org.jclouds.abiquo.monitor.VirtualMachineMonitor; +import org.jclouds.abiquo.predicates.LinkPredicates; +import org.jclouds.abiquo.reference.ValidationErrors; +import org.jclouds.abiquo.reference.rest.ParentLinkName; +import org.jclouds.abiquo.rest.internal.ExtendedUtils; +import org.jclouds.abiquo.strategy.cloud.ListAttachedNics; +import org.jclouds.http.HttpResponse; +import org.jclouds.http.functions.ParseXMLWithJAXB; +import org.jclouds.rest.RestContext; + +import com.abiquo.model.rest.RESTLink; +import com.abiquo.model.transport.AcceptedRequestDto; +import com.abiquo.server.core.appslibrary.VirtualMachineTemplateDto; +import com.abiquo.server.core.cloud.VirtualApplianceDto; +import com.abiquo.server.core.cloud.VirtualDatacenterDto; +import com.abiquo.server.core.cloud.VirtualMachineState; +import com.abiquo.server.core.cloud.VirtualMachineStateDto; +import com.abiquo.server.core.cloud.VirtualMachineTaskDto; +import com.abiquo.server.core.cloud.VirtualMachineWithNodeExtendedDto; +import com.abiquo.server.core.enterprise.EnterpriseDto; +import com.abiquo.server.core.infrastructure.network.UnmanagedIpDto; +import com.abiquo.server.core.infrastructure.network.VMNetworkConfigurationDto; +import com.abiquo.server.core.infrastructure.network.VMNetworkConfigurationsDto; +import com.abiquo.server.core.infrastructure.storage.DiskManagementDto; +import com.abiquo.server.core.infrastructure.storage.DisksManagementDto; +import com.abiquo.server.core.infrastructure.storage.DvdManagementDto; +import com.abiquo.server.core.infrastructure.storage.VolumeManagementDto; +import com.abiquo.server.core.infrastructure.storage.VolumesManagementDto; +import com.google.common.base.Function; +import com.google.common.base.Predicate; +import com.google.common.base.Predicates; +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; +import com.google.inject.TypeLiteral; + +/** + * Adds high level functionality to {@link VirtualMachineWithNodeExtendedDto}. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + * @see API: + * http://community.abiquo.com/display/ABI20/VirtualMachineResource + */ +public class VirtualMachine extends DomainWithTasksWrapper { + /** The virtual appliance where the virtual machine belongs. */ + private VirtualAppliance virtualAppliance; + + /** The virtual machine template of the virtual machine. */ + private VirtualMachineTemplate template; + + /** + * Constructor to be used only by the builder. + */ + protected VirtualMachine(final RestContext context, + final VirtualMachineWithNodeExtendedDto target) { + super(context, target); + } + + // Domain operations + + /** + * Delete the virtual machine. + * + * @see API: http://community.abiquo.com/display/ABI20/VirtualMachineResource# + * VirtualMachineResource -Deleteavirtualmachine + */ + public void delete() { + context.getApi().getCloudApi().deleteVirtualMachine(target); + target = null; + } + + /** + * Create a new virtual machine in Abiquo. + * + * @see API: http://community.abiquo.com/display/ABI20/VirtualMachineResource# + * VirtualMachineResource-Createavirtualmachine + */ + public void save() { + checkNotNull(template, ValidationErrors.NULL_RESOURCE + VirtualMachineTemplate.class); + checkNotNull(template.getId(), ValidationErrors.MISSING_REQUIRED_FIELD + " id in " + VirtualMachineTemplate.class); + + this.updateLink(target, ParentLinkName.VIRTUAL_MACHINE_TEMPLATE, template.unwrap(), "edit"); + + target = context.getApi().getCloudApi().createVirtualMachine(virtualAppliance.unwrap(), target); + } + + /** + * Update virtual machine information in the server with the data from this + * virtual machine. This is an asynchronous call. This method returns a + * {@link org.jclouds.abiquo.domain.task.AsyncTask} object that keeps track + * of the task completion. Please refer to the documentation for details. + * + * @see API: http://community.abiquo.com/display/ABI20/VirtualMachineResource# + * VirtualMachineResource-Modifyavirtualmachine + * @see github: https://github.com/abiquo/jclouds-abiquo/wiki/Asynchronous-monitor- + * example + * @return The task reference or null if the operation completed + * synchronously. + */ + public AsyncTask update() { + AcceptedRequestDto taskRef = context.getApi().getCloudApi().updateVirtualMachine(target); + return taskRef == null ? null : getTask(taskRef); + } + + /** + * Update virtual machine information in the server with the data from this + * virtual machine. This is an asynchronous call. This method returns a + * {@link org.jclouds.abiquo.domain.task.AsyncTask} object that keeps track + * of the task completion. Please refer to the documentation for details. + * + * @param force + * Force update. + * @see API: http://community.abiquo.com/display/ABI20/VirtualMachineResource# + * VirtualMachineResource-Modifyavirtualmachine + * @see github: https://github.com/abiquo/jclouds-abiquo/wiki/Asynchronous-monitor- + * example + * @return The task reference or null if the operation completed + * synchronously. + */ + public AsyncTask update(final boolean force) { + AcceptedRequestDto taskRef = context.getApi().getCloudApi() + .updateVirtualMachine(target, VirtualMachineOptions.builder().force(force).build()); + return taskRef == null ? null : getTask(taskRef); + } + + /** + * Change the state of the virtual machine. This is an asynchronous call. + * This method returns a {@link org.jclouds.abiquo.domain.task.AsyncTask} + * object that keeps track of the task completion. Please refer to the + * documentation for details. + * + * @param state + * The new state of the virtual machine. + * @see API: http://community.abiquo.com/display/ABI20/VirtualMachineResource# + * VirtualMachineResource-Changethestateofavirtualmachine + * @see github: https://github.com/abiquo/jclouds-abiquo/wiki/Asynchronous-monitor- + * example + * @return The task reference or null if the operation completed + * synchronously. + */ + public AsyncTask changeState(final VirtualMachineState state) { + VirtualMachineStateDto dto = new VirtualMachineStateDto(); + dto.setState(state); + + AcceptedRequestDto taskRef = context.getApi().getCloudApi().changeVirtualMachineState(target, dto); + + return getTask(taskRef); + } + + /** + * Retrieve the state of the virtual machine. + * + * @see API: http://community.abiquo.com/display/ABI20/VirtualMachineResource# + * VirtualMachineResource-Retrievethestateofthevirtualmachine + * @return Current state of the virtual machine. + */ + public VirtualMachineState getState() { + VirtualMachineStateDto stateDto = context.getApi().getCloudApi().getVirtualMachineState(target); + VirtualMachineState state = stateDto.getState(); + target.setState(state); + target.setIdState(state.id()); + return state; + } + + public void refresh() { + RESTLink link = checkNotNull(target.getEditLink(), ValidationErrors.MISSING_REQUIRED_LINK + " edit"); + + ExtendedUtils utils = (ExtendedUtils) context.getUtils(); + HttpResponse response = utils.getAbiquoHttpClient().get(link); + + ParseXMLWithJAXB parser = new ParseXMLWithJAXB( + utils.getXml(), TypeLiteral.get(VirtualMachineWithNodeExtendedDto.class)); + + target = parser.apply(response); + } + + // Parent access + + /** + * Retrieve the virtual appliance where this virtual machine is. + * + * @see API: http://community.abiquo.com/display/ABI20/VirtualApplianceResource# + * VirtualApplianceResource-Retrieveavirtualappliance + * @return The virtual appliance where this virtual machine is. + */ + public VirtualAppliance getVirtualAppliance() { + RESTLink link = checkNotNull(target.searchLink(ParentLinkName.VIRTUAL_APPLIANCE), + ValidationErrors.MISSING_REQUIRED_LINK + " " + ParentLinkName.VIRTUAL_APPLIANCE); + + ExtendedUtils utils = (ExtendedUtils) context.getUtils(); + HttpResponse response = utils.getAbiquoHttpClient().get(link); + + ParseXMLWithJAXB parser = new ParseXMLWithJAXB(utils.getXml(), + TypeLiteral.get(VirtualApplianceDto.class)); + + return wrap(context, VirtualAppliance.class, parser.apply(response)); + } + + /** + * Retrieve the virtual datacenter where this virtual machine is. + * + * @see API: http://community.abiquo.com/display/ABI20/VirtualDatacenterResource + * # VirtualDatacenterResource-Retireveavirtualdatacenter + * @return The virtual datacenter where this virtual machine is. + */ + public VirtualDatacenter getVirtualDatacenter() { + Integer virtualDatacenterId = target.getIdFromLink(ParentLinkName.VIRTUAL_DATACENTER); + VirtualDatacenterDto dto = context.getApi().getCloudApi().getVirtualDatacenter(virtualDatacenterId); + return wrap(context, VirtualDatacenter.class, dto); + } + + /** + * Retrieve the enterprise of this virtual machine. + * + * @see API: http://community.abiquo.com/display/ABI20/EnterpriseResource# + * EnterpriseResource- RetrieveanEnterprise + * @return Enterprise of this virtual machine. + */ + public Enterprise getEnterprise() { + Integer enterpriseId = target.getIdFromLink(ParentLinkName.ENTERPRISE); + EnterpriseDto dto = context.getApi().getEnterpriseApi().getEnterprise(enterpriseId); + return wrap(context, Enterprise.class, dto); + } + + /** + * Retrieve the template of this virtual machine. + * + * @return Template of this virtual machine. + */ + public VirtualMachineTemplate getTemplate() { + VirtualMachineTemplateDto dto = context.getApi().getCloudApi().getVirtualMachineTemplate(target); + return wrap(context, VirtualMachineTemplate.class, dto); + } + + // Children access + + public List listAttachedHardDisks() { + refresh(); + DisksManagementDto hardDisks = context.getApi().getCloudApi().listAttachedHardDisks(target); + return wrap(context, HardDisk.class, hardDisks.getCollection()); + } + + public List listAttachedHardDisks(final Predicate filter) { + return Lists.newLinkedList(filter(listAttachedHardDisks(), filter)); + } + + public HardDisk findAttachedHardDisk(final Predicate filter) { + return Iterables.getFirst(filter(listAttachedHardDisks(), filter), null); + } + + public List listAttachedVolumes() { + refresh(); + VolumesManagementDto volumes = context.getApi().getCloudApi().listAttachedVolumes(target); + return wrap(context, Volume.class, volumes.getCollection()); + } + + public List listAttachedVolumes(final Predicate filter) { + return Lists.newLinkedList(filter(listAttachedVolumes(), filter)); + } + + public Volume findAttachedVolume(final Predicate filter) { + return Iterables.getFirst(filter(listAttachedVolumes(), filter), null); + } + + public List> listAttachedNics() { + // The strategy will refresh the vm. There is no need to do it here + ListAttachedNics strategy = context.getUtils().getInjector().getInstance(ListAttachedNics.class); + return Lists.newLinkedList(strategy.execute(this)); + } + + public List> listAttachedNics(final Predicate> filter) { + return Lists.newLinkedList(filter(listAttachedNics(), filter)); + } + + public Ip findAttachedNic(final Predicate> filter) { + return Iterables.getFirst(filter(listAttachedNics(), filter), null); + } + + // Actions + + public AsyncTask deploy() { + return deploy(false); + } + + public AsyncTask deploy(final boolean forceEnterpriseSoftLimits) { + VirtualMachineTaskDto force = new VirtualMachineTaskDto(); + force.setForceEnterpriseSoftLimits(forceEnterpriseSoftLimits); + + AcceptedRequestDto response = context.getApi().getCloudApi().deployVirtualMachine(unwrap(), force); + + return getTask(response); + } + + public AsyncTask undeploy() { + return undeploy(false); + } + + public AsyncTask undeploy(final boolean forceUndeploy) { + VirtualMachineTaskDto force = new VirtualMachineTaskDto(); + force.setForceUndeploy(forceUndeploy); + + AcceptedRequestDto response = context.getApi().getCloudApi().undeployVirtualMachine(unwrap(), force); + + return getTask(response); + } + + /** + * Reboot a virtual machine. This is an asynchronous call. This method + * returns a {@link org.jclouds.abiquo.domain.task.AsyncTask} object that + * keeps track of the task completion. Please refer to the documentation for + * details. + * + * @see API: http://community.abiquo.com/display/ABI20/Rack+Resource#/ + * VirtualMachineResource# + * VirtualMachineResource-Resetavirtualmachine + * @see github: https://github.com/abiquo/jclouds-abiquo/wiki/Asynchronous-monitor- + * example + * @return The task reference or null if the operation completed + * synchronously. + */ + public AsyncTask reboot() { + AcceptedRequestDto response = context.getApi().getCloudApi().rebootVirtualMachine(unwrap()); + + return getTask(response); + } + + public AsyncTask attachHardDisks(final HardDisk... hardDisks) { + List expected = listAttachedHardDisks(); + expected.addAll(Arrays.asList(hardDisks)); + + HardDisk[] disks = new HardDisk[expected.size()]; + return setHardDisks(expected.toArray(disks)); + } + + public AsyncTask detachAllHardDisks() { + AcceptedRequestDto taskRef = context.getApi().getCloudApi().detachAllHardDisks(target); + return taskRef == null ? null : getTask(taskRef); + } + + public AsyncTask detachHardDisks(final HardDisk... hardDisks) { + List expected = listAttachedHardDisks(); + Iterables.removeIf(expected, hardDiskIdIn(hardDisks)); + + HardDisk[] disks = new HardDisk[expected.size()]; + return setHardDisks(expected.toArray(disks)); + } + + public AsyncTask setHardDisks(final HardDisk... hardDisks) { + AcceptedRequestDto taskRef = context.getApi().getCloudApi() + .replaceHardDisks(target, toHardDiskDto(hardDisks)); + return taskRef == null ? null : getTask(taskRef); + } + + public AsyncTask attachVolumes(final Volume... volumes) { + List expected = listAttachedVolumes(); + expected.addAll(Arrays.asList(volumes)); + + Volume[] vols = new Volume[expected.size()]; + return setVolumes(true, expected.toArray(vols)); + } + + public AsyncTask detachAllVolumes() { + AcceptedRequestDto taskRef = context.getApi().getCloudApi().detachAllVolumes(target); + return taskRef == null ? null : getTask(taskRef); + } + + public AsyncTask detachVolumes(final Volume... volumes) { + List expected = listAttachedVolumes(); + Iterables.removeIf(expected, volumeIdIn(volumes)); + + Volume[] vols = new Volume[expected.size()]; + return setVolumes(true, expected.toArray(vols)); + } + + public AsyncTask setVolumes(final Boolean forceSoftLimits, final Volume... volumes) { + AcceptedRequestDto taskRef = context + .getApi() + .getCloudApi() + .replaceVolumes(target, VirtualMachineOptions.builder().force(forceSoftLimits).build(), + toVolumeDto(volumes)); + + return taskRef == null ? null : getTask(taskRef); + } + + public AsyncTask setVolumes(final Volume... volumes) { + return setVolumes(true, volumes); + } + + public AsyncTask setNics(final List> ips) { + // By default the network of the first ip will be used as a gateway + return setNics(ips != null && !ips.isEmpty() ? ips.get(0).getNetwork() : null, ips, null); + } + + public AsyncTask setNics(final List> ips, final List unmanagetNetworks) { + // By default the network of the first ip will be used as a gateway + Network gateway = null; + if (ips != null && !ips.isEmpty()) { + gateway = ips.get(0).getNetwork(); + } else if (unmanagetNetworks != null && !unmanagetNetworks.isEmpty()) { + gateway = unmanagetNetworks.get(0); + } + + return setNics(gateway, ips, unmanagetNetworks); + } + + public AsyncTask setNics(final Network gatewayNetwork, final List> ips) { + return setNics(gatewayNetwork, ips, null); + } + + public AsyncTask setNics(final Network gatewayNetwork, final List> ips, + final List unmanagetNetworks) { + // Remove the gateway configuration and the current nics + Iterables.removeIf(target.getLinks(), + Predicates.or(LinkPredicates.isNic(), LinkPredicates.rel(ParentLinkName.NETWORK_GATEWAY))); + + // Add the given nics in the appropriate order + int i = 0; + if (ips != null) { + for (i = 0; i < ips.size(); i++) { + RESTLink source = LinkUtils.getSelfLink(ips.get(i).unwrap()); + RESTLink link = new RESTLink("nic" + i, source.getHref()); + link.setType(ips.get(i).unwrap().getBaseMediaType()); + target.addLink(link); + } + } + + // Add unmanaged network references, if given + if (unmanagetNetworks != null) { + for (UnmanagedNetwork unmanaged : unmanagetNetworks) { + RESTLink source = checkNotNull(unmanaged.unwrap().searchLink("ips"), ValidationErrors.MISSING_REQUIRED_LINK + + "ips"); + + RESTLink link = new RESTLink("nic" + i, source.getHref()); + link.setType(UnmanagedIpDto.BASE_MEDIA_TYPE); + target.addLink(link); + i++; + } + } + + AsyncTask task = update(true); + if (gatewayNetwork == null) { + return task; + } + + // If there is a gateway network, we have to wait until the network + // configuration links are + // available + if (task != null) { + VirtualMachineState originalState = target.getState(); + VirtualMachineMonitor monitor = context.getUtils().getInjector().getInstance(MonitoringService.class) + .getVirtualMachineMonitor(); + monitor.awaitState(originalState, this); + } + + // Set the new network configuration + + // Refresh virtual machine, to get the new configuration links + refresh(); + + VMNetworkConfigurationsDto configs = context.getApi().getCloudApi().listNetworkConfigurations(target); + + Iterables.removeIf(target.getLinks(), LinkPredicates.rel(ParentLinkName.NETWORK_GATEWAY)); + for (VMNetworkConfigurationDto config : configs.getCollection()) { + if (config.getGateway().equalsIgnoreCase(gatewayNetwork.getGateway())) { + target.addLink(new RESTLink(ParentLinkName.NETWORK_GATEWAY, config.getEditLink().getHref())); + break; + } + } + + return update(true); + } + + // TODO: Get current gateway network + + public void setGatewayNetwork(final Network network) { + context.getApi().getCloudApi().setGatewayNetwork(target, network.unwrap()); + refresh(); // First refresh the target and its links + } + + /** + * Checks if the virtual machine is persistent. + *

+ * Persistent virtual machines have the system disc in an external volume. + * This way, when the virtual machine is undeployed, the contents of the + * system disk remain in the storage device and the user can deploy the + * virtual machine again without losing the data in the system disk. + * + * @return Boolean indicating if the virtual machine is persistent. + */ + public boolean isPersistent() { + return getTemplate().unwrap().searchLink("volume") != null; + } + + public boolean hasDvd() { + return target.getDvd() != null; + } + + public void attachDvd() { + DvdManagementDto dvd = new DvdManagementDto(); + RESTLink link = new RESTLink("image", ""); + dvd.addLink(link); + target.setDvd(dvd); + } + + public void detachDvd() { + target.setDvd(null); + } + + // Builder + + public static Builder builder(final RestContext context, + final VirtualAppliance virtualAppliance, final VirtualMachineTemplate template) { + return new Builder(context, virtualAppliance, template); + } + + public static class Builder { + private final RestContext context; + + private VirtualAppliance virtualAppliance; + + private final VirtualMachineTemplate template; + + private String nameLabel; + + private String internalName; + + private String description; + + private Integer ram; + + private Integer cpu; + + private Integer vncPort; + + private String vncAddress; + + private Integer idState; + + private Integer idType; + + private String password; + + private String keymap; + + private String uuid; + + private boolean dvd; + + public Builder(final RestContext context, final VirtualAppliance virtualAppliance, + final VirtualMachineTemplate template) { + super(); + checkNotNull(virtualAppliance, ValidationErrors.NULL_RESOURCE + VirtualAppliance.class); + this.virtualAppliance = virtualAppliance; + this.template = template; + this.context = context; + } + + public Builder nameLabel(final String nameLabel) { + this.nameLabel = nameLabel; + return this; + } + + public Builder description(final String description) { + this.description = description; + return this; + } + + public Builder ram(final int ram) { + this.ram = ram; + return this; + } + + public Builder cpu(final int cpu) { + this.cpu = cpu; + return this; + } + + public Builder password(final String password) { + this.password = password; + return this; + } + + public Builder keymap(final String keymap) { + this.keymap = keymap; + return this; + } + + public Builder dvd(final boolean dvd) { + this.dvd = dvd; + return this; + } + + // This methods are used only to build a builder from an existing + // VirtualMachine but should + // never be used by the user. This fields are set automatically by Abiquo + + private Builder vncPort(final int vdrpPort) { + this.vncPort = vdrpPort; + return this; + } + + private Builder vncAddress(final String vdrpIP) { + this.vncAddress = vdrpIP; + return this; + } + + private Builder idState(final int idState) { + this.idState = idState; + return this; + } + + private Builder idType(final int idType) { + this.idType = idType; + return this; + } + + private Builder internalName(final String internalName) { + this.internalName = internalName; + return this; + } + + public Builder virtualAppliance(final VirtualAppliance virtualAppliance) { + checkNotNull(virtualAppliance, ValidationErrors.NULL_RESOURCE + VirtualAppliance.class); + this.virtualAppliance = virtualAppliance; + return this; + } + + public VirtualMachine build() { + VirtualMachineWithNodeExtendedDto dto = new VirtualMachineWithNodeExtendedDto(); + dto.setNodeName(nameLabel); + dto.setDescription(description); + dto.setHdInBytes(template.getHdRequired()); + dto.setVdrpIP(vncAddress); + + if (cpu != null) { + dto.setCpu(cpu); + } + + if (ram != null) { + dto.setRam(ram); + } + + if (vncPort != null) { + dto.setVdrpPort(vncPort); + } + + if (idState != null) { + dto.setIdState(idState); + } + + if (idType != null) { + dto.setIdType(idType); + } + + if (internalName != null) { + dto.setName(internalName); + } + + dto.setPassword(password); + dto.setKeymap(keymap); + dto.setUuid(uuid); + + // DVD + if (dvd) { + DvdManagementDto dvd = new DvdManagementDto(); + RESTLink link = new RESTLink("image", ""); + dvd.addLink(link); + dto.setDvd(dvd); + } + + VirtualMachine virtualMachine = new VirtualMachine(context, dto); + virtualMachine.virtualAppliance = virtualAppliance; + virtualMachine.template = template; + + return virtualMachine; + } + + public static Builder fromVirtualMachine(final VirtualMachine in) { + return VirtualMachine.builder(in.context, in.virtualAppliance, in.template).internalName(in.getInternalName()) + .nameLabel(in.getNameLabel()).description(in.getDescription()).ram(in.getRam()).cpu(in.getCpu()) + .vncAddress(in.getVncAddress()).vncPort(in.getVncPort()).idState(in.getIdState()).idType(in.getIdType()) + .password(in.getPassword()).keymap(in.getKeymap()).dvd(in.hasDvd()); + } + } + + // Delegate methods + + public int getCpu() { + return target.getCpu(); + } + + public String getDescription() { + return target.getDescription(); + } + + // Read-only field. This value is computed from the size of the Template + public long getHdInBytes() { + return target.getHdInBytes(); + } + + public Integer getId() { + return target.getId(); + } + + public int getIdState() { + return target.getIdState(); + } + + public int getIdType() { + return target.getIdType(); + } + + public String getNameLabel() { + return target.getNodeName(); + } + + public String getOwnerName() { + return target.getUserName() + " " + target.getUserSurname(); + } + + public String getInternalName() { + return target.getName(); + } + + public String getPassword() { + return target.getPassword(); + } + + public int getRam() { + return target.getRam(); + } + + public String getUuid() { + return target.getUuid(); + } + + public String getVncAddress() { + return target.getVdrpIP(); + } + + public int getVncPort() { + return target.getVdrpPort(); + } + + public String getKeymap() { + return target.getKeymap(); + } + + public void setCpu(final int cpu) { + target.setCpu(cpu); + } + + public void setDescription(final String description) { + target.setDescription(description); + } + + public void setNameLabel(final String nameLabel) { + target.setNodeName(nameLabel); + } + + public void setPassword(final String password) { + target.setPassword(password); + } + + public void setRam(final int ram) { + target.setRam(ram); + } + + public void setKeymap(final String keymap) { + target.setKeymap(keymap); + } + + private static VolumeManagementDto[] toVolumeDto(final Volume... volumes) { + checkNotNull(volumes, "must provide at least one volume"); + + VolumeManagementDto[] dtos = new VolumeManagementDto[volumes.length]; + for (int i = 0; i < volumes.length; i++) { + dtos[i] = volumes[i].unwrap(); + } + + return dtos; + } + + private static DiskManagementDto[] toHardDiskDto(final HardDisk... hardDisks) { + checkNotNull(hardDisks, "must provide at least one hard disk"); + + DiskManagementDto[] dtos = new DiskManagementDto[hardDisks.length]; + for (int i = 0; i < hardDisks.length; i++) { + dtos[i] = hardDisks[i].unwrap(); + } + + return dtos; + } + + private static Predicate volumeIdIn(final Volume... volumes) { + return new Predicate() { + List ids = volumeIds(Arrays.asList(volumes)); + + @Override + public boolean apply(final Volume input) { + return ids.contains(input.getId()); + } + }; + } + + private static Predicate hardDiskIdIn(final HardDisk... hardDisks) { + return new Predicate() { + List ids = hardDisksIds(Arrays.asList(hardDisks)); + + @Override + public boolean apply(final HardDisk input) { + return ids.contains(input.getId()); + } + }; + } + + private static List volumeIds(final List volumes) { + return Lists.transform(volumes, new Function() { + @Override + public Integer apply(final Volume input) { + return input.getId(); + } + }); + } + + private static List hardDisksIds(final List HardDisk) { + return Lists.transform(HardDisk, new Function() { + @Override + public Integer apply(final HardDisk input) { + return input.getId(); + } + }); + } + + @Override + public String toString() { + return "VirtualMachine [id=" + getId() + ", state=" + target.getState().name() + ", cpu=" + getCpu() + + ", description=" + getDescription() + ", hdInBytes=" + getHdInBytes() + ", idType=" + getIdType() + + ", nameLabel=" + getNameLabel() + ", internalName=" + getInternalName() + ", password=" + getPassword() + + ", ram=" + getRam() + ", uuid=" + getUuid() + ", vncAddress=" + getVncAddress() + ", vncPort=" + + getVncPort() + ", keymap=" + getKeymap() + ", dvd=" + hasDvd() + "]"; + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/cloud/VirtualMachineTemplate.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/cloud/VirtualMachineTemplate.java new file mode 100644 index 0000000000..4f0f4832d9 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/cloud/VirtualMachineTemplate.java @@ -0,0 +1,380 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.cloud; + +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.collect.Iterables.filter; + +import java.util.Date; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.domain.DomainWrapper; +import org.jclouds.abiquo.domain.cloud.options.ConversionOptions; +import org.jclouds.abiquo.domain.config.Category; +import org.jclouds.abiquo.domain.config.CostCode; +import org.jclouds.abiquo.domain.enterprise.Enterprise; +import org.jclouds.abiquo.domain.infrastructure.Datacenter; +import org.jclouds.abiquo.domain.infrastructure.Tier; +import org.jclouds.abiquo.domain.task.AsyncTask; +import org.jclouds.abiquo.reference.rest.ParentLinkName; +import org.jclouds.abiquo.rest.internal.ExtendedUtils; +import org.jclouds.http.HttpResponse; +import org.jclouds.http.functions.ParseXMLWithJAXB; +import org.jclouds.rest.RestContext; + +import com.abiquo.model.enumerator.ConversionState; +import com.abiquo.model.enumerator.DiskFormatType; +import com.abiquo.model.enumerator.HypervisorType; +import com.abiquo.model.rest.RESTLink; +import com.abiquo.model.transport.AcceptedRequestDto; +import com.abiquo.server.core.appslibrary.CategoryDto; +import com.abiquo.server.core.appslibrary.ConversionDto; +import com.abiquo.server.core.appslibrary.ConversionsDto; +import com.abiquo.server.core.appslibrary.VirtualMachineTemplateDto; +import com.abiquo.server.core.appslibrary.VirtualMachineTemplatePersistentDto; +import com.abiquo.server.core.infrastructure.storage.VolumeManagementDto; +import com.abiquo.server.core.pricing.CostCodeDto; +import com.google.common.base.Predicate; +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; +import com.google.inject.TypeLiteral; + +/** + * Adds high level functionality to {@link VirtualMachineTemplateDto}. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + * @see API: + * http://community.abiquo.com/display/ABI20/Virtual+Machine+Template+Resource + * + */ +public class VirtualMachineTemplate extends DomainWrapper { + /** + * Constructor to be used only by the builder. + */ + protected VirtualMachineTemplate(final RestContext context, + final VirtualMachineTemplateDto target) { + super(context, target); + } + + // Domain operations + + public void delete() { + context.getApi().getVirtualMachineTemplateApi().deleteVirtualMachineTemplate(target); + target = null; + } + + public void update() { + target = context.getApi().getVirtualMachineTemplateApi().updateVirtualMachineTemplate(target); + } + + /** + * TODO + * + * @param vdc + * @param volume + * @param persistentTemplateName + * @param persistentVolumeName + * @return + */ + public AsyncTask makePersistent(final VirtualDatacenter vdc, final Volume volume, final String persistentTemplateName) { + RESTLink storageLink = volume.unwrap().getEditLink(); + storageLink.setRel("volume"); + return makePeristent(vdc, storageLink, persistentTemplateName, null); + } + + public AsyncTask makePersistent(final VirtualDatacenter vdc, final Tier tier, final String persistentTemplateName, + final String persistentVolumeName) { + // infrastructure + RESTLink storageLink = tier.unwrap().getEditLink(); + if (storageLink == null) { + // cloud + storageLink = tier.unwrap().searchLink("self"); + } + storageLink.setRel(ParentLinkName.TIER); + return makePeristent(vdc, storageLink, persistentTemplateName, persistentVolumeName); + } + + private AsyncTask makePeristent(final VirtualDatacenter vdc, final RESTLink storageLink, + final String persistentTemplateName, final String persistentVolumeName) { + VirtualMachineTemplatePersistentDto persistentData = new VirtualMachineTemplatePersistentDto(); + persistentData.setPersistentTemplateName(persistentTemplateName); + persistentData.setPersistentVolumeName(persistentVolumeName); + RESTLink vdcLink = new RESTLink(ParentLinkName.VIRTUAL_DATACENTER, vdc.unwrap().getEditLink().getHref()); + RESTLink templateLink = new RESTLink(ParentLinkName.VIRTUAL_MACHINE_TEMPLATE, target.getEditLink().getHref()); + + persistentData.addLink(vdcLink); + persistentData.addLink(storageLink); + persistentData.addLink(templateLink); + + // SCG: + // A simple user should not have permissions to obtain a datacenter + // repository, but at this + // point we have the datacenter repository and enterprise ids in the own + // target uri. So we + // can obtain the path where do the POST + // Assumption that to create a new object a user needs to get the parent + // object cannot be + // applied in this case + String editUri = getURI().getPath(); + Pattern p = Pattern.compile("\\d+"); + Matcher m = p.matcher(editUri); + m.find(); + Integer idEnt = new Integer(m.group()); + m.find(); + Integer idDcRepo = new Integer(m.group()); + + AcceptedRequestDto response = context.getApi().getVirtualMachineTemplateApi() + .createPersistentVirtualMachineTemplate(idEnt, idDcRepo, persistentData); + + return getTask(response); + } + + // Children access + + /** + * @see API: http://community.abiquo.com/display/ABI20/Category+Resource# + * CategoryResource- Retrieveacategory + */ + public Category getCategory() { + Integer categoryId = target.getIdFromLink(ParentLinkName.CATEGORY); + CategoryDto category = context.getApi().getConfigApi().getCategory(categoryId); + return wrap(context, Category.class, category); + } + + /** + * @see API: http://community.abiquo.com/display/Abiquo/Volume+Resource# + * VolumeResource- Retrieveavolume + */ + public Volume getVolume() { + if (this.isPersistent()) { + ExtendedUtils utils = (ExtendedUtils) context.getUtils(); + HttpResponse rp = checkNotNull(utils.getAbiquoHttpClient().get(target.searchLink("volume")), "volume"); + + ParseXMLWithJAXB parser = new ParseXMLWithJAXB(utils.getXml(), + TypeLiteral.get(VolumeManagementDto.class)); + + VolumeManagementDto dto = parser.apply(rp); + return new Volume(context, dto); + } + return null; + } + + public boolean isPersistent() { + return target.searchLink("volume") != null; + } + + // Parent access + + /** + * @see API: http://community.abiquo.com/display/ABI20/Enterprise+Resource# + * EnterpriseResource- RetrieveanEnterprise + */ + public Enterprise getEnterprise() { + Integer enterpriseId = target.getIdFromLink(ParentLinkName.ENTERPRISE); + return wrap(context, Enterprise.class, context.getApi().getEnterpriseApi().getEnterprise(enterpriseId)); + } + + /** + * @see API: http://community.abiquo.com/display/ABI20/Datacenter+Resource# + * DatacenterResource- RetrieveaDatacenter + */ + public Datacenter getDatacenter() { + Integer repositoryId = target.getIdFromLink(ParentLinkName.DATACENTER_REPOSITORY); + return wrap(context, Datacenter.class, context.getApi().getInfrastructureApi().getDatacenter(repositoryId)); + } + + /** + * List all the conversions for the virtual machine template. + * + * @see API: http://community.abiquo.com/display/ABI20/Conversion+Resource# + * ConversionResource- ListConversions + * @return all the conversions of the virtual machine template + */ + public List listConversions() { + ConversionsDto convs = context.getApi().getVirtualMachineTemplateApi().listConversions(target); + return wrap(context, Conversion.class, convs.getCollection()); + } + + /** + * List all the conversions for the virtual machine template matching the + * given filter. + * + * @param filter + * The filter to apply. + * @return The list all the conversions for the virtual machine template + * matching the given filter. + */ + public List listConversions(final Predicate filter) { + return Lists.newLinkedList(filter(listConversions(), filter)); + } + + /** + * Gets a single conversion in the virtual machine template matching the + * given filter. + * + * @param filter + * The filter to apply. + * @return The conversion or null if none matched the given + * filter. + */ + public Conversion findConversion(final Predicate filter) { + return Iterables.getFirst(filter(listConversions(), filter), null); + } + + /** + * List conversions for a virtual machine template. + * + * @see API: http://community.abiquo.com/display/ABI20/Conversion+Resource# + * ConversionResource- ListConversions + * @param hypervisor + * , Optionally filter conversions compatible with the provided + * hypervisor + * @param state + * , Optionally filter conversions with the desired state + * @return all the conversions of the virtual machine template applying the + * constrains + */ + public List listConversions(final HypervisorType hypervisor, final ConversionState state) { + ConversionsDto convs = context + .getApi() + .getVirtualMachineTemplateApi() + .listConversions(target, + ConversionOptions.builder().hypervisorType(hypervisor).conversionState(state).build()); + return wrap(context, Conversion.class, convs.getCollection()); + } + + /** + * Starts a new conversion for a virtual machine template. + * + * @see API: http://community.abiquo.com/display/ABI20/Conversion+Resource# + * ConversionResource- RequestConversion + * @param diskFormat + * , desired target format for the request template + * @return The task reference to track its progress + */ + public AsyncTask requestConversion(final DiskFormatType diskFormat) { + ConversionDto request = new ConversionDto(); + request.setTargetFormat(diskFormat); + + AcceptedRequestDto taskRef = context.getApi().getVirtualMachineTemplateApi() + .requestConversion(target, diskFormat, request); + + return taskRef == null ? null : getTask(taskRef); + } + + public CostCode getCostCode() { + Integer costcodeId = target.getIdFromLink(ParentLinkName.COST_CODE); + CostCodeDto costcode = context.getApi().getPricingApi().getCostCode(costcodeId); + return wrap(context, CostCode.class, costcode); + } + + // Delegate methods + + public int getCpuRequired() { + return target.getCpuRequired(); + } + + public Date getCreationDate() { + return target.getCreationDate(); + } + + public String getCreationUser() { + return target.getCreationUser(); + } + + public String getDescription() { + return target.getDescription(); + } + + public long getDiskFileSize() { + return target.getDiskFileSize(); + } + + public DiskFormatType getDiskFormatType() { + return DiskFormatType.valueOf(target.getDiskFormatType()); + } + + public long getHdRequired() { + return target.getHdRequired(); + } + + public String getName() { + return target.getName(); + } + + public String getPath() { + return target.getPath(); + } + + public int getRamRequired() { + return target.getRamRequired(); + } + + public boolean isChefEnabled() { + return target.isChefEnabled(); + } + + public void setChefEnabled(final boolean chefEnabled) { + target.setChefEnabled(chefEnabled); + } + + public void setName(final String name) { + target.setName(name); + } + + public Integer getId() { + return target.getId(); + } + + public String getIconUrl() { + return target.getIconUrl(); + } + + @Override + public String toString() { + return "VirtualMachineTemplate [id=" + getId() + ", cpuRequired=" + getCpuRequired() + ", creationDate=" + + getCreationDate() + ", creationUser=" + getCreationUser() + ", description=" + getDescription() + + ", diskFileSize=" + getDiskFileSize() + ", diskFormatType=" + getDiskFormatType() + ", hdRequired=" + + getHdRequired() + ", name=" + getName() + ", path=" + getPath() + ", ramRequired=" + getRamRequired() + + ", chefEnabled=" + isChefEnabled() + "]"; + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/cloud/VirtualMachineTemplateInVirtualDatacenter.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/cloud/VirtualMachineTemplateInVirtualDatacenter.java new file mode 100644 index 0000000000..e5bb53053c --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/cloud/VirtualMachineTemplateInVirtualDatacenter.java @@ -0,0 +1,48 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.abiquo.domain.cloud; + +import static com.google.common.base.Preconditions.checkNotNull; + +/** + * Wrapper to hold the information of a virtual machine template scoped to a + * concrete hypervisor type. + * + * @author Ignasi Barrera + */ +public class VirtualMachineTemplateInVirtualDatacenter { + private VirtualMachineTemplate template; + + private VirtualDatacenter zone; + + public VirtualMachineTemplateInVirtualDatacenter(final VirtualMachineTemplate template, final VirtualDatacenter zone) { + super(); + this.template = checkNotNull(template, "template"); + this.zone = checkNotNull(zone, "zone"); + } + + public VirtualMachineTemplate getTemplate() { + return template; + } + + public VirtualDatacenter getZone() { + return zone; + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/cloud/Volume.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/cloud/Volume.java new file mode 100644 index 0000000000..9315d37feb --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/cloud/Volume.java @@ -0,0 +1,224 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.cloud; + +import static com.google.common.base.Preconditions.checkNotNull; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.domain.DomainWrapper; +import org.jclouds.abiquo.domain.infrastructure.Tier; +import org.jclouds.abiquo.domain.task.AsyncTask; +import org.jclouds.abiquo.reference.ValidationErrors; +import org.jclouds.abiquo.reference.annotations.EnterpriseEdition; +import org.jclouds.abiquo.reference.rest.ParentLinkName; +import org.jclouds.rest.RestContext; + +import com.abiquo.model.enumerator.VolumeState; +import com.abiquo.model.rest.RESTLink; +import com.abiquo.model.transport.AcceptedRequestDto; +import com.abiquo.server.core.cloud.VirtualDatacenterDto; +import com.abiquo.server.core.infrastructure.storage.TierDto; +import com.abiquo.server.core.infrastructure.storage.VolumeManagementDto; + +/** + * Adds high level functionality to {@link VolumeManagementDto}. + * + * @author Ignasi Barrera + * @see API: + * http://community.abiquo.com/display/ABI20/Volume+Resource + */ +@EnterpriseEdition +public class Volume extends DomainWrapper { + /** The default state for folumes. */ + public static final VolumeState DEFAULT_STATE = VolumeState.DETACHED; + + /** The virtual datacenter where the volume belongs. */ + private VirtualDatacenter virtualDatacenter; + + /** The tier where the volume belongs. */ + private Tier tier; + + /** + * Constructor to be used only by the builder. + */ + protected Volume(final RestContext context, final VolumeManagementDto target) { + super(context, target); + } + + // Domain operations + + public void delete() { + context.getApi().getCloudApi().deleteVolume(target); + target = null; + } + + public void save() { + target = context.getApi().getCloudApi().createVolume(virtualDatacenter.unwrap(), target); + } + + public AsyncTask update() { + AcceptedRequestDto taskRef = context.getApi().getCloudApi().updateVolume(target); + return taskRef == null ? null : getTask(taskRef); + } + + // Parent access + + /** + * @see API: http://community.abiquo.com/display/ABI20/Virtual+Datacenter+ + * Resource# VirtualDatacenterResource-RetrieveaVirtualDatacenter + */ + public VirtualDatacenter getVirtualDatacenter() { + Integer virtualDatacenterId = target.getIdFromLink(ParentLinkName.VIRTUAL_DATACENTER); + VirtualDatacenterDto dto = context.getApi().getCloudApi().getVirtualDatacenter(virtualDatacenterId); + virtualDatacenter = wrap(context, VirtualDatacenter.class, dto); + return virtualDatacenter; + } + + /** + * TODO javadoc link + */ + public Tier getTier() { + Integer tierId = target.getIdFromLink(ParentLinkName.TIER); + TierDto dto = context.getApi().getCloudApi().getStorageTier(virtualDatacenter.unwrap(), tierId); + tier = wrap(context, Tier.class, dto); + return tier; + } + + // Actions + + /** + * Move the volume to the given virtual datacenter. + * + * @param newVirtualDatacenter + * The destination virtual datacenter. + */ + public void moveTo(final VirtualDatacenter newVirtualDatacenter) { + target = context.getApi().getCloudApi().moveVolume(unwrap(), newVirtualDatacenter.unwrap()); + } + + // Builder + + public static Builder builder(final RestContext context, + final VirtualDatacenter virtualDatacenter, final Tier tier) { + return new Builder(context, virtualDatacenter, tier); + } + + public static class Builder { + private RestContext context; + + private String name; + + private String description; + + private Long sizeInMb; + + private VirtualDatacenter virtualDatacenter; + + private Tier tier; + + public Builder(final RestContext context, final VirtualDatacenter virtualDatacenter, + final Tier tier) { + super(); + checkNotNull(virtualDatacenter, ValidationErrors.NULL_RESOURCE + VirtualDatacenter.class); + checkNotNull(tier, ValidationErrors.NULL_RESOURCE + Tier.class); + this.context = context; + this.virtualDatacenter = virtualDatacenter; + this.tier = tier; + } + + public Builder name(final String name) { + this.name = name; + return this; + } + + public Builder description(final String description) { + this.description = description; + return this; + } + + public Builder sizeInMb(final long sizeInMb) { + this.sizeInMb = sizeInMb; + return this; + } + + public Volume build() { + VolumeManagementDto dto = new VolumeManagementDto(); + dto.setName(name); + dto.setDescription(description); + dto.setSizeInMB(sizeInMb); + dto.setState(DEFAULT_STATE.name()); + + RESTLink link = tier.unwrap().searchLink("self"); + checkNotNull(link, ValidationErrors.MISSING_REQUIRED_LINK); + dto.addLink(new RESTLink("tier", link.getHref())); + + Volume volume = new Volume(context, dto); + volume.virtualDatacenter = virtualDatacenter; + volume.tier = tier; + + return volume; + } + } + + // Delegate methods + + public Integer getId() { + return target.getId(); + } + + public String getState() { + return target.getState(); + } + + public String getName() { + return target.getName(); + } + + public void setName(final String name) { + target.setName(name); + } + + public long getSizeInMB() { + return target.getSizeInMB(); + } + + public void setSizeInMB(final long sizeInMB) { + target.setSizeInMB(sizeInMB); + } + + public String getDescription() { + return target.getDescription(); + } + + public void setDescription(final String description) { + target.setDescription(description); + } + + @Override + public String toString() { + return "Volume [id=" + getId() + ", state=" + getState() + ", name=" + getName() + ", sizeInMB=" + getSizeInMB() + + ", description=" + getDescription() + "]"; + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/cloud/options/ConversionOptions.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/cloud/options/ConversionOptions.java new file mode 100644 index 0000000000..e074f9e4b9 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/cloud/options/ConversionOptions.java @@ -0,0 +1,73 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.cloud.options; + +import org.jclouds.http.options.BaseHttpRequestOptions; + +import com.abiquo.model.enumerator.ConversionState; +import com.abiquo.model.enumerator.HypervisorType; + +/** + * Available options to filter virtual machine template conversions + */ +public class ConversionOptions extends BaseHttpRequestOptions { + + public static Builder builder() { + return new Builder(); + } + + @Override + protected Object clone() throws CloneNotSupportedException { + ConversionOptions options = new ConversionOptions(); + options.queryParameters.putAll(queryParameters); + return options; + } + + public static class Builder { + private HypervisorType hypervisorType; + + private ConversionState conversionState; + + /** Only conversions compatible with this hypervisor */ + public Builder hypervisorType(final HypervisorType hypervisorType) { + this.hypervisorType = hypervisorType; + return this; + } + + /** Only conversions with the provided state */ + public Builder conversionState(final ConversionState conversionState) { + this.conversionState = conversionState; + return this; + } + + public ConversionOptions build() { + ConversionOptions options = new ConversionOptions(); + + if (hypervisorType != null) { + options.queryParameters.put("hypervisor", hypervisorType.name()); + } + if (conversionState != null) { + options.queryParameters.put("state", conversionState.name()); + } + + return options; + } + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/cloud/options/VirtualApplianceOptions.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/cloud/options/VirtualApplianceOptions.java new file mode 100644 index 0000000000..3fdf07a646 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/cloud/options/VirtualApplianceOptions.java @@ -0,0 +1,61 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.cloud.options; + +import org.jclouds.http.options.BaseHttpRequestOptions; + +/** + * Available options to query virtual appliances. + * + * @author Francesc Montserrat + * @author Ignasi Barrera + */ +public class VirtualApplianceOptions extends BaseHttpRequestOptions { + public static Builder builder() { + return new Builder(); + } + + @Override + protected Object clone() throws CloneNotSupportedException { + VirtualApplianceOptions options = new VirtualApplianceOptions(); + options.queryParameters.putAll(queryParameters); + return options; + } + + public static class Builder { + + private Boolean available; + + public Builder available(final boolean available) { + this.available = available; + return this; + } + + public VirtualApplianceOptions build() { + VirtualApplianceOptions options = new VirtualApplianceOptions(); + + if (available != null) { + options.queryParameters.put("available", String.valueOf(available)); + } + + return options; + } + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/cloud/options/VirtualDatacenterOptions.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/cloud/options/VirtualDatacenterOptions.java new file mode 100644 index 0000000000..27bea5d092 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/cloud/options/VirtualDatacenterOptions.java @@ -0,0 +1,75 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.cloud.options; + +import org.jclouds.http.options.BaseHttpRequestOptions; + +/** + * Available options to query virtual datacenters. + * + * @author Francesc Montserrat + */ +public class VirtualDatacenterOptions extends BaseHttpRequestOptions { + public static Builder builder() { + return new Builder(); + } + + @Override + protected Object clone() throws CloneNotSupportedException { + VirtualDatacenterOptions options = new VirtualDatacenterOptions(); + options.queryParameters.putAll(queryParameters); + return options; + } + + public static class Builder { + private Integer datacenterId; + + private Integer enterpriseId; + + /** + * Set the optional datacenter. + */ + public Builder datacenterId(final int datacenterId) { + this.datacenterId = datacenterId; + return this; + } + + /** + * Set the optional enterprise. + */ + public Builder enterpriseId(final int enterpriseId) { + this.enterpriseId = enterpriseId; + return this; + } + + public VirtualDatacenterOptions build() { + VirtualDatacenterOptions options = new VirtualDatacenterOptions(); + + if (datacenterId != null) { + options.queryParameters.put("datacenter", datacenterId.toString()); + } + + if (enterpriseId != null) { + options.queryParameters.put("enterprise", enterpriseId.toString()); + } + return options; + } + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/cloud/options/VirtualMachineOptions.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/cloud/options/VirtualMachineOptions.java new file mode 100644 index 0000000000..e78c02baac --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/cloud/options/VirtualMachineOptions.java @@ -0,0 +1,60 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.cloud.options; + +import org.jclouds.abiquo.domain.options.search.FilterOptions.BaseFilterOptionsBuilder; +import org.jclouds.http.options.BaseHttpRequestOptions; + +/** + * Available options to query virtual machine. + * + * @author Alessia Prete + */ +public class VirtualMachineOptions extends BaseHttpRequestOptions { + public static Builder builder() { + return new Builder(); + } + + @Override + protected Object clone() throws CloneNotSupportedException { + VirtualMachineOptions options = new VirtualMachineOptions(); + options.queryParameters.putAll(queryParameters); + return options; + } + + public static class Builder extends BaseFilterOptionsBuilder { + private Boolean force; + + public Builder force(final Boolean force) { + this.force = force; + return this; + } + + public VirtualMachineOptions build() { + VirtualMachineOptions options = new VirtualMachineOptions(); + + if (force != null) { + options.queryParameters.put("force", String.valueOf(force)); + } + + return addFilterOptions(options); + } + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/cloud/options/VirtualMachineTemplateOptions.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/cloud/options/VirtualMachineTemplateOptions.java new file mode 100644 index 0000000000..7f587187d9 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/cloud/options/VirtualMachineTemplateOptions.java @@ -0,0 +1,105 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.cloud.options; + +import org.jclouds.abiquo.domain.config.Category; +import org.jclouds.http.options.BaseHttpRequestOptions; + +import com.abiquo.model.enumerator.HypervisorType; +import com.abiquo.model.enumerator.StatefulInclusion; + +/** + * Available options to query virtual machine templates. + * + * @author Ignasi Barrera + */ +public class VirtualMachineTemplateOptions extends BaseHttpRequestOptions { + public static Builder builder() { + return new Builder(); + } + + @Override + protected Object clone() throws CloneNotSupportedException { + VirtualMachineTemplateOptions options = new VirtualMachineTemplateOptions(); + options.queryParameters.putAll(queryParameters); + return options; + } + + public static class Builder { + private StatefulInclusion persistent; + + private HypervisorType hypervisorType; + + private Category category; + + private String categoryName; + + private Integer idTemplate; + + public Builder persistent(final StatefulInclusion persistent) { + this.persistent = persistent; + return this; + } + + public Builder hypervisorType(final HypervisorType hypervisorType) { + this.hypervisorType = hypervisorType; + return this; + } + + public Builder category(final Category category) { + this.category = category; + return this; + } + + public Builder categoryName(final String categoryName) { + this.categoryName = categoryName; + return this; + } + + public Builder idTemplate(final Integer idTemplate) { + this.idTemplate = idTemplate; + return this; + } + + public VirtualMachineTemplateOptions build() { + VirtualMachineTemplateOptions options = new VirtualMachineTemplateOptions(); + + if (persistent != null) { + options.queryParameters.put("stateful", persistent.name()); + } + if (hypervisorType != null) { + options.queryParameters.put("hypervisorTypeName", hypervisorType.name()); + } + if (category != null) { + options.queryParameters.put("categoryName", category.getName()); + } + + if (category == null && categoryName != null) { + options.queryParameters.put("categoryName", categoryName); + } + + if (idTemplate != null) { + options.queryParameters.put("idTemplate", String.valueOf(idTemplate)); + } + + return options; + } + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/cloud/options/VolumeOptions.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/cloud/options/VolumeOptions.java new file mode 100644 index 0000000000..9048da61bf --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/cloud/options/VolumeOptions.java @@ -0,0 +1,62 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.cloud.options; + +import org.jclouds.abiquo.domain.options.search.FilterOptions.BaseFilterOptionsBuilder; +import org.jclouds.abiquo.reference.annotations.EnterpriseEdition; +import org.jclouds.http.options.BaseHttpRequestOptions; + +/** + * Available options to query volumes. + * + * @author Ignasi Barrera + */ +@EnterpriseEdition +public class VolumeOptions extends BaseHttpRequestOptions { + public static Builder builder() { + return new Builder(); + } + + @Override + protected Object clone() throws CloneNotSupportedException { + VolumeOptions options = new VolumeOptions(); + options.queryParameters.putAll(queryParameters); + return options; + } + + public static class Builder extends BaseFilterOptionsBuilder { + private Boolean onlyAvailable; + + public Builder onlyAvailable(final boolean onlyAvailable) { + this.onlyAvailable = onlyAvailable; + return this; + } + + public VolumeOptions build() { + VolumeOptions options = new VolumeOptions(); + + if (onlyAvailable != null) { + options.queryParameters.put("available", String.valueOf(onlyAvailable)); + } + + return addFilterOptions(options); + } + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/config/Category.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/config/Category.java new file mode 100644 index 0000000000..f0206d67d3 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/config/Category.java @@ -0,0 +1,169 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.config; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.domain.DomainWrapper; +import org.jclouds.rest.RestContext; + +import com.abiquo.server.core.appslibrary.CategoryDto; + +/** + * Adds high level functionality to {@link CategoryDto}. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + * @see API: + * http://community.abiquo.com/display/ABI20/Category+Resource + */ + +public class Category extends DomainWrapper { + /** The default value for the default category flag. */ + private static final boolean DEFAULT_DEFAULT_CATEGORY = false; + + /** The default value for the erasable flag. */ + private static final boolean DEFAULT_ERASABLE = true; + + /** + * Constructor to be used only by the builder. This resource cannot be + * created. + */ + private Category(final RestContext context, final CategoryDto target) { + super(context, target); + } + + // Domain operations + + /** + * @see API: http://community.abiquo.com/display/ABI20/Category+Resource# + * CategoryResource-Deleteacategory + */ + public void delete() { + context.getApi().getConfigApi().deleteCategory(target); + target = null; + } + + /** + * @see API: http://community.abiquo.com/display/ABI20/Category+Resource# + * CategoryResource-Createacategory + */ + public void save() { + target = context.getApi().getConfigApi().createCategory(target); + } + + /** + * @see API: http://community.abiquo.com/display/ABI20/Category+Resource# + * CategoryResource-Updateanexistingcategory + */ + public void update() { + target = context.getApi().getConfigApi().updateCategory(target); + } + + // Builder + + public static Builder builder(final RestContext context) { + return new Builder(context); + } + + public static class Builder { + private RestContext context; + + private String name; + + private Boolean erasable = DEFAULT_ERASABLE; + + private Boolean defaultCategory = DEFAULT_DEFAULT_CATEGORY; + + public Builder(final RestContext context) { + super(); + this.context = context; + } + + public Builder name(final String name) { + this.name = name; + return this; + } + + public Builder defaultCategory(final boolean defaultCategory) { + this.defaultCategory = defaultCategory; + return this; + } + + public Builder erasable(final boolean erasable) { + this.erasable = erasable; + return this; + } + + public Category build() { + CategoryDto dto = new CategoryDto(); + dto.setErasable(erasable); + dto.setDefaultCategory(defaultCategory); + dto.setName(name); + Category category = new Category(context, dto); + + return category; + } + + public static Builder fromCategory(final Category in) { + Builder builder = Category.builder(in.context).name(in.getName()).erasable(in.isErasable()) + .defaultCategory(in.isDefaultCategory()); + + return builder; + } + } + + // Delegate methods + + public Integer getId() { + return target.getId(); + } + + public String getName() { + return target.getName(); + } + + public boolean isDefaultCategory() { + return target.isDefaultCategory(); + } + + public boolean isErasable() { + return target.isErasable(); + } + + public void setDefaultCategory(final boolean defaultCategory) { + target.setDefaultCategory(defaultCategory); + } + + public void setErasable(final boolean erasable) { + target.setErasable(erasable); + } + + public void setName(final String name) { + target.setName(name); + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/config/CostCode.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/config/CostCode.java new file mode 100644 index 0000000000..2963a7d83e --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/config/CostCode.java @@ -0,0 +1,174 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.config; + +import java.util.List; + +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.domain.DomainWrapper; +import org.jclouds.abiquo.domain.cloud.VirtualMachineTemplate; +import org.jclouds.rest.RestContext; + +import com.abiquo.model.rest.RESTLink; +import com.abiquo.server.core.pricing.CostCodeCurrenciesDto; +import com.abiquo.server.core.pricing.CostCodeCurrencyDto; +import com.abiquo.server.core.pricing.CostCodeDto; +import com.google.common.collect.Lists; + +/** + * A cost code is a kind of label where concrete prices can be assigned. + *

+ * Cloud administrators can create several cost codes and assign a price to each + * one, to have a flexible way to configure custom billings for each resource. + *

+ * Cost codes can be assigned to {@link VirtualMachineTemplate}s and other + * resources to provide pricing information about them. + * + * @author Ignasi Barrera + * @author Susana Acedo + */ +public class CostCode extends DomainWrapper { + + private List defaultPrices; + + /** + * Constructor to be used only by the builder. This resource cannot be + * created. + */ + private CostCode(final RestContext context, final CostCodeDto target) { + super(context, target); + } + + // Domain operations + + public void delete() { + context.getApi().getPricingApi().deleteCostCode(target); + target = null; + } + + public void save() { + target = context.getApi().getPricingApi().createCostCode(target); + + if (defaultPrices != null && !defaultPrices.isEmpty()) { + CostCodeCurrenciesDto costcodecurrencies = new CostCodeCurrenciesDto(); + for (CostCodePrice ccp : defaultPrices) { + CostCodeCurrencyDto costcodecurrency = new CostCodeCurrencyDto(); + Currency currency = ccp.getCurrency(); + + costcodecurrency.addLink(new RESTLink("currency", currency.unwrap().getEditLink().getHref())); + costcodecurrency.setPrice(ccp.getPrice()); + costcodecurrencies.add(costcodecurrency); + } + context.getApi().getPricingApi().updateCostCodeCurrencies(getId(), costcodecurrencies); + } + + } + + public void update() { + target = context.getApi().getPricingApi().updateCostCode(target); + } + + // Builder + + public static Builder builder(final RestContext context) { + return new Builder(context); + } + + public static class Builder { + private RestContext context; + + private String name; + + private String description; + + private List defaultPrices = Lists.newArrayList(); + + public Builder(final RestContext context) { + super(); + this.context = context; + } + + public Builder name(final String name) { + this.name = name; + return this; + } + + public Builder description(final String description) { + this.description = description; + return this; + } + + public Builder defaultPrices(final List prices) { + this.defaultPrices.addAll(prices); + return this; + } + + public CostCode build() { + CostCodeDto dto = new CostCodeDto(); + dto.setName(name); + dto.setDescription(description); + CostCode costcode = new CostCode(context, dto); + costcode.setDefaultPrices(defaultPrices); + return costcode; + } + + public static Builder fromCostCode(final CostCode in) { + Builder builder = CostCode.builder(in.context).name(in.getName()).description(in.getDescription()) + .defaultPrices(in.getDefaultPrices()); + return builder; + } + } + + // Delegate methods + + public Integer getId() { + return target.getId(); + } + + public String getName() { + return target.getName(); + } + + public void setName(final String name) { + target.setName(name); + } + + public String getDescription() { + return target.getDescription(); + } + + public void setDescription(final String description) { + target.setDescription(description); + } + + public List getDefaultPrices() { + return defaultPrices; + } + + public void setDefaultPrices(final List defaultPrices) { + this.defaultPrices = defaultPrices; + } + + @Override + public String toString() { + return "CostCode [id=" + getId() + ", name=" + getName() + ", description=" + getDescription() + "]"; + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/config/CostCodeCurrency.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/config/CostCodeCurrency.java new file mode 100644 index 0000000000..f0a63dfefb --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/config/CostCodeCurrency.java @@ -0,0 +1,50 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.abiquo.domain.config; + +import java.math.BigDecimal; + +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.domain.DomainWrapper; +import org.jclouds.rest.RestContext; + +import com.abiquo.server.core.pricing.CostCodeCurrencyDto; + +public class CostCodeCurrency extends DomainWrapper { + + protected CostCodeCurrency(final RestContext context, final CostCodeCurrencyDto target) { + super(context, target); + } + + // Delegate methods + + public Integer getId() { + return target.getId(); + } + + public BigDecimal getPrice() { + return target.getPrice(); + } + + @Override + public String toString() { + return "CostCodeCurrency [id=" + getId() + ", price=" + getPrice() + "]"; + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/config/CostCodePrice.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/config/CostCodePrice.java new file mode 100644 index 0000000000..324d11ea78 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/config/CostCodePrice.java @@ -0,0 +1,60 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.abiquo.domain.config; + +import java.math.BigDecimal; + +/** + * Gives a price to a {@link CostCode}. + * + * @author Susana Acedo + */ +public class CostCodePrice { + private Currency currency; + + private BigDecimal price; + + public CostCodePrice(final Currency currency, final BigDecimal price) { + super(); + this.currency = currency; + this.price = price; + } + + public Currency getCurrency() { + return currency; + } + + public void setCurrency(final Currency currency) { + this.currency = currency; + } + + public BigDecimal getPrice() { + return price; + } + + public void setPrice(final BigDecimal price) { + this.price = price; + } + + @Override + public String toString() { + return "CostCodePrice [currency=" + currency + ", price=" + price + "]"; + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/config/Currency.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/config/Currency.java new file mode 100644 index 0000000000..1e0aa35568 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/config/Currency.java @@ -0,0 +1,148 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.config; + +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.domain.DomainWrapper; +import org.jclouds.rest.RestContext; + +import com.abiquo.server.core.pricing.CurrencyDto; + +/** + * Adds high level functionality to {@link CurrencyDto}. + * + * @author Ignasi Barrera + * @author Susana Acedo + */ +public class Currency extends DomainWrapper { + + /** + * Constructor to be used only by the builder. This resource cannot be + * created. + */ + private Currency(final RestContext context, final CurrencyDto target) { + super(context, target); + } + + // Domain operations + + public void delete() { + context.getApi().getPricingApi().deleteCurrency(target); + target = null; + } + + public void save() { + target = context.getApi().getPricingApi().createCurrency(target); + } + + public void update() { + target = context.getApi().getPricingApi().updateCurrency(target); + } + + // Builder + + public static Builder builder(final RestContext context) { + return new Builder(context); + } + + public static class Builder { + private RestContext context; + + private String name; + + private String symbol; + + private int digits; + + public Builder(final RestContext context) { + super(); + this.context = context; + } + + public Builder name(final String name) { + this.name = name; + return this; + } + + public Builder symbol(final String symbol) { + this.symbol = symbol; + return this; + } + + public Builder digits(final int digits) { + this.digits = digits; + return this; + } + + public Currency build() { + CurrencyDto dto = new CurrencyDto(); + dto.setName(name); + dto.setSymbol(symbol); + dto.setDigits(digits); + Currency currency = new Currency(context, dto); + + return currency; + } + + public static Builder fromCurrency(final Currency in) { + Builder builder = Currency.builder(in.context).name(in.getName()).symbol(in.getSymbol()) + .digits(in.getDigits()); + + return builder; + } + } + + // Delegate methods + + public Integer getId() { + return target.getId(); + } + + public String getName() { + return target.getName(); + } + + public void setName(final String name) { + target.setName(name); + } + + public String getSymbol() { + return target.getSymbol(); + } + + public void setSymbol(final String symbol) { + target.setSymbol(symbol); + } + + public int getDigits() { + return target.getDigits(); + } + + public void setDigits(final int digits) { + target.setDigits(digits); + } + + @Override + public String toString() { + return "Currency [id=" + getId() + ", name=" + getName() + ", symbol=" + getSymbol() + ", digits=" + getDigits() + + "]"; + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/config/License.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/config/License.java new file mode 100644 index 0000000000..d7f1c29f2c --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/config/License.java @@ -0,0 +1,123 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.config; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.domain.DomainWrapper; +import org.jclouds.abiquo.reference.annotations.EnterpriseEdition; +import org.jclouds.rest.RestContext; + +import com.abiquo.server.core.config.LicenseDto; + +/** + * Adds high level functionality to {@link LicenseDto}. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +@EnterpriseEdition +public class License extends DomainWrapper { + /** + * Constructor to be used only by the builder. + */ + protected License(final RestContext context, final LicenseDto target) { + super(context, target); + } + + // Domain operations + + public void remove() { + context.getApi().getConfigApi().removeLicense(target); + target = null; + } + + public void add() { + target = context.getApi().getConfigApi().addLicense(target); + } + + // Builder + + public static Builder builder(final RestContext context, final String code) { + return new Builder(context, code); + } + + public static class Builder { + private RestContext context; + + private String code; + + public Builder(final RestContext context, final String code) { + super(); + this.context = context; + this.code = code; + } + + public Builder code(final String code) { + this.code = code; + return this; + } + + public License build() { + LicenseDto dto = new LicenseDto(); + dto.setCode(code); + + License license = new License(context, dto); + return license; + } + + public static Builder fromLicense(final License in) { + return License.builder(in.context, in.getCode()); + } + } + + // Delegate methods + + public String getCode() { + return target.getCode(); + } + + public String getCustomerId() { + return target.getCustomerid(); + } + + public String getEnabledIp() { + return target.getEnabledip(); + } + + public String getExpiration() { + return target.getExpiration(); + } + + public Integer getId() { + return target.getId(); + } + + public Integer getNumCores() { + return target.getNumcores(); + } + + @Override + public String toString() { + return "License [id=" + getId() + ", code=" + getCode() + ", customerId=" + getCustomerId() + ", enabledIp=" + + getEnabledIp() + ", expiration=" + getExpiration() + ", numCores=" + getNumCores() + "]"; + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/config/PricingCostCode.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/config/PricingCostCode.java new file mode 100644 index 0000000000..397f03a74d --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/config/PricingCostCode.java @@ -0,0 +1,115 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.abiquo.domain.config; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.math.BigDecimal; + +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.domain.DomainWrapper; +import org.jclouds.abiquo.reference.ValidationErrors; +import org.jclouds.rest.RestContext; + +import com.abiquo.model.rest.RESTLink; +import com.abiquo.server.core.pricing.PricingCostCodeDto; + +/** + * Associates a {@link CostCode} with a pricing template. + * + * @author Susana Acedo + */ +public class PricingCostCode extends DomainWrapper { + private CostCode costcode; + + private PricingTemplate pricingTemplate; + + protected PricingCostCode(final RestContext context, final PricingCostCodeDto target) { + super(context, target); + } + + // Builder + + public static Builder builder(final RestContext context, + final PricingTemplate pricingtemplate, final CostCode costcode) { + return new Builder(context, pricingtemplate, costcode); + } + + public static class Builder { + private RestContext context; + + private Integer id; + + private PricingTemplate pricingTemplate; + + private CostCode costcode; + + private BigDecimal price; + + public Builder(final RestContext context, final PricingTemplate pricingTemplate, + final CostCode costcode) { + super(); + this.pricingTemplate = checkNotNull(pricingTemplate, ValidationErrors.NULL_RESOURCE + PricingTemplate.class); + this.costcode = checkNotNull(costcode, ValidationErrors.NULL_RESOURCE + CostCode.class); + this.context = context; + } + + public Builder price(final BigDecimal price) { + this.price = price; + return this; + } + + public PricingCostCode build() { + PricingCostCodeDto dto = new PricingCostCodeDto(); + dto.setId(id); + dto.setPrice(price); + + RESTLink link = costcode.unwrap().searchLink("edit"); + checkNotNull(link, ValidationErrors.MISSING_REQUIRED_LINK); + dto.addLink(new RESTLink("costcode", link.getHref())); + + PricingCostCode pricingcostcode = new PricingCostCode(context, dto); + pricingcostcode.pricingTemplate = pricingTemplate; + pricingcostcode.costcode = costcode; + + return pricingcostcode; + } + + public static Builder fromPricingCostCode(final PricingCostCode in) { + return PricingCostCode.builder(in.context, in.pricingTemplate, in.costcode).price(in.getPrice()); + } + } + + // Delegate methods + + public Integer getId() { + return target.getId(); + } + + public BigDecimal getPrice() { + return target.getPrice(); + } + + @Override + public String toString() { + return "PricingCostCode [id=" + getId() + ", price=" + getPrice() + "]"; + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/config/PricingTemplate.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/config/PricingTemplate.java new file mode 100644 index 0000000000..a31623fcde --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/config/PricingTemplate.java @@ -0,0 +1,379 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.config; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.math.BigDecimal; +import java.util.Date; + +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.domain.DomainWrapper; +import org.jclouds.abiquo.domain.enterprise.Enterprise; +import org.jclouds.abiquo.reference.ValidationErrors; +import org.jclouds.rest.RestContext; + +import com.abiquo.model.enumerator.PricingPeriod; +import com.abiquo.model.rest.RESTLink; +import com.abiquo.server.core.pricing.PricingTemplateDto; + +/** + * A pricing template is a complete pricing schema that can be assigned to an + * {@link Enterprise}. + *

+ * This pricing schema will provide detailed billing information for each + * resource consumed by the users of the enterprise. + * + * @author Ignasi Barrera + * @author Susana Acedo + */ + +public class PricingTemplate extends DomainWrapper { + + /** The currency used by the pricing template. */ + protected Currency currency; + + /** + * Constructor to be used only by the builder. This resource cannot be + * created. + */ + private PricingTemplate(final RestContext context, final PricingTemplateDto target) { + super(context, target); + } + + // Domain operations + + public void delete() { + context.getApi().getPricingApi().deletePricingTemplate(target); + target = null; + } + + public void save() { + target = context.getApi().getPricingApi().createPricingTemplate(target); + } + + public void update() { + target = context.getApi().getPricingApi().updatePricingTemplate(target); + } + + // Builder + + public static Builder builder(final RestContext context, final Currency currency) { + return new Builder(context, currency); + } + + public static class Builder { + private RestContext context; + + private Currency currency; + + private String name; + + private String description; + + private BigDecimal hdGB; + + private BigDecimal standingChargePeriod; + + private BigDecimal vlan; + + private PricingPeriod chargingPeriod; + + private BigDecimal minimumChargePeriod; + + private boolean showChangesBefore; + + private boolean showMinimumCharge; + + private PricingPeriod minimumCharge; + + private BigDecimal publicIp; + + private BigDecimal vcpu; + + private BigDecimal memoryGB; + + private boolean defaultTemplate; + + private Date lastUpdate; + + public Builder(final RestContext context, final Currency currency) { + super(); + this.currency = checkNotNull(currency, ValidationErrors.NULL_RESOURCE + Currency.class); + this.context = context; + } + + public Builder name(final String name) { + this.name = name; + return this; + } + + public Builder description(final String description) { + this.description = description; + return this; + } + + public Builder hdGB(final BigDecimal hdGB) { + this.hdGB = hdGB; + return this; + } + + public Builder standingChargePeriod(final BigDecimal standingChargePeriod) { + this.standingChargePeriod = standingChargePeriod; + return this; + } + + public Builder chargingPeriod(final PricingPeriod chargingPeriod) { + this.chargingPeriod = chargingPeriod; + return this; + } + + public Builder vlan(final BigDecimal vlan) { + this.vlan = vlan; + return this; + } + + public Builder minimumChargePeriod(final BigDecimal minimumChargePeriod) { + this.minimumChargePeriod = minimumChargePeriod; + return this; + } + + public Builder minimumCharge(final PricingPeriod minimumCharge) { + this.minimumCharge = minimumCharge; + return this; + } + + public Builder showChangesBefore(final boolean showChangesBefore) { + this.showChangesBefore = showChangesBefore; + return this; + } + + public Builder showMinimumCharge(final boolean showMinimumCharge) { + this.showMinimumCharge = showMinimumCharge; + return this; + } + + public Builder publicIp(final BigDecimal publicIp) { + this.publicIp = publicIp; + return this; + } + + public Builder vcpu(final BigDecimal vcpu) { + this.vcpu = vcpu; + return this; + } + + public Builder memoryGB(final BigDecimal memoryGB) { + this.memoryGB = memoryGB; + return this; + } + + public Builder defaultTemplate(final boolean defaultTemplate) { + this.defaultTemplate = defaultTemplate; + return this; + } + + public Builder lastUpdate(final Date lastUpdate) { + this.lastUpdate = lastUpdate; + return this; + } + + public Builder currency(final Currency currency) { + this.currency = checkNotNull(currency, ValidationErrors.NULL_RESOURCE + Currency.class); + return this; + } + + public PricingTemplate build() { + PricingTemplateDto dto = new PricingTemplateDto(); + dto.setName(name); + dto.setDescription(description); + dto.setHdGB(hdGB); + dto.setStandingChargePeriod(standingChargePeriod); + dto.setVlan(vlan); + dto.setChargingPeriod(chargingPeriod.ordinal()); + dto.setMinimumCharge(minimumCharge.ordinal()); + dto.setMinimumChargePeriod(minimumChargePeriod); + dto.setShowChangesBefore(showChangesBefore); + dto.setShowMinimumCharge(showMinimumCharge); + dto.setPublicIp(publicIp); + dto.setVcpu(vcpu); + dto.setMemoryGB(memoryGB); + dto.setDefaultTemplate(defaultTemplate); + dto.setLastUpdate(lastUpdate); + + RESTLink link = currency.unwrap().searchLink("edit"); + checkNotNull(link, ValidationErrors.MISSING_REQUIRED_LINK); + dto.addLink(new RESTLink("currency", link.getHref())); + + PricingTemplate pricingTemplate = new PricingTemplate(context, dto); + pricingTemplate.currency = currency; + + return pricingTemplate; + } + + public static Builder fromPricingTemplate(final PricingTemplate in) { + Builder builder = PricingTemplate.builder(in.context, in.currency).name(in.getName()) + .description(in.getDescription()).hdGB(in.getHdGB()).standingChargePeriod(in.getStandingChargePeriod()) + .vcpu(in.getVlan()).chargingPeriod(in.getChargingPeriod()).minimumCharge(in.getMinimumCharge()) + .minimumChargePeriod(in.getMinimumChargePeriod()).showChangesBefore(in.isShowChangesBefore()) + .showMinimumCharge(in.isShowMinimumCharge()).publicIp(in.getPublicIp()).vcpu(in.getVcpu()) + .memoryGB(in.getMemoryGB()).defaultTemplate(in.isDefaultTemplate()).lastUpdate(in.getLastUpdate()); + return builder; + } + } + + // Delegate methods + + public Integer getId() { + return target.getId(); + } + + public String getName() { + return target.getName(); + } + + public void setName(final String name) { + target.setName(name); + } + + public String getDescription() { + return target.getDescription(); + } + + public void setDescription(final String description) { + target.setDescription(description); + } + + public BigDecimal getHdGB() { + return target.getHdGB(); + } + + public void setHdGB(final BigDecimal hdGB) { + target.setHdGB(hdGB); + } + + public BigDecimal getStandingChargePeriod() { + return target.getStandingChargePeriod(); + } + + public void setStandingChargePeriod(final BigDecimal standingChargePeriod) { + target.setStandingChargePeriod(standingChargePeriod); + } + + public BigDecimal getVlan() { + return target.getVlan(); + } + + public void setVlan(final BigDecimal vlan) { + target.getVlan(); + } + + public BigDecimal getMinimumChargePeriod() { + return target.getMinimumChargePeriod(); + } + + public void setMinimumChargePeriod(final BigDecimal minimumChargePeriod) { + target.setMinimumChargePeriod(minimumChargePeriod); + } + + public boolean isShowChangesBefore() { + return target.isShowChangesBefore(); + } + + public void setShowChangesBefore(final boolean showChangesBefore) { + target.setShowChangesBefore(showChangesBefore); + } + + public boolean isShowMinimumCharge() { + return target.isShowMinimumCharge(); + } + + public void setShowMinimumCharge(final boolean showMinimumCharge) { + target.setShowMinimumCharge(showMinimumCharge); + } + + public PricingPeriod getMinimumCharge() { + return PricingPeriod.fromId(target.getMinimumCharge()); + } + + public void setMinimumCharge(final PricingPeriod minimumCharge) { + target.setMinimumCharge(minimumCharge.ordinal()); + } + + public PricingPeriod getChargingPeriod() { + return PricingPeriod.fromId(target.getChargingPeriod()); + } + + public void setChargingPeriod(final PricingPeriod chargingPeriod) { + target.setChargingPeriod(chargingPeriod.ordinal()); + } + + public BigDecimal getPublicIp() { + return target.getPublicIp(); + } + + public void setPublicIp(final BigDecimal publicIp) { + target.setPublicIp(publicIp); + } + + public BigDecimal getVcpu() { + return target.getVcpu(); + } + + public void setVcpu(final BigDecimal vcpu) { + target.setVcpu(vcpu); + } + + public BigDecimal getMemoryGB() { + return target.getMemoryGB(); + } + + public void setMemoryGB(final BigDecimal memoryGB) { + target.setMemoryGB(memoryGB); + } + + public boolean isDefaultTemplate() { + return target.isDefaultTemplate(); + } + + public void setDefaultTemplate(final boolean defaultTemplate) { + target.setDefaultTemplate(defaultTemplate); + } + + public Date getLastUpdate() { + return target.getLastUpdate(); + } + + public void setLastUpdate(final Date lastUpdate) { + target.setLastUpdate(lastUpdate); + } + + @Override + public String toString() { + return "PricingTemplate [id=" + getId() + ", name=" + getName() + ", description=" + getDescription() + + ", hdGB =" + getHdGB() + ", standingChargePeriod =" + getStandingChargePeriod() + ", vlan = " + getVlan() + + ", chargingPeriod =" + getChargingPeriod() + ", minimumChargePeriod=" + getMinimumChargePeriod() + + ", showChangesBefore =" + isShowChangesBefore() + ", showMinimumCharge= " + isShowMinimumCharge() + + ", minimumCharge = " + getMinimumCharge() + ", publicIp = " + getPublicIp() + ", vcpu =" + getVcpu() + + ", memoryGB= " + getMemoryGB() + ", defaultTemplate= " + isDefaultTemplate() + ", lastUpdate = " + + getLastUpdate() + "]"; + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/config/PricingTier.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/config/PricingTier.java new file mode 100644 index 0000000000..89f4ec548c --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/config/PricingTier.java @@ -0,0 +1,115 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.abiquo.domain.config; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.math.BigDecimal; + +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.domain.DomainWrapper; +import org.jclouds.abiquo.domain.infrastructure.Tier; +import org.jclouds.abiquo.reference.ValidationErrors; +import org.jclouds.rest.RestContext; + +import com.abiquo.model.rest.RESTLink; +import com.abiquo.server.core.pricing.PricingTierDto; + +/** + * Associates an storage {@link Tier} with a {@link PricingTemplate}. + * + * @author Susana Acedo + */ +public class PricingTier extends DomainWrapper { + private Tier tier; + + private PricingTemplate pricingTemplate; + + protected PricingTier(final RestContext context, final PricingTierDto target) { + super(context, target); + } + + // Builder + + public static Builder builder(final RestContext context, + final PricingTemplate pricingtemplate, final Tier tier) { + return new Builder(context, pricingtemplate, tier); + } + + public static class Builder { + private RestContext context; + + private Integer id; + + private PricingTemplate pricingTemplate; + + private Tier tier; + + private BigDecimal price; + + public Builder(final RestContext context, final PricingTemplate pricingTemplate, + final Tier tier) { + super(); + this.pricingTemplate = checkNotNull(pricingTemplate, ValidationErrors.NULL_RESOURCE + PricingTemplate.class); + this.tier = checkNotNull(tier, ValidationErrors.NULL_RESOURCE + Tier.class); + this.context = context; + } + + public Builder price(final BigDecimal price) { + this.price = price; + return this; + } + + public PricingTier build() { + PricingTierDto dto = new PricingTierDto(); + dto.setId(id); + dto.setPrice(price); + + RESTLink link = tier.unwrap().searchLink("edit"); + checkNotNull(link, ValidationErrors.MISSING_REQUIRED_LINK); + dto.addLink(new RESTLink("tier", link.getHref())); + + PricingTier pricingTier = new PricingTier(context, dto); + pricingTier.pricingTemplate = pricingTemplate; + pricingTier.tier = tier; + + return pricingTier; + } + + public static Builder fromPricingTier(final PricingTier in) { + return PricingTier.builder(in.context, in.pricingTemplate, in.tier).price(in.getPrice()); + } + } + + // Delegate methods + + public Integer getId() { + return target.getId(); + } + + public BigDecimal getPrice() { + return target.getPrice(); + } + + @Override + public String toString() { + return "PricingTier [id=" + getId() + ", price=" + getPrice() + "]"; + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/config/Privilege.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/config/Privilege.java new file mode 100644 index 0000000000..8c828dbdcf --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/config/Privilege.java @@ -0,0 +1,61 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.config; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.domain.DomainWrapper; +import org.jclouds.abiquo.reference.annotations.EnterpriseEdition; +import org.jclouds.rest.RestContext; + +import com.abiquo.server.core.enterprise.PrivilegeDto; + +/** + * Adds high level functionality to {@link PrivilegeDto}. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +@EnterpriseEdition +public class Privilege extends DomainWrapper { + /** + * Constructor to be used only by the builder. This resource cannot be + * created. + */ + private Privilege(final RestContext context, final PrivilegeDto target) { + super(context, target); + } + + // Delegate methods + + public Integer getId() { + return target.getId(); + } + + public String getName() { + return target.getName(); + } + + @Override + public String toString() { + return "Privilege [id=" + getId() + ", name=" + getName() + "]"; + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/config/SystemProperty.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/config/SystemProperty.java new file mode 100644 index 0000000000..07c57827a2 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/config/SystemProperty.java @@ -0,0 +1,79 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.config; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.domain.DomainWrapper; +import org.jclouds.rest.RestContext; + +import com.abiquo.server.core.config.SystemPropertyDto; + +/** + * Adds high level functionality to {@link SystemPropertyDto}. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + * @see API: http://community.abiquo.com/display/ABI20/System+Property+resource + */ + +public class SystemProperty extends DomainWrapper { + /** + * Constructor to be used only by the builder. This resource cannot be + * created. + */ + private SystemProperty(final RestContext context, final SystemPropertyDto target) { + super(context, target); + } + + // Domain operations + + /** + * @see API: http://community.abiquo.com/display/ABI20/System+Property+resource# + * SystemPropertyresource-ModifyanexistingSystemProperty + */ + public void update() { + target = context.getApi().getConfigApi().updateSystemProperty(target); + } + + // Delegate methods + + public String getName() { + return target.getName(); + } + + public String getValue() { + return target.getValue(); + } + + public void setValue(final String value) { + target.setValue(value); + } + + @Override + public String toString() { + return "SystemPorperty [getName()=" + getName() + ", getValue()=" + getValue() + "]"; + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/config/options/IconOptions.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/config/options/IconOptions.java new file mode 100644 index 0000000000..792abeefd1 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/config/options/IconOptions.java @@ -0,0 +1,58 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.config.options; + +import org.jclouds.http.options.BaseHttpRequestOptions; + +/** + * Available options to query icons. + * + * @author Francesc Montserrat + */ +public class IconOptions extends BaseHttpRequestOptions { + public static Builder builder() { + return new Builder(); + } + + @Override + protected Object clone() throws CloneNotSupportedException { + IconOptions options = new IconOptions(); + options.queryParameters.putAll(queryParameters); + return options; + } + + public static class Builder { + private String path; + + public Builder path(final String path) { + this.path = path; + return this; + } + + public IconOptions build() { + IconOptions options = new IconOptions(); + if (path != null) { + options.queryParameters.put("path", path); + } + + return options; + } + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/config/options/LicenseOptions.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/config/options/LicenseOptions.java new file mode 100644 index 0000000000..252b507791 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/config/options/LicenseOptions.java @@ -0,0 +1,70 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.config.options; + +import org.jclouds.abiquo.reference.annotations.EnterpriseEdition; +import org.jclouds.http.options.BaseHttpRequestOptions; + +/** + * Available options to query licenses. + * + * @author Francesc Montserrat + */ +@EnterpriseEdition +public class LicenseOptions extends BaseHttpRequestOptions { + public static Builder builder() { + return new Builder(); + } + + @Override + protected Object clone() throws CloneNotSupportedException { + LicenseOptions options = new LicenseOptions(); + options.queryParameters.putAll(queryParameters); + return options; + } + + public static class Builder { + private Boolean active; + + /** + * Search active licenses + */ + public Builder active(final boolean active) { + this.active = active; + return this; + } + + /** + * Search inaactive licenses + */ + public Builder inactive(final boolean inactive) { + this.active = !inactive; + return this; + } + + public LicenseOptions build() { + LicenseOptions options = new LicenseOptions(); + if (active != null) { + options.queryParameters.put("active", active.toString()); + } + return options; + } + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/config/options/PropertyOptions.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/config/options/PropertyOptions.java new file mode 100644 index 0000000000..8b9c597619 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/config/options/PropertyOptions.java @@ -0,0 +1,68 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.config.options; + +import org.jclouds.http.options.BaseHttpRequestOptions; + +/** + * Available options to query system properties. + * + * @author Francesc Montserrat + */ +public class PropertyOptions extends BaseHttpRequestOptions { + public static Builder builder() { + return new Builder(); + } + + @Override + protected Object clone() throws CloneNotSupportedException { + PropertyOptions options = new PropertyOptions(); + options.queryParameters.putAll(queryParameters); + return options; + } + + public static class Builder { + private String component; + + private String name; + + public Builder component(final String component) { + this.component = component; + return this; + } + + public Builder name(final String name) { + this.name = name; + return this; + } + + public PropertyOptions build() { + PropertyOptions options = new PropertyOptions(); + if (component != null) { + options.queryParameters.put("component", component.toString()); + } + + if (name != null) { + options.queryParameters.put("name", name.toString()); + } + return options; + } + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/enterprise/Enterprise.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/enterprise/Enterprise.java new file mode 100644 index 0000000000..7b6d55bfa5 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/enterprise/Enterprise.java @@ -0,0 +1,932 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.enterprise; + +import static com.google.common.collect.Iterables.filter; + +import java.util.List; + +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.domain.DomainWithLimitsWrapper; +import org.jclouds.abiquo.domain.builder.LimitsBuilder; +import org.jclouds.abiquo.domain.cloud.VirtualAppliance; +import org.jclouds.abiquo.domain.cloud.VirtualDatacenter; +import org.jclouds.abiquo.domain.cloud.VirtualMachine; +import org.jclouds.abiquo.domain.cloud.VirtualMachineTemplate; +import org.jclouds.abiquo.domain.exception.AbiquoException; +import org.jclouds.abiquo.domain.infrastructure.Datacenter; +import org.jclouds.abiquo.domain.infrastructure.Machine; +import org.jclouds.abiquo.domain.network.ExternalIp; +import org.jclouds.abiquo.domain.network.ExternalNetwork; +import org.jclouds.abiquo.domain.network.Network; +import org.jclouds.abiquo.domain.network.UnmanagedIp; +import org.jclouds.abiquo.domain.network.UnmanagedNetwork; +import org.jclouds.abiquo.reference.annotations.EnterpriseEdition; +import org.jclouds.abiquo.rest.internal.ExtendedUtils; +import org.jclouds.abiquo.strategy.enterprise.ListVirtualMachineTemplates; +import org.jclouds.http.HttpResponse; +import org.jclouds.http.functions.ParseXMLWithJAXB; +import org.jclouds.rest.RestContext; + +import com.abiquo.model.rest.RESTLink; +import com.abiquo.server.core.appslibrary.TemplateDefinitionListDto; +import com.abiquo.server.core.appslibrary.TemplateDefinitionListsDto; +import com.abiquo.server.core.appslibrary.VirtualMachineTemplateDto; +import com.abiquo.server.core.appslibrary.VirtualMachineTemplatesDto; +import com.abiquo.server.core.cloud.VirtualAppliancesDto; +import com.abiquo.server.core.cloud.VirtualDatacentersDto; +import com.abiquo.server.core.cloud.VirtualMachinesWithNodeExtendedDto; +import com.abiquo.server.core.enterprise.DatacenterLimitsDto; +import com.abiquo.server.core.enterprise.DatacentersLimitsDto; +import com.abiquo.server.core.enterprise.EnterpriseDto; +import com.abiquo.server.core.enterprise.EnterprisePropertiesDto; +import com.abiquo.server.core.enterprise.RolesDto; +import com.abiquo.server.core.enterprise.UserDto; +import com.abiquo.server.core.enterprise.UsersDto; +import com.abiquo.server.core.infrastructure.DatacentersDto; +import com.abiquo.server.core.infrastructure.MachinesDto; +import com.abiquo.server.core.infrastructure.network.VLANNetworksDto; +import com.google.common.base.Predicate; +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; +import com.google.inject.TypeLiteral; + +/** + * Adds high level functionality to {@link EnterpriseDto}. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + * @see API: + * http://community.abiquo.com/display/ABI20/EnterpriseResource + */ +public class Enterprise extends DomainWithLimitsWrapper { + /** The default value for the reservation restricted flag. */ + private static final boolean DEFAULT_RESERVATION_RESTRICTED = false; + + /** + * Constructor to be used only by the builder. + */ + protected Enterprise(final RestContext context, final EnterpriseDto target) { + super(context, target); + } + + // Domain operations + + /** + * Delete the enterprise. + * + * @see API: http://community.abiquo.com/display/ABI20/EnterpriseResource# + * EnterpriseResource- DeleteanexistingEnterprise + */ + public void delete() { + context.getApi().getEnterpriseApi().deleteEnterprise(target); + target = null; + } + + /** + * Create a new enterprise in Abiquo. + * + * @see API: http://community.abiquo.com/display/ABI20/EnterpriseResource# + * EnterpriseResource- CreatesanewEnterprise + */ + public void save() { + target = context.getApi().getEnterpriseApi().createEnterprise(target); + } + + /** + * Update emterprise information in the server with the data from this + * enterprise. + * + * @see API: http://community.abiquo.com/display/ABI20/EnterpriseResource# + * EnterpriseResource- Updateanexistingenterprise + */ + public void update() { + target = context.getApi().getEnterpriseApi().updateEnterprise(target); + } + + // Children access + + /** + * Retrieve the list of virtual datacenters by this enterprise. + * + * @see API: http://community.abiquo.com/display/ABI20/EnterpriseResource# + * EnterpriseResource- + * RetrievealistofvitualdatacentersbyanEnterprise + * @return List of virtual datacenters in this enterprise. + */ + public List listVirtualDatacenters() { + VirtualDatacentersDto dto = context.getApi().getEnterpriseApi().listVirtualDatacenters(target); + return wrap(context, VirtualDatacenter.class, dto.getCollection()); + } + + /** + * Retrieve a filtered list of virtual datacenters by this enterprise. + * + * @param filter + * Filter to be applied to the list. + * @see API: http://community.abiquo.com/display/ABI20/EnterpriseResource# + * EnterpriseResource- + * RetrievealistofvitualdatacentersbyanEnterprise + * @return Filtered list of virtual datacenters in this enterprise. + */ + public List listVirtualDatacenters(final Predicate filter) { + return Lists.newLinkedList(filter(listVirtualDatacenters(), filter)); + } + + /** + * Retrieve a the first virtual datacenter matching the filter within the + * list of virtual datacenters by this enterprise. + * + * @param filter + * Filter to be applied to the list. + * @see API: http://community.abiquo.com/display/ABI20/EnterpriseResource# + * EnterpriseResource- + * RetrievealistofvitualdatacentersbyanEnterprise + * @return First virtual datacenter matching the filter or null + * if the is none. + */ + public VirtualDatacenter findVirtualDatacenter(final Predicate filter) { + return Iterables.getFirst(filter(listVirtualDatacenters(), filter), null); + } + + /** + * Retrieve the list of template definition lists of the enterprise. + * + * @see API: http://community.abiquo.com/display/ABI20/ + * TemplateDefinitionListResource# + * TemplateDefinitionListResource-Retrievealltemplatedefinitionlists + * @return List of template definition lists of the enterprise. + */ + public List listTemplateDefinitionLists() { + TemplateDefinitionListsDto dto = context.getApi().getEnterpriseApi().listTemplateDefinitionLists(target); + return wrap(context, TemplateDefinitionList.class, dto.getCollection()); + } + + /** + * Retrieve a filtered list of template definition lists from this + * enterprise. + * + * @param filter + * Filter to be applied to the list. + * @see API: http://community.abiquo.com/display/ABI20/ + * TemplateDefinitionListResource# + * TemplateDefinitionListResource-Retrievealltemplatedefinitionlists + * @return Filtered list of template definition lists of the enterprise. + */ + public List listTemplateDefinitionLists(final Predicate filter) { + return Lists.newLinkedList(filter(listTemplateDefinitionLists(), filter)); + } + + /** + * Retrieve the first template definition list matching the filter within the + * list. + * + * @param filter + * Filter to be applied to the list. + * @see API: http://community.abiquo.com/display/ABI20/ + * TemplateDefinitionListResource# + * TemplateDefinitionListResource-Retrievealltemplatedefinitionlists + * @return First template definition list matching the filter or + * null if the is none. + */ + public TemplateDefinitionList findTemplateDefinitionList(final Predicate filter) { + return Iterables.getFirst(filter(listTemplateDefinitionLists(), filter), null); + } + + /** + * Retrieve a single template definition list. + * + * @param id + * Unique ID of the template definition list for this enterprise. + * @see API: http://community.abiquo.com/display/ABI20/ + * TemplateDefinitionListResource# + * TemplateDefinitionListResource-Retrieveatemplatedefinitionlist + * @return Template definition with the given id or null if it + * does not exist. + */ + public TemplateDefinitionList getTemplateDefinitionList(final Integer id) { + TemplateDefinitionListDto templateList = context.getApi().getEnterpriseApi() + .getTemplateDefinitionList(target, id); + return wrap(context, TemplateDefinitionList.class, templateList); + } + + /** + * Retrieve the list of datacenter limits by enterprise. + * + * @see API: http://community.abiquo.com/display/ABI20/DatacenterLimitsResource# + * DatacenterLimitsResource-Retrievelimitsbyenterprise + * @return List of datacenter limits by enterprise. + */ + public List listLimits() { + DatacentersLimitsDto dto = context.getApi().getEnterpriseApi().listLimits(this.unwrap()); + return wrap(context, Limits.class, dto.getCollection()); + } + + /** + * Retrieve a filtered list of datacenter limits by enterprise. + * + * @param filter + * Filter to be applied to the list. + * @see API: http://community.abiquo.com/display/ABI20/DatacenterLimitsResource# + * DatacenterLimitsResource-Retrievelimitsbyenterprise + * @return Filtered list of datacenter limits by enterprise. + */ + public List listLimits(final Predicate filter) { + return Lists.newLinkedList(filter(listLimits(), filter)); + } + + /** + * Retrieve the first datacenter limits matching the filter within the list + * of datacenter limits by enterprise. + * + * @param filter + * Filter to be applied to the list. + * @see API: http://community.abiquo.com/display/ABI20/DatacenterLimitsResource# + * DatacenterLimitsResource-Retrievelimitsbyenterprise + * @return First datacenter limits matching the filter or null + * if there is none. + */ + public Limits findLimits(final Predicate filter) { + return Iterables.getFirst(filter(listLimits(), filter), null); + } + + /** + * Retrieve the defined properties of the given enterprise. + * + * @see API: http://community.abiquo.com/display/ABI20/ + * EnterprisePropertiesResource# + * EnterprisePropertiesResource-Retrievethepropertiesforanenterprise + * @return The defined properties of the given enterprise. + */ + public EnterpriseProperties getEnterpriseProperties() { + EnterprisePropertiesDto dto = context.getApi().getEnterpriseApi().getEnterpriseProperties(this.unwrap()); + return wrap(context, EnterpriseProperties.class, dto); + } + + /** + * Retrieve the list of users of this enterprise. + * + * @see API: + * http://community.abiquo.com/display/ABI20/UserResource#UserResource- + * Retrievealistofusers + * @return List of users of this enterprise. + */ + public List listUsers() { + UsersDto dto = context.getApi().getEnterpriseApi().listUsers(this.unwrap()); + return wrap(context, User.class, dto.getCollection()); + } + + /** + * Retrieve a filtered list of users of this enterprise. + * + * @param filter + * Filter to be applied to the list. + * @see API: + * http://community.abiquo.com/display/ABI20/UserResource#UserResource- + * Retrievealistofusers + * @return Filtered list of users of this enterprise. + */ + public List listUsers(final Predicate filter) { + return Lists.newLinkedList(filter(listUsers(), filter)); + } + + /** + * Retrieve the first user matching the filter within the list of users of + * this enterprise. + * + * @param filter + * Filter to be applied to the list. + * @see API: + * http://community.abiquo.com/display/ABI20/UserResource#UserResource- + * Retrievealistofusers + * @return First user matching the filter or null if there is + * none. + */ + public User findUser(final Predicate filter) { + return Iterables.getFirst(filter(listUsers(), filter), null); + } + + /** + * Retrieve a single user. + * + * @param id + * Unique ID of the user in this enterprise. + * @see API: + * http://community.abiquo.com/display/ABI20/UserResource#UserResource- + * Retrieveauser + * @return User with the given id or null if it does not exist. + */ + public User getUser(final Integer id) { + UserDto user = context.getApi().getEnterpriseApi().getUser(target, id); + return wrap(context, User.class, user); + } + + /** + * Retrieve the list of roles defined by this enterprise. + * + * @return List of roles by this enterprise. + */ + public List listRoles() { + RolesDto dto = context.getApi().getAdminApi().listRoles(target); + return wrap(context, Role.class, dto.getCollection()); + } + + /** + * Retrieve a filtered list of roles defined by this enterprise. + * + * @param filter + * Filter to be applied to the list. + * @return Filtered list of roles by this enterprise. + */ + public List listRoles(final Predicate filter) { + return Lists.newLinkedList(filter(listRoles(), filter)); + } + + /** + * Retrieve the first role matching the filter within the list of roles + * defined by this enterprise. + * + * @param filter + * Filter to be applied to the list. + * @return First role matching the filter or null if there is + * none. + */ + public Role findRole(final Predicate filter) { + return Iterables.getFirst(filter(listRoles(), filter), null); + } + + public List listTemplatesInRepository(final Datacenter datacenter) { + VirtualMachineTemplatesDto dto = context.getApi().getVirtualMachineTemplateApi() + .listVirtualMachineTemplates(target.getId(), datacenter.getId()); + return wrap(context, VirtualMachineTemplate.class, dto.getCollection()); + } + + public List listTemplatesInRepository(final Datacenter datacenter, + final Predicate filter) { + return Lists.newLinkedList(filter(listTemplatesInRepository(datacenter), filter)); + } + + public VirtualMachineTemplate findTemplateInRepository(final Datacenter datacenter, + final Predicate filter) { + return Iterables.getFirst(filter(listTemplatesInRepository(datacenter), filter), null); + } + + public VirtualMachineTemplate getTemplateInRepository(final Datacenter datacenter, final Integer id) { + VirtualMachineTemplateDto template = context.getApi().getVirtualMachineTemplateApi() + .getVirtualMachineTemplate(target.getId(), datacenter.getId(), id); + return wrap(context, VirtualMachineTemplate.class, template); + } + + public List listTemplates() { + ListVirtualMachineTemplates strategy = context.getUtils().getInjector() + .getInstance(ListVirtualMachineTemplates.class); + return Lists.newLinkedList(strategy.execute(this)); + } + + public List listTemplates(final Predicate filter) { + ListVirtualMachineTemplates strategy = context.getUtils().getInjector() + .getInstance(ListVirtualMachineTemplates.class); + return Lists.newLinkedList(strategy.execute(this, filter)); + } + + public VirtualMachineTemplate findTemplate(final Predicate filter) { + ListVirtualMachineTemplates strategy = context.getUtils().getInjector() + .getInstance(ListVirtualMachineTemplates.class); + return Iterables.getFirst(strategy.execute(this, filter), null); + } + + public List listAllowedDatacenters() { + DatacentersDto datacenters = context.getApi().getEnterpriseApi().listAllowedDatacenters(target.getId()); + return wrap(context, Datacenter.class, datacenters.getCollection()); + } + + public List listAllowedDatacenters(final Predicate filter) { + return Lists.newLinkedList(filter(listAllowedDatacenters(), filter)); + } + + public Datacenter findAllowedDatacenter(final Predicate filter) { + return Iterables.getFirst(filter(listAllowedDatacenters(), filter), null); + } + + /** + * @see API: http://community.abiquo.com/display/ABI20/Enterprise+Resource# + * EnterpriseResource- Getthelistofexternalnetworks + */ + @EnterpriseEdition + public List listExternalNetworks(final Datacenter datacenter) { + DatacenterLimitsDto limitForDatacenter = getLimits(datacenter); + + ExtendedUtils utils = (ExtendedUtils) context.getUtils(); + HttpResponse response = utils.getAbiquoHttpClient().get(limitForDatacenter.searchLink("externalnetworks")); + + ParseXMLWithJAXB parser = new ParseXMLWithJAXB(utils.getXml(), + TypeLiteral.get(VLANNetworksDto.class)); + + return wrap(context, ExternalNetwork.class, parser.apply(response).getCollection()); + } + + @EnterpriseEdition + public List listExternalNetworks(final Datacenter datacenter, + final Predicate> filter) { + return Lists.newLinkedList(filter(listExternalNetworks(datacenter), filter)); + } + + @EnterpriseEdition + public ExternalNetwork findExternalNetwork(final Datacenter datacenter, final Predicate> filter) { + return Iterables.getFirst(filter(listExternalNetworks(datacenter), filter), null); + } + + @EnterpriseEdition + public List listUnmanagedNetworks(final Datacenter datacenter) { + DatacenterLimitsDto limitForDatacenter = getLimits(datacenter); + + ExtendedUtils utils = (ExtendedUtils) context.getUtils(); + // The "rel" for the unmanaged networks is the same than teh one used for + // external networks + HttpResponse response = utils.getAbiquoHttpClient().get(limitForDatacenter.searchLink("externalnetworks")); + + ParseXMLWithJAXB parser = new ParseXMLWithJAXB(utils.getXml(), + TypeLiteral.get(VLANNetworksDto.class)); + + return wrap(context, UnmanagedNetwork.class, parser.apply(response).getCollection()); + } + + @EnterpriseEdition + public List listUnmanagedNetworks(final Datacenter datacenter, + final Predicate> filter) { + return Lists.newLinkedList(filter(listUnmanagedNetworks(datacenter), filter)); + } + + @EnterpriseEdition + public UnmanagedNetwork findUnmanagedNetwork(final Datacenter datacenter, + final Predicate> filter) { + return Iterables.getFirst(filter(listUnmanagedNetworks(datacenter), filter), null); + } + + /** + * Retrieve the list of virtual appliances by this enterprise. + * + * @see API: http://community.abiquo.com/display/ABI20/EnterpriseResource# + * EnterpriseResource- + * RetrievethelistofvirtualappliancesbyanEnterprise + * @return List of virtual appliances by this enterprise. + */ + public List listVirtualAppliances() { + VirtualAppliancesDto virtualAppliances = context.getApi().getEnterpriseApi().listVirtualAppliances(target); + return wrap(context, VirtualAppliance.class, virtualAppliances.getCollection()); + } + + /** + * Retrieve a filtered list of virtual appliances by this enterprise. + * + * @param filter + * Filter to be applied to the list. + * @see API: http://community.abiquo.com/display/ABI20/EnterpriseResource# + * EnterpriseResource- + * RetrievethelistofvirtualappliancesbyanEnterprise + * @return Filtered list of virtual appliances by this enterprise. + */ + public List listVirtualAppliances(final Predicate filter) { + return Lists.newLinkedList(filter(listVirtualAppliances(), filter)); + } + + /** + * Retrieve the first virtual appliance matching the filter within the list + * of virtual appliances in this enterprise. + * + * @param filter + * Filter to be applied to the list. + * @see API: http://community.abiquo.com/display/ABI20/EnterpriseResource# + * EnterpriseResource- + * RetrievethelistofvirtualappliancesbyanEnterprise + * @return First virtual machine matching the filter or null if + * the is none. + */ + public VirtualAppliance findVirtualAppliance(final Predicate filter) { + return Iterables.getFirst(filter(listVirtualAppliances(), filter), null); + } + + /** + * Retrieve the list of virtual machines by this enterprise. + * + * @see API: http://community.abiquo.com/display/ABI20/EnterpriseResource# + * EnterpriseResource- RetrievealistofvirtualmachinesbyanEnterprise + * @return List of virtual machines by this enterprise. + */ + public List listVirtualMachines() { + VirtualMachinesWithNodeExtendedDto machines = context.getApi().getEnterpriseApi().listVirtualMachines(target); + return wrap(context, VirtualMachine.class, machines.getCollection()); + } + + /** + * Retrieve a filtered list of virtual machines by this enterprise. + * + * @param filter + * Filter to be applied to the list. + * @see API: http://community.abiquo.com/display/ABI20/EnterpriseResource# + * EnterpriseResource- RetrievealistofvirtualmachinesbyanEnterprise + * @return Filtered list of virtual machines by this enterprise. + */ + public List listVirtualMachines(final Predicate filter) { + return Lists.newLinkedList(filter(listVirtualMachines(), filter)); + } + + /** + * Retrieve the first virtual machine matching the filter within the list of + * virtual machines in this enterprise. + * + * @param filter + * Filter to be applied to the list. + * @see API: http://community.abiquo.com/display/ABI20/EnterpriseResource# + * EnterpriseResource- RetrievealistofvirtualmachinesbyanEnterprise + * @return First virtual machine matching the filter or null if + * the is none. + */ + public VirtualMachine findVirtualMachine(final Predicate filter) { + return Iterables.getFirst(filter(listVirtualMachines(), filter), null); + } + + public List listReservedMachines() { + MachinesDto machines = context.getApi().getEnterpriseApi().listReservedMachines(target); + return wrap(context, Machine.class, machines.getCollection()); + } + + public List listReservedMachines(final Predicate filter) { + return Lists.newLinkedList(filter(listVirtualMachines(), filter)); + } + + public VirtualMachine findReservedMachine(final Predicate filter) { + return Iterables.getFirst(filter(listVirtualMachines(), filter), null); + } + + // Actions + + /** + * @see API: http://community.abiquo.com/display/ABI20/Datacenter+Repository+ + * Resource# DatacenterRepositoryResource- + * SynchronizetheDatacenterRepositorywiththerepository + */ + public void refreshTemplateRepository(final Datacenter datacenter) { + context.getApi().getEnterpriseApi().refreshTemplateRepository(target.getId(), datacenter.getId()); + } + + /** + * Allows the given datacenter to be used by this enterprise. Creates a + * {@link Limits} object if not exists. + * + * @param datacenter + * The datacenter. + * @return Default datacenter limits of the enterprise for the given + * datacenter. + * @see API: http://community.abiquo.com/display/ABI20/Datacenter+Limits+ + * Resource# + * DatacenterLimitsResource-CreateanewLimitforanenterpriseinadatacenter + * + */ + public Limits allowDatacenter(final Datacenter datacenter) { + DatacenterLimitsDto dto; + + try { + // Create new limits + Limits limits = Limits.builder(context).build(); + + // Save new limits + dto = context.getApi().getEnterpriseApi().createLimits(target, datacenter.unwrap(), limits.unwrap()); + } catch (AbiquoException ex) { + // Controlled error to allow duplicated authorizations + if (ex.hasError("LIMIT-7")) { + DatacentersLimitsDto limits = context.getApi().getEnterpriseApi().getLimits(target, datacenter.unwrap()); + // Should be only one limit + dto = limits.getCollection().get(0); + } else { + throw ex; + } + } + + return wrap(context, Limits.class, dto); + } + + /** + * Prohibe the given datacenter to be used by this enterprise. Deletes a + * {@link Limits} object. + * + * @param datacenter + * The datacenter. + * @return Default datacenter limits of the enterprise for the given + * datacenter. + * @see API: http://community.abiquo.com/display/ABI20/Datacenter+Limits+ + * Resource# DatacenterLimitsResource- + * Deleteanexistinglimitforanenterpriseinadatacenter + */ + public void prohibitDatacenter(final Datacenter datacenter) { + // Get limits + DatacentersLimitsDto dto = context.getApi().getEnterpriseApi().getLimits(target, datacenter.unwrap()); + + // Delete limits (if any) + if (dto != null && !dto.isEmpty()) { + // Should be only one limit + context.getApi().getEnterpriseApi().deleteLimits(dto.getCollection().get(0)); + } + } + + /** + * Disables chef in the enterprise. + * + * @see API: http://community.abiquo.com/display/ABI20/Enterprise+Resource# + * EnterpriseResource- DisableChefinanexistingEnterprise + */ + public void disableChef() { + target.setChefClient(null); + target.setChefClientCertificate(null); + target.setChefURL(null); + target.setChefValidator(null); + target.setChefValidatorCertificate(null); + update(); + } + + // Builder + + public static Builder builder(final RestContext context) { + return new Builder(context); + } + + public static class Builder extends LimitsBuilder { + private RestContext context; + + private String name; + + protected Long repositorySoft = Long.valueOf(DEFAULT_LIMITS); + + protected Long repositoryHard = Long.valueOf(DEFAULT_LIMITS); + + private Boolean isReservationRestricted = DEFAULT_RESERVATION_RESTRICTED; + + private String chefURL; + + private String chefClient; + + private String chefValidator; + + private String chefApiCertificate; + + private String chefValidatorCertificate; + + public Builder(final RestContext context) { + super(); + this.context = context; + } + + public Builder isReservationRestricted(final boolean isReservationRestricted) { + this.isReservationRestricted = isReservationRestricted; + return this; + } + + public Builder chefURL(final String chefURL) { + this.chefURL = chefURL; + return this; + } + + public Builder chefClient(final String chefClient) { + this.chefClient = chefClient; + return this; + } + + public Builder chefApiCertificate(final String chefApiCertificate) { + this.chefApiCertificate = chefApiCertificate; + return this; + } + + public Builder chefValidator(final String chefValidator) { + this.chefValidator = chefValidator; + return this; + } + + public Builder chefValidatorCertificate(final String chefValidatorCertificate) { + this.chefValidatorCertificate = chefValidatorCertificate; + return this; + } + + public Builder name(final String name) { + this.name = name; + return this; + } + + public Builder repositoryLimits(final long soft, final long hard) { + this.repositorySoft = soft; + this.repositoryHard = hard; + return this; + } + + public Enterprise build() { + EnterpriseDto dto = new EnterpriseDto(); + dto.setName(name); + dto.setRamLimitsInMb(ramSoftLimitInMb, ramHardLimitInMb); + dto.setCpuCountLimits(cpuCountSoftLimit, cpuCountHardLimit); + dto.setHdLimitsInMb(hdSoftLimitInMb, hdHardLimitInMb); + dto.setStorageLimits(storageSoft, storageHard); + dto.setVlansLimits(vlansSoft, vlansHard); + dto.setPublicIPLimits(publicIpsSoft, publicIpsHard); + dto.setRepositoryLimits(repositorySoft, repositoryHard); + dto.setIsReservationRestricted(isReservationRestricted); + dto.setChefClient(chefClient); + dto.setChefClientCertificate(chefApiCertificate); + dto.setChefURL(chefURL); + dto.setChefValidator(chefValidator); + dto.setChefValidatorCertificate(chefValidatorCertificate); + + return new Enterprise(context, dto); + } + + public static Builder fromEnterprise(final Enterprise in) { + return Enterprise.builder(in.context).name(in.getName()) + .ramLimits(in.getRamSoftLimitInMb(), in.getRamHardLimitInMb()) + .cpuCountLimits(in.getCpuCountSoftLimit(), in.getCpuCountHardLimit()) + .hdLimitsInMb(in.getHdSoftLimitInMb(), in.getHdHardLimitInMb()) + .storageLimits(in.getStorageSoft(), in.getStorageHard()) + .vlansLimits(in.getVlansSoft(), in.getVlansHard()) + .publicIpsLimits(in.getPublicIpsSoft(), in.getPublicIpsHard()) + .repositoryLimits(in.getRepositorySoft(), in.getRepositoryHard()) + .isReservationRestricted(in.getIsReservationRestricted()).chefClient(in.getChefClient()) + .chefApiCertificate(in.getChefApiCertificate()).chefURL(in.getChefURL()) + .chefValidator(in.getChefValidator()).chefValidatorCertificate(in.getChefValidatorCertificate()); + } + } + + // Delegate methods + + public Integer getId() { + return target.getId(); + } + + public boolean getIsReservationRestricted() { + return target.getIsReservationRestricted(); + } + + public String getName() { + return target.getName(); + } + + public long getRepositoryHard() { + return target.getRepositoryHard(); + } + + public long getRepositorySoft() { + return target.getRepositorySoft(); + } + + public void setIsReservationRestricted(final boolean isReservationRestricted) { + target.setIsReservationRestricted(isReservationRestricted); + } + + public void setName(final String name) { + target.setName(name); + } + + public void setRepositoryHard(final long repositoryHard) { + target.setRepositoryHard(repositoryHard); + } + + public void setRepositoryLimits(final long soft, final long hard) { + target.setRepositoryLimits(soft, hard); + } + + public void setRepositorySoft(final long repositorySoft) { + target.setRepositorySoft(repositorySoft); + } + + public String getChefClient() { + return target.getChefClient(); + } + + public String getChefApiCertificate() { + return target.getChefClientCertificate(); + } + + public String getChefURL() { + return target.getChefURL(); + } + + public String getChefValidator() { + return target.getChefValidator(); + } + + public String getChefValidatorCertificate() { + return target.getChefValidatorCertificate(); + } + + public void setChefClient(final String chefClient) { + target.setChefClient(chefClient); + } + + public void setChefClientCertificate(final String chefClientCertificate) { + target.setChefClientCertificate(chefClientCertificate); + } + + public void setChefURL(final String chefURL) { + target.setChefURL(chefURL); + } + + public void setChefValidator(final String chefValidator) { + target.setChefValidator(chefValidator); + } + + public void setChefValidatorCertificate(final String chefValidatorCertificate) { + target.setChefValidatorCertificate(chefValidatorCertificate); + } + + @Override + public String toString() { + return "Enterprise [id=" + getId() + ", isReservationRestricted=" + getIsReservationRestricted() + ", name=" + + getName() + "]"; + } + + private DatacenterLimitsDto getLimits(final Datacenter datacenter) { + DatacentersLimitsDto limits = context.getApi().getEnterpriseApi().listLimits(target); + + return Iterables.find(limits.getCollection(), new Predicate() { + @Override + public boolean apply(final DatacenterLimitsDto input) { + RESTLink datacenterLink = input.searchLink("datacenter"); + return datacenterLink != null + && datacenterLink.getHref().equals(datacenter.unwrap().getEditLink().getHref()); + } + }); + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/enterprise/EnterpriseProperties.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/enterprise/EnterpriseProperties.java new file mode 100644 index 0000000000..897c49b43b --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/enterprise/EnterpriseProperties.java @@ -0,0 +1,85 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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.abiquo.domain.enterprise; + +import java.util.Map; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.domain.DomainWrapper; +import org.jclouds.abiquo.reference.annotations.EnterpriseEdition; +import org.jclouds.abiquo.reference.rest.ParentLinkName; +import org.jclouds.rest.RestContext; + +import com.abiquo.server.core.enterprise.EnterprisePropertiesDto; + +/** + * Adds high level functionality to {@link EnterprisePropertiesDto}. + * + * @author Francesc Montserrat + * @see API: + * http://community.abiquo.com/display/ABI20/Enterprise+Properties+Resource + * + */ +@EnterpriseEdition +public class EnterpriseProperties extends DomainWrapper { + /** + * Constructor to be used only by the builder. + */ + protected EnterpriseProperties(final RestContext context, + final EnterprisePropertiesDto target) { + super(context, target); + } + + // Domain operations + /** + * @see API: http://community.abiquo.com/display/ABI20/Enterprise+Properties+ + * Resource# + * EnterprisePropertiesResource-UpdatesthepropertiesforanEnterprise + */ + public void update() { + target = context.getApi().getEnterpriseApi().updateEnterpriseProperties(target); + } + + // Parent access + /** + * @see API: http://community.abiquo.com/display/ABI20/Enterprise+Resource# + * EnterpriseResource- RetrieveaEnterprise + */ + public Enterprise getEnterprise() { + Integer enterpriseId = target.getIdFromLink(ParentLinkName.ENTERPRISE); + return wrap(context, Enterprise.class, context.getApi().getEnterpriseApi().getEnterprise(enterpriseId)); + } + + // Delegate methods + public Map getProperties() { + return target.getProperties(); + } + + public void setProperties(final Map properties) { + target.setProperties(properties); + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/enterprise/Limits.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/enterprise/Limits.java new file mode 100644 index 0000000000..bf2fa20ef0 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/enterprise/Limits.java @@ -0,0 +1,151 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.enterprise; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.domain.DomainWithLimitsWrapper; +import org.jclouds.abiquo.domain.builder.LimitsBuilder; +import org.jclouds.rest.RestContext; + +import com.abiquo.server.core.enterprise.DatacenterLimitsDto; + +/** + * Adds high level functionality to {@link DatacenterLimitsDto}. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + * @see API: + * http://community.abiquo.com/display/ABI20/Datacenter+Limits+Resource + */ +public class Limits extends DomainWithLimitsWrapper { + /** + * Constructor to be used only by the builder. + */ + protected Limits(final RestContext context, final DatacenterLimitsDto target) { + super(context, target); + } + + // Domain operations + + /** + * @see API: + * http://community.abiquo.com/display/ABI20/Datacenter+Limits+Resource + * #DatacenterLimitsResource + * -UpdatesanexistingLimitforanenterpriseinadatacenter + */ + public void update() { + target = context.getApi().getEnterpriseApi().updateLimits(target); + } + + // Builder + + public static Builder builder(final RestContext context) { + return new Builder(context); + } + + public static class Builder extends LimitsBuilder { + private RestContext context; + + protected Long repositorySoft = Long.valueOf(DEFAULT_LIMITS); + + protected Long repositoryHard = Long.valueOf(DEFAULT_LIMITS); + + public Builder(final RestContext context) { + super(); + this.context = context; + } + + public Builder repositoryLimits(final long soft, final long hard) { + this.repositorySoft = soft; + this.repositoryHard = hard; + return this; + } + + public Limits build() { + DatacenterLimitsDto dto = new DatacenterLimitsDto(); + dto.setRamLimitsInMb(ramSoftLimitInMb, ramHardLimitInMb); + dto.setCpuCountLimits(cpuCountSoftLimit, cpuCountHardLimit); + dto.setHdLimitsInMb(hdSoftLimitInMb, hdHardLimitInMb); + dto.setStorageLimits(storageSoft, storageHard); + dto.setVlansLimits(vlansSoft, vlansHard); + dto.setPublicIPLimits(publicIpsSoft, publicIpsHard); + dto.setRepositoryHardLimitsInMb(repositoryHard); + dto.setRepositorySoftLimitsInMb(repositorySoft); + + Limits limits = new Limits(context, dto); + + return limits; + } + + public static Builder fromEnterprise(final Limits in) { + return Limits.builder(in.context).ramLimits(in.getRamSoftLimitInMb(), in.getRamHardLimitInMb()) + .cpuCountLimits(in.getCpuCountSoftLimit(), in.getCpuCountHardLimit()) + .hdLimitsInMb(in.getHdSoftLimitInMb(), in.getHdHardLimitInMb()) + .storageLimits(in.getStorageSoft(), in.getStorageHard()) + .vlansLimits(in.getVlansSoft(), in.getVlansHard()) + .publicIpsLimits(in.getPublicIpsSoft(), in.getPublicIpsHard()) + .repositoryLimits(in.getRepositorySoft(), in.getRepositoryHard()); + } + } + + // Delegate methods + + public Integer getId() { + return target.getId(); + } + + public long getRepositoryHard() { + return target.getRepositoryHardLimitsInMb(); + } + + public long getRepositorySoft() { + return target.getRepositorySoftLimitsInMb(); + } + + public void setRepositoryHard(final long repositoryHard) { + target.setRepositoryHardLimitsInMb(repositoryHard); + } + + public void setRepositoryLimits(final long soft, final long hard) { + target.setRepositoryHardLimitsInMb(hard); + target.setRepositorySoftLimitsInMb(soft); + } + + public void setRepositorySoft(final long repositorySoft) { + target.setRepositorySoftLimitsInMb(repositorySoft); + } + + @Override + public String toString() { + return "Limits [id=" + getId() + ", repositoryHard=" + getRepositoryHard() + ", repositorySoft=" + + getRepositorySoft() + ", cpuCounthard=" + getCpuCountHardLimit() + ", cpuCountSoft=" + + getCpuCountSoftLimit() + ", hdHardInMB=" + getHdHardLimitInMb() + ", hdSoftInMB=" + getHdSoftLimitInMb() + + ", publicIPsHard=" + getPublicIpsHard() + ", publicIpsSoft=" + getPublicIpsSoft() + ", ramHardInMB=" + + getRamHardLimitInMb() + ", ramSoftInMB=" + getRamSoftLimitInMb() + ", storageHard=" + getStorageHard() + + ", storageSoft=" + getStorageSoft() + ", vlansHard=" + getVlansHard() + ", vlansSoft=" + getVlansSoft() + + "]"; + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/enterprise/Role.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/enterprise/Role.java new file mode 100644 index 0000000000..b77c560bf9 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/enterprise/Role.java @@ -0,0 +1,223 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.enterprise; + +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.collect.Iterables.filter; + +import java.util.List; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.domain.DomainWrapper; +import org.jclouds.abiquo.domain.config.Privilege; +import org.jclouds.abiquo.reference.ValidationErrors; +import org.jclouds.abiquo.reference.annotations.EnterpriseEdition; +import org.jclouds.rest.RestContext; + +import com.abiquo.model.rest.RESTLink; +import com.abiquo.server.core.enterprise.PrivilegesDto; +import com.abiquo.server.core.enterprise.RoleDto; +import com.google.common.base.Predicate; +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; + +/** + * Adds high level functionality to {@link RoleDto}. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + * @see API: + * http://community.abiquo.com/display/ABI20/Roles+Resource + */ +public class Role extends DomainWrapper { + /** Default active value of the user */ + private static final boolean DEFAULT_BLOCKED = false; + + /** + * Constructor to be used only by the builder. + */ + protected Role(final RestContext context, final RoleDto target) { + super(context, target); + } + + // Domain operations + + /** + * @see API: + * http://community.abiquo.com/display/ABI20/Roles+Resource#RolesResource + * -DeleteanexistingRole + */ + public void delete() { + context.getApi().getAdminApi().deleteRole(target); + target = null; + } + + /** + * @see API: http + * ://community.abiquo.com/display/ABI20/Roles+Resource#RolesResource + * -CreateanewRole + */ + public void save() { + target = context.getApi().getAdminApi().createRole(target); + } + + /** + * @see API: + * http://community.abiquo.com/display/ABI20/Roles+Resource#RolesResource + * -UpdateanexistingRole + */ + public void update() { + target = context.getApi().getAdminApi().updateRole(target); + } + + public void setEnterprise(final Enterprise enterprise) { + checkNotNull(enterprise, ValidationErrors.NULL_RESOURCE + Enterprise.class); + checkNotNull(enterprise.getId(), ValidationErrors.MISSING_REQUIRED_FIELD + " id in " + Enterprise.class); + + RESTLink link = enterprise.unwrap().searchLink("edit"); + + checkNotNull(link, ValidationErrors.MISSING_REQUIRED_LINK); + + target.addLink(new RESTLink("enterprise", link.getHref())); + } + + @EnterpriseEdition + public void setPrivileges(final List privileges) { + for (Privilege privilege : privileges) { + addPrivilege(privilege); + } + } + + @EnterpriseEdition + private void addPrivilege(final Privilege privilege) { + checkNotNull(privilege, ValidationErrors.NULL_RESOURCE + Privilege.class); + checkNotNull(privilege.getId(), ValidationErrors.MISSING_REQUIRED_FIELD + " id in " + Privilege.class); + + RESTLink link = privilege.unwrap().searchLink("self"); + + // rel would be "privilege" if the object is coming from a privilege list. + if (link == null) { + link = privilege.unwrap().searchLink("privilege"); + } + + checkNotNull(link, ValidationErrors.MISSING_REQUIRED_LINK); + + target.addLink(new RESTLink("privilege" + privilege.getId(), link.getHref())); + } + + // Children access + + /** + * @see API: http://community.abiquo.com/display/ABI20/Roles+Resource# + * RolesResource- RetrievealistofprivilegesfromaRole + */ + public List listPrivileges() { + PrivilegesDto dto = context.getApi().getAdminApi().listPrivileges(target); + + return wrap(context, Privilege.class, dto.getCollection()); + } + + public List listPrivileges(final Predicate filter) { + return Lists.newLinkedList(filter(listPrivileges(), filter)); + } + + public Privilege findPrivileges(final Predicate filter) { + return Iterables.getFirst(filter(listPrivileges(), filter), null); + } + + // Builder + + public static Builder builder(final RestContext context) { + return new Builder(context); + } + + public static class Builder { + private RestContext context; + + private String name; + + private boolean blocked = DEFAULT_BLOCKED; + + public Builder(final RestContext context) { + super(); + this.context = context; + } + + public Builder name(final String name) { + this.name = name; + return this; + } + + public Builder blocked(final boolean blocked) { + this.blocked = blocked; + return this; + } + + public Role build() { + RoleDto dto = new RoleDto(); + dto.setName(name); + dto.setBlocked(blocked); + Role role = new Role(context, dto); + + return role; + } + + public static Builder fromRole(final Role in) { + return Role.builder(in.context).blocked(in.isBlocked()).name(in.getName()); + } + } + + // Delegate methods + + public Integer getId() { + return target.getId(); + } + + public String getName() { + return target.getName(); + } + + public boolean isBlocked() { + return target.isBlocked(); + } + + public void setBlocked(final boolean blocked) { + target.setBlocked(blocked); + } + + public void setName(final String name) { + target.setName(name); + } + + @Override + public String toString() { + return "Role [id=" + getId() + ", name=" + getName() + ", blocked=" + isBlocked() + "]"; + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/enterprise/TemplateDefinitionList.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/enterprise/TemplateDefinitionList.java new file mode 100644 index 0000000000..c8803a5c06 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/enterprise/TemplateDefinitionList.java @@ -0,0 +1,219 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.enterprise; + +import static com.google.common.collect.Iterables.filter; + +import java.util.List; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.domain.DomainWrapper; +import org.jclouds.abiquo.domain.infrastructure.Datacenter; +import org.jclouds.rest.RestContext; + +import com.abiquo.am.model.TemplatesStateDto; +import com.abiquo.server.core.appslibrary.TemplateDefinitionListDto; +import com.google.common.base.Predicate; +import com.google.common.collect.Lists; + +/** + * Adds high level functionality to {@link TemplateDefinitionListDto}. A + * Template Definition List provides a way to organize multiple Template + * Definitions. A single Template Definition can be shared by many lists. Its + * compatible with ovfindex.xml format. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +public class TemplateDefinitionList extends DomainWrapper { + /** The enterprise where the list belongs. */ + private Enterprise enterprise; + + /** + * Constructor to be used only by the builder. + */ + protected TemplateDefinitionList(final RestContext context, + final TemplateDefinitionListDto target) { + super(context, target); + } + + // Domain operations + + /** + * Delete the template definition list. Deleting the list doesn't delete the + * containing Template Definitions. + * + * @see API: http://community.abiquo.com/display/ABI20/ + * TemplateDefinitionListResource# + * TemplateDefinitionListResource-Deleteatemplatedefinitionlist + */ + public void delete() { + context.getApi().getEnterpriseApi().deleteTemplateDefinitionList(target); + target = null; + } + + /** + * Create a template definition list. All the contained Template Definitions + * will also be created. + * + * @see API: http://community.abiquo.com/display/ABI20/ + * TemplateDefinitionListResource# + * TemplateDefinitionListResource-Createatemplatedefinitionlistr + */ + public void save() { + target = context.getApi().getEnterpriseApi().createTemplateDefinitionList(enterprise.unwrap(), target); + } + + /** + * Update a template definition list with the data from this template + * definition list. + * + * @see API: http://community.abiquo.com/display/ABI20/ + * TemplateDefinitionListResource# + * TemplateDefinitionListResource-Modifyatemplatedefinitionlist + */ + public void update() { + target = context.getApi().getEnterpriseApi().updateTemplateDefinitionList(target); + } + + // Children access + + /** + * Retrieve the list of states of the templates in the template definition + * list in the repository of the given datacenter. Template Definition are + * available sources, but in order to create a Virtual Machine the Definition + * should be downloaded into the Datacenter Repository (NFS filesystem). + * + * @param The + * datacenter in which repository search. + * @see API: http://community.abiquo.com/display/ABI20/ + * TemplateDefinitionListResource# TemplateDefinitionListResource- + * Retrievealistofthestatusofalltemplatestatuslist + */ + public List listStatus(final Datacenter datacenter) { + TemplatesStateDto states = context.getApi().getEnterpriseApi() + .listTemplateListStatus(target, datacenter.unwrap()); + return wrap(context, TemplateState.class, states.getCollection()); + } + + /** + * Retrieve a filtered list of states of the templates in the template + * definition list in the repository of the given datacenter. Template + * Definition are available sources, but in order to create a Virtual Machine + * the Definition should be downloaded into the Datacenter Repository (NFS + * filesystem). + * + * @param filter + * Filter to be applied to the list. + * @param The + * datacenter in which repository search. + * @see API: http://community.abiquo.com/display/ABI20/ + * TemplateDefinitionListResource# TemplateDefinitionListResource- + * Retrievealistofthestatusofalltemplatestatuslist + */ + public List listStatus(final Predicate filter, final Datacenter datacenter) { + return Lists.newLinkedList(filter(listStatus(datacenter), filter)); + } + + // Builder + + public static Builder builder(final RestContext context, final Enterprise enterprise) { + return new Builder(context, enterprise); + } + + public static class Builder { + private RestContext context; + + private Enterprise enterprise; + + private String name; + + private String url; + + public Builder(final RestContext context, final Enterprise enterprise) { + super(); + this.context = context; + this.enterprise = enterprise; + } + + public Builder name(final String name) { + this.name = name; + return this; + } + + public Builder url(final String url) { + this.url = url; + return this; + } + + public TemplateDefinitionList build() { + TemplateDefinitionListDto dto = new TemplateDefinitionListDto(); + dto.setName(name); + dto.setUrl(url); + + TemplateDefinitionList templateList = new TemplateDefinitionList(context, dto); + templateList.enterprise = enterprise; + return templateList; + + } + + public static Builder fromTemplateDefinitionList(final TemplateDefinitionList in) { + return TemplateDefinitionList.builder(in.context, in.enterprise).name(in.getName()).url(in.getUrl()); + } + } + + // Delegate methods + + public Integer getId() { + return target.getId(); + } + + public String getName() { + return target.getName(); + } + + public String getUrl() { + return target.getUrl(); + } + + public void setName(final String name) { + target.setName(name); + } + + public void setUrl(final String url) { + target.setUrl(url); + } + + @Override + public String toString() { + return "TemplateDefinitionList [getId()=" + getId() + ", getName()=" + getName() + ", getUrl()=" + getUrl() + "]"; + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/enterprise/TemplateState.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/enterprise/TemplateState.java new file mode 100644 index 0000000000..31f02a21cc --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/enterprise/TemplateState.java @@ -0,0 +1,72 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.enterprise; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.domain.DomainWrapper; +import org.jclouds.rest.RestContext; + +import com.abiquo.am.model.TemplateStateDto; +import com.abiquo.am.model.TemplateStatusEnumType; + +/** + * Adds high level functionality to {@link TemplateStateDto}. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +public class TemplateState extends DomainWrapper { + /** + * Constructor to be used only by the builder. + */ + protected TemplateState(final RestContext context, final TemplateStateDto target) { + super(context, target); + } + + // Domain operations + + public Double getDownloadingProgress() { + return target.getDownloadingProgress(); + } + + public String getErrorCause() { + return target.getErrorCause(); + } + + public String getMasterOvf() { + return target.getMasterOvf(); + } + + public String getOvfId() { + return target.getOvfId(); + } + + public TemplateStatusEnumType getStatus() { + return target.getStatus(); + } + + @Override + public String toString() { + return "TemplateState [getDownloadingProgress()=" + getDownloadingProgress() + ", getErrorCause()=" + + getErrorCause() + ", getMasterOvf()=" + getMasterOvf() + ", getOvfId()=" + getOvfId() + ", getStatus()=" + + getStatus() + "]"; + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/enterprise/User.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/enterprise/User.java new file mode 100644 index 0000000000..26265123bb --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/enterprise/User.java @@ -0,0 +1,444 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.enterprise; + +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.collect.Iterables.filter; + +import java.util.ArrayList; +import java.util.List; +import java.util.StringTokenizer; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.domain.DomainWrapper; +import org.jclouds.abiquo.domain.cloud.VirtualDatacenter; +import org.jclouds.abiquo.domain.cloud.VirtualMachine; +import org.jclouds.abiquo.reference.ValidationErrors; +import org.jclouds.abiquo.reference.rest.ParentLinkName; +import org.jclouds.abiquo.strategy.cloud.ListVirtualDatacenters; +import org.jclouds.rest.RestContext; + +import com.abiquo.model.rest.RESTLink; +import com.abiquo.server.core.cloud.VirtualMachinesWithNodeExtendedDto; +import com.abiquo.server.core.enterprise.RoleDto; +import com.abiquo.server.core.enterprise.UserDto; +import com.google.common.base.Joiner; +import com.google.common.base.Predicate; +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; + +/** + * Adds high level functionality to {@link UserDto}. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + * @see API: + * http://community.abiquo.com/display/ABI20/Users+Resource + */ +public class User extends DomainWrapper { + /** Default active value of the user */ + private static final boolean DEFAULT_ACTIVE = true; + + /** The default authentication type. */ + private static final String DEFAULT_AUTH_TYPE = "ABIQUO"; + + /** The default locale for the user. */ + private static final String DEFAULT_LOCALE = "en_US"; + + /** The enterprise where the user belongs. */ + private Enterprise enterprise; + + /** Role of the user. */ + private Role role; + + /** + * Constructor to be used only by the builder. + */ + protected User(final RestContext context, final UserDto target) { + super(context, target); + } + + // Domain operations + + /** + * @see API: + * http://community.abiquo.com/display/ABI20/User+resource#Userresource + * -Deleteanexistinguser + */ + public void delete() { + context.getApi().getEnterpriseApi().deleteUser(target); + target = null; + } + + /** + * @see API: + * http://community.abiquo.com/display/ABI20/User+resource#Userresource + * -Createanewuser + */ + public void save() { + // set role link + target.addLink(new RESTLink("role", role.unwrap().getEditLink().getHref())); + target = context.getApi().getEnterpriseApi().createUser(enterprise.unwrap(), target); + } + + /** + * @see API: + * http://community.abiquo.com/display/ABI20/User+resource#Userresource + * -Updatesanexistinguser + */ + public void update() { + // update role link (if exists) + if (role != null) { + target.searchLink("role").setHref(role.unwrap().getEditLink().getHref()); + } + + target = context.getApi().getEnterpriseApi().updateUser(target); + } + + public List listPermitedVirtualDatacenters() { + List ids = extractAvailableDatacenters(); + + // null value means all virtual datacenters all allowed + if (ids.size() == 0) { + return this.getEnterprise().listVirtualDatacenters(); + } + + ListVirtualDatacenters listVirtualDatacenters = context.getUtils().getInjector() + .getInstance(ListVirtualDatacenters.class); + return Lists.newArrayList(listVirtualDatacenters.execute(ids)); + } + + public List listPermitedVirtualDatacenters(final Predicate filter) { + return Lists.newLinkedList(filter(listPermitedVirtualDatacenters(), filter)); + } + + public VirtualDatacenter findPermitedVirtualDatacenter(final Predicate filter) { + return Iterables.getFirst(filter(listPermitedVirtualDatacenters(), filter), null); + } + + /** + * Give access to all virtualdatacenters in the enterprise (requires update). + */ + public void permitAllVirtualDatacenters() { + setAvailableVirtualDatacenters(null); + } + + /** + * Limits user access ONLY to the virtual datacenters in the list. If the + * list is empty, user will get access to all virtual datacenters. + * + * @param vdc + * List of virtual datancers from the user's enterprise. + */ + public void setPermitedVirtualDatacenters(final List vdcs) { + List ids = new ArrayList(); + + for (VirtualDatacenter vdc : vdcs) { + checkNotNull(vdc.getId(), ValidationErrors.MISSING_REQUIRED_FIELD + " id in " + VirtualDatacenter.class); + ids.add(vdc.getId()); + } + + setAvailableVirtualDatacenters(ids); + } + + // Parent access + /** + * @see API: http://community.abiquo.com/display/ABI20/Enterprise+Resource# + * EnterpriseResource- RetrieveaEnterprise + */ + public Enterprise getEnterprise() { + Integer enterpriseId = target.getIdFromLink(ParentLinkName.ENTERPRISE); + return wrap(context, Enterprise.class, context.getApi().getEnterpriseApi().getEnterprise(enterpriseId)); + } + + // Children access + + public Role getRole() { + RoleDto role = context.getApi().getAdminApi().getRole(target); + return wrap(context, Role.class, role); + } + + /** + * @see API: http://community.abiquo.com/display/ABI20/User+resource# + * Userresource- Retrievethelistofvirtualmachinesbyuser + */ + public List listMachines() { + VirtualMachinesWithNodeExtendedDto machines = context.getApi().getEnterpriseApi().listVirtualMachines(target); + return wrap(context, VirtualMachine.class, machines.getCollection()); + } + + public List listMachines(final Predicate filter) { + return Lists.newLinkedList(filter(listMachines(), filter)); + } + + public VirtualMachine findMachine(final Predicate filter) { + return Iterables.getFirst(filter(listMachines(), filter), null); + } + + // Builder + + public static Builder builder(final RestContext context, final Enterprise enterprise, + final Role role) { + return new Builder(context, enterprise, role); + } + + public static class Builder { + private RestContext context; + + private Enterprise enterprise; + + private Role role; + + private String name; + + private String nick; + + private String locale = DEFAULT_LOCALE; + + private String password; + + private String surname; + + private boolean active = DEFAULT_ACTIVE; + + private String email; + + private String description; + + private String authType = DEFAULT_AUTH_TYPE; + + public Builder(final RestContext context, final Enterprise enterprise, final Role role) { + super(); + checkNotNull(enterprise, ValidationErrors.NULL_RESOURCE + Enterprise.class); + checkNotNull(role, ValidationErrors.NULL_RESOURCE + Role.class); + this.context = context; + this.enterprise = enterprise; + this.role = role; + } + + public Builder enterprise(final Enterprise enterprise) { + checkNotNull(enterprise, ValidationErrors.NULL_RESOURCE + Enterprise.class); + this.enterprise = enterprise; + return this; + } + + public Builder role(final Role role) { + this.role = role; + return this; + } + + public Builder name(final String name, final String surname) { + this.name = name; + this.surname = surname; + return this; + } + + public Builder nick(final String nick) { + this.nick = nick; + return this; + } + + public Builder locale(final String locale) { + this.locale = locale; + return this; + } + + public Builder password(final String password) { + this.password = password; + return this; + } + + public Builder active(final boolean active) { + this.active = active; + return this; + } + + public Builder email(final String email) { + this.email = email; + return this; + } + + public Builder description(final String description) { + this.description = description; + return this; + } + + public Builder authType(final String authType) { + this.authType = authType; + return this; + } + + public User build() { + UserDto dto = new UserDto(); + dto.setActive(active); + dto.setAuthType(authType); + dto.setDescription(description); + dto.setEmail(email); + dto.setLocale(locale); + dto.setName(name); + dto.setNick(nick); + dto.setPassword(password); + dto.setSurname(surname); + User user = new User(context, dto); + user.enterprise = enterprise; + user.role = role; + + return user; + } + + public static Builder fromUser(final User in) { + return User.builder(in.context, in.enterprise, in.role).active(in.isActive()).authType(in.getAuthType()) + .description(in.getDescription()).email(in.getEmail()).locale(in.getLocale()) + .name(in.getName(), in.getSurname()).nick(in.getNick()).password(in.getPassword()); + } + } + + // Delegate methods + + public String getAuthType() { + return target.getAuthType(); + } + + public String getDescription() { + return target.getDescription(); + } + + public String getEmail() { + return target.getEmail(); + } + + public Integer getId() { + return target.getId(); + } + + public String getLocale() { + return target.getLocale(); + } + + public String getName() { + return target.getName(); + } + + public String getNick() { + return target.getNick(); + } + + public String getPassword() { + return target.getPassword(); + } + + public String getSurname() { + return target.getSurname(); + } + + public boolean isActive() { + return target.isActive(); + } + + public void setActive(final boolean active) { + target.setActive(active); + } + + public void setAuthType(final String authType) { + target.setAuthType(authType); + } + + public void setDescription(final String description) { + target.setDescription(description); + } + + public void setEmail(final String email) { + target.setEmail(email); + } + + public void setLocale(final String locale) { + target.setLocale(locale); + } + + public void setName(final String name) { + target.setName(name); + } + + public void setNick(final String nick) { + target.setNick(nick); + } + + public void setPassword(final String password) { + target.setPassword(password); + } + + public void setSurname(final String surname) { + target.setSurname(surname); + } + + public void setRole(final Role role) { + this.role = role; + } + + // Aux operations + + /** + * Converts the tokenized String of available virtual datacenters provided in + * the userDto to a list of ids. + */ + private List extractAvailableDatacenters() { + List ids = Lists.newArrayList(); + + if (target.getAvailableVirtualDatacenters() != null) { + + StringTokenizer st = new StringTokenizer(target.getAvailableVirtualDatacenters(), ","); + + while (st.hasMoreTokens()) { + ids.add(Integer.parseInt(st.nextToken())); + } + } + + return ids; + } + + private void setAvailableVirtualDatacenters(final List ids) { + if (ids == null || ids.size() == 0) { + target.setAvailableVirtualDatacenters(""); + } else { + Joiner joiner = Joiner.on(",").skipNulls(); + target.setAvailableVirtualDatacenters(joiner.join(ids)); + } + } + + @Override + public String toString() { + return "User [id=" + getId() + ", role=" + getRole() + ", authType=" + getAuthType() + ", description=" + + getDescription() + ", email=" + getEmail() + ", locale=" + getLocale() + ", name=" + getName() + + ", nick=" + getNick() + ", password=" + getPassword() + ", surname=" + getSurname() + ", active=" + + isActive() + "]"; + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/enterprise/options/EnterpriseOptions.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/enterprise/options/EnterpriseOptions.java new file mode 100644 index 0000000000..f64e95a1a7 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/enterprise/options/EnterpriseOptions.java @@ -0,0 +1,115 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.enterprise.options; + +import org.jclouds.abiquo.domain.options.search.FilterOptions.BaseFilterOptionsBuilder; +import org.jclouds.http.options.BaseHttpRequestOptions; + +/** + * Available options to query enterprises. + * + * @author Francesc Montserrat + */ +public class EnterpriseOptions extends BaseHttpRequestOptions { + public static Builder builder() { + return new Builder(); + } + + @Override + protected Object clone() throws CloneNotSupportedException { + EnterpriseOptions options = new EnterpriseOptions(); + options.queryParameters.putAll(queryParameters); + return options; + } + + public static class Builder extends BaseFilterOptionsBuilder { + private String idPricingTemplate; + + private Boolean included; + + private String filter; + + private Integer page; + + private Integer results; + + private Boolean network; + + public Builder pricingTemplate(final String idPricingTemplate) { + this.idPricingTemplate = idPricingTemplate; + return this; + } + + public Builder included(final boolean included) { + this.included = included; + return this; + } + + public Builder filter(final String filter) { + this.filter = filter; + return this; + } + + public Builder network(final boolean network) { + this.network = network; + return this; + } + + public Builder page(final int page) { + this.page = page; + return this; + } + + public Builder results(final int results) { + this.results = results; + return this; + } + + public EnterpriseOptions build() { + EnterpriseOptions options = new EnterpriseOptions(); + + if (idPricingTemplate != null) { + options.queryParameters.put("idPricingTemplate", String.valueOf(idPricingTemplate)); + } + + if (included != null) { + options.queryParameters.put("included", String.valueOf(included)); + } + + if (filter != null) { + options.queryParameters.put("filter", String.valueOf(filter)); + } + + if (page != null) { + options.queryParameters.put("page", String.valueOf(page)); + } + + if (results != null) { + options.queryParameters.put("numResults", String.valueOf(results)); + } + + if (network != null) { + options.queryParameters.put("network", String.valueOf(network)); + } + + return addFilterOptions(options); + } + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/event/Event.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/event/Event.java new file mode 100644 index 0000000000..d83ac1396e --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/event/Event.java @@ -0,0 +1,321 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.event; + +import java.util.Date; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.domain.DomainWrapper; +import org.jclouds.rest.RestContext; + +import com.abiquo.model.enumerator.SeverityType; +import com.abiquo.server.core.event.EventDto; + +/** + * @author Vivien Mahé + */ +public class Event extends DomainWrapper { + /** + * Constructor to be used only by the builder. + */ + protected Event(final RestContext context, final EventDto target) { + super(context, target); + } + + // Delegate methods + + public Integer getId() { + return target.getId(); + } + + public String getUser() { + return target.getUser(); + } + + public void setUser(final String user) { + target.setUser(user); + } + + public String getStacktrace() { + return target.getStacktrace(); + } + + public void setStacktrace(final String stacktrace) { + target.setStacktrace(stacktrace); + } + + public String getComponent() { + return target.getComponent(); + } + + public void setComponent(final String component) { + target.setComponent(component); + } + + public String getPerformedBy() { + return target.getPerformedBy(); + } + + public void setPerformedBy(final String performedBy) { + target.setPerformedBy(performedBy); + } + + public Integer getIdNetwork() { + return target.getIdNetwork(); + } + + public void setIdNetwork(final Integer idNetwork) { + target.setIdNetwork(idNetwork); + } + + public String getIdVolume() { + return target.getIdVolume(); + } + + public void setIdVolume(final String idVolume) { + target.setIdVolume(idVolume); + } + + public String getStoragePool() { + return target.getStoragePool(); + } + + public void setStoragePool(final String storagePool) { + target.setStoragePool(storagePool); + } + + public Date getTimestamp() { + return target.getTimestamp(); + } + + public void setTimestamp(final Date timestamp) { + target.setTimestamp(timestamp); + } + + public String getVirtualApp() { + return target.getVirtualApp(); + } + + public void setVirtualApp(final String virtualApp) { + target.setVirtualApp(virtualApp); + } + + public String getDatacenter() { + return target.getDatacenter(); + } + + public void setDatacenter(final String datacenter) { + target.setDatacenter(datacenter); + } + + public String getActionPerformed() { + return target.getActionPerformed(); + } + + public void setActionPerformed(final String actionPerformed) { + target.setActionPerformed(actionPerformed); + } + + public Integer getIdVirtualMachine() { + return target.getIdVirtualMachine(); + } + + public void setIdVirtualMachine(final Integer idVirtualMachine) { + target.setIdVirtualMachine(idVirtualMachine); + } + + public String getVirtualDatacenter() { + return target.getVirtualDatacenter(); + } + + public void setVirtualDatacenter(final String virtualDatacenter) { + target.setVirtualDatacenter(virtualDatacenter); + } + + public String getEnterprise() { + return target.getEnterprise(); + } + + public void setEnterprise(final String enterprise) { + target.setEnterprise(enterprise); + } + + public String getStorageSystem() { + return target.getStorageSystem(); + } + + public void setStorageSystem(final String storageSystem) { + target.setStorageSystem(storageSystem); + } + + public Integer getIdPhysicalMachine() { + return target.getIdPhysicalMachine(); + } + + public void setIdPhysicalMachine(final Integer idPhysicalMachine) { + target.setIdPhysicalMachine(idPhysicalMachine); + } + + public SeverityType getSeverity() { + return target.getSeverity(); + } + + public void setSeverity(final SeverityType severity) { + target.setSeverity(severity); + } + + public Integer getIdStorageSystem() { + return target.getIdStorageSystem(); + } + + public void setIdStorageSystem(final Integer idStorageSystem) { + target.setIdStorageSystem(idStorageSystem); + } + + public Integer getIdDatacenter() { + return target.getIdDatacenter(); + } + + public void setIdDatacenter(final Integer idDatacenter) { + target.setIdDatacenter(idDatacenter); + } + + public String getNetwork() { + return target.getNetwork(); + } + + public void setNetwork(final String network) { + target.setNetwork(network); + } + + public String getPhysicalMachine() { + return target.getPhysicalMachine(); + } + + public void setPhysicalMachine(final String physicalMachine) { + target.setPhysicalMachine(physicalMachine); + } + + public String getRack() { + return target.getRack(); + } + + public void setRack(final String rack) { + target.setRack(rack); + } + + public Integer getIdVirtualDatacenter() { + return target.getIdVirtualDatacenter(); + } + + public void setIdVirtualDatacenter(final Integer idVirtualDatacenter) { + target.setIdVirtualDatacenter(idVirtualDatacenter); + } + + public Integer getIdSubnet() { + return target.getIdSubnet(); + } + + public void setIdSubnet(final Integer idSubnet) { + target.setIdSubnet(idSubnet); + } + + public String getVolume() { + return target.getVolume(); + } + + public void setVolume(final String volume) { + target.setVolume(volume); + } + + public String getSubnet() { + return target.getSubnet(); + } + + public void setSubnet(final String subnet) { + target.setSubnet(subnet); + } + + public Integer getIdUser() { + return target.getIdUser(); + } + + public void setIdUser(final Integer idUser) { + target.setIdUser(idUser); + } + + public String getIdStoragePool() { + return target.getIdStoragePool(); + } + + public void setIdStoragePool(final String idStoragePool) { + target.setIdStoragePool(idStoragePool); + } + + public Integer getIdRack() { + return target.getIdRack(); + } + + public void setIdRack(final Integer idRack) { + target.setIdRack(idRack); + } + + public String getVirtualMachine() { + return target.getVirtualMachine(); + } + + public void setVirtualMachine(final String virtualMachine) { + target.setVirtualMachine(virtualMachine); + } + + public Integer getIdVirtualApp() { + return target.getIdVirtualApp(); + } + + public void setIdVirtualApp(final Integer idVirtualApp) { + target.setIdVirtualApp(idVirtualApp); + } + + public Integer getIdEnterprise() { + return target.getIdEnterprise(); + } + + public void setIdEnterprise(final Integer idEnterprise) { + target.setIdEnterprise(idEnterprise); + } + + @Override + public String toString() { + return "Event [id=" + getId() + ", idUser=" + getIdUser() + ", user=" + getUser() + ", idEnterprise=" + + getIdEnterprise() + ", enterprise=" + getEnterprise() + ", actionPerformed=" + getActionPerformed() + + ", component=" + getComponent() + ", idDatacenter=" + getIdDatacenter() + ", datacenter=" + + getDatacenter() + ", idStoragePool=" + getIdStoragePool() + ", storagePool=" + getStoragePool() + + ", idVolume=" + getIdVolume() + ", volume=" + getVolume() + ", idNetwork=" + getIdNetwork() + + ", network=" + getNetwork() + ", idPhysicalMachine=" + getIdPhysicalMachine() + ", physicalMachine=" + + getPhysicalMachine() + ", idRack=" + getIdRack() + ", rack=" + getRack() + ", idStorageSystem=" + + getIdStorageSystem() + ", storageSystem=" + getStorageSystem() + ", idSubnet=" + getIdSubnet() + + ", subnet=" + getSubnet() + ", idVirtualApp=" + getIdVirtualApp() + ", virtualApp=" + getVirtualApp() + + ", idVirtualDatacenter=" + getIdVirtualDatacenter() + ", virtualDatacenter=" + getVirtualDatacenter() + + ", idVirtualMachine=" + getIdVirtualMachine() + ", virtualMachine=" + getVirtualMachine() + + ", stackstrace=" + getStacktrace() + ", performedBy=" + getPerformedBy() + ", severity=" + getSeverity() + + "]"; + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/event/options/EventOptions.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/event/options/EventOptions.java new file mode 100644 index 0000000000..5225f67199 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/event/options/EventOptions.java @@ -0,0 +1,169 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.event.options; + +import java.util.Date; +import java.util.Map; +import java.util.Map.Entry; + +import org.jclouds.abiquo.domain.options.search.FilterOptions.BaseFilterOptionsBuilder; +import org.jclouds.http.options.BaseHttpRequestOptions; + +import com.abiquo.model.enumerator.ComponentType; +import com.abiquo.model.enumerator.EventType; +import com.abiquo.model.enumerator.SeverityType; +import com.google.common.collect.Maps; + +/** + * Available options to query events. + * + * @author Vivien Mahé + */ +public class EventOptions extends BaseHttpRequestOptions { + public static Builder builder() { + return new Builder(); + } + + @Override + protected Object clone() throws CloneNotSupportedException { + EventOptions options = new EventOptions(); + options.queryParameters.putAll(queryParameters); + return options; + } + + public static class Builder extends BaseFilterOptionsBuilder { + private Map filters = Maps.newHashMap(); + + public Builder filters(final Map filters) { + this.filters = filters; + return this; + } + + public Builder severity(final SeverityType severity) { + this.filters.put("severity", severity.name()); + return this; + } + + public Builder component(final ComponentType component) { + this.filters.put("component", component.name()); + return this; + } + + public Builder actionPerformed(final EventType action) { + this.filters.put("actionperformed", action.name()); + return this; + } + + public Builder datacenterName(final String dc) { + this.filters.put("datacenter", dc); + return this; + } + + public Builder rackName(final String rack) { + this.filters.put("rack", rack); + return this; + } + + public Builder physicalMachineName(final String pm) { + this.filters.put("physicalmachine", pm); + return this; + } + + public Builder storageSystemName(final String ss) { + this.filters.put("storagesystem", ss); + return this; + } + + public Builder storagePoolName(final String sp) { + this.filters.put("storagepool", sp); + return this; + } + + public Builder volumeName(final String volume) { + this.filters.put("volume", volume); + return this; + } + + public Builder networkName(final String network) { + this.filters.put("network", network); + return this; + } + + public Builder subnetName(final String subnet) { + this.filters.put("subnet", subnet); + return this; + } + + public Builder enterpriseName(final String ent) { + this.filters.put("enterprise", ent); + return this; + } + + public Builder userName(final String user) { + this.filters.put("user", user); + return this; + } + + public Builder virtualDatacenterName(final String vdc) { + this.filters.put("virtualdatacenter", vdc); + return this; + } + + public Builder virtualAppName(final String vapp) { + this.filters.put("virtualapp", vapp); + return this; + } + + public Builder virtualMachineName(final String vm) { + this.filters.put("virtualMachine", vm); + return this; + } + + public Builder performedBy(final String pb) { + this.filters.put("performedBy", pb); + return this; + } + + public Builder description(final String description) { + this.filters.put("stacktrace", description); + return this; + } + + public Builder dateFrom(final Date date) { + this.filters.put("datefrom", String.valueOf(date.getTime())); + return this; + } + + public Builder dateTo(final Date date) { + this.filters.put("dateTo", String.valueOf(date.getTime())); + return this; + } + + public EventOptions build() { + EventOptions options = new EventOptions(); + + for (Entry filter : filters.entrySet()) { + options.queryParameters.put(filter.getKey(), filter.getValue()); + } + + return addFilterOptions(options); + } + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/exception/AbiquoException.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/exception/AbiquoException.java new file mode 100644 index 0000000000..e3b635c736 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/exception/AbiquoException.java @@ -0,0 +1,117 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.exception; + +import static com.google.common.collect.Iterables.any; +import static com.google.common.collect.Iterables.filter; +import static com.google.common.collect.Iterables.find; +import static org.jclouds.abiquo.predicates.ErrorPredicates.code; + +import java.util.List; + +import javax.ws.rs.core.Response.Status; + +import com.abiquo.model.transport.error.ErrorDto; +import com.abiquo.model.transport.error.ErrorsDto; +import com.google.common.collect.Lists; + +/** + * Abiquo API exception. + * + * @author Francesc Montserrat + * @author Ignasi Barrera + */ +public class AbiquoException extends RuntimeException { + /** Serial UID. */ + private static final long serialVersionUID = 1L; + + /** The HTTP statuc. */ + private Status httpStatus; + + /** The errors. */ + private ErrorsDto errors; + + public AbiquoException(final Status httpStatus, final ErrorsDto errors) { + super(); + this.httpStatus = httpStatus; + this.errors = errors; + } + + /** + * Check if there is an error with the given code. + */ + public boolean hasError(final String code) { + return any(errors.getCollection(), code(code)); + } + + /** + * Find the first error with the given code. + */ + public ErrorDto findError(final String code) { + return find(errors.getCollection(), code(code), null); + } + + /** + * Find all errors with the given code. + */ + public List findErrors(final String code) { + return Lists.newLinkedList(filter(errors.getCollection(), code(code))); + } + + /** + * Get the number of errors. + */ + public int numErrors() { + return errors.getCollection().size(); + } + + /** + * Get the list of all errors. + */ + public List getErrors() { + return errors.getCollection(); + } + + /** + * Get the HTTP status code. + */ + public int getHttpStatusCode() { + return httpStatus.getStatusCode(); + } + + /** + * Get the HTTP status name. + */ + public String getHttpStatusName() { + return httpStatus.getReasonPhrase(); + } + + /** + * Get the HTTP status. + */ + public Status getHttpStatus() { + return httpStatus; + } + + @Override + public String getMessage() { + return errors.toString(); + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/exception/BuilderException.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/exception/BuilderException.java new file mode 100644 index 0000000000..3fea01a0d3 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/exception/BuilderException.java @@ -0,0 +1,61 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.exception; + +/** + * Exception thrown during domain object building. + * + * @author Ignasi Barrera + */ +public class BuilderException extends RuntimeException { + private static final long serialVersionUID = 1L; + + /** + * Creates a {@link BuilderException} with the given message. + * + * @param message + * The message. + */ + public BuilderException(String message) { + super(message); + } + + /** + * Creates a {@link BuilderException} with the given cause. + * + * @param cause + * The cause. + */ + public BuilderException(Throwable cause) { + super(cause); + } + + /** + * Creates a {@link BuilderException} with the given message and cause. + * + * @param message + * The message. + * @param cause + * The cause. + */ + public BuilderException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/exception/WrapperException.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/exception/WrapperException.java new file mode 100644 index 0000000000..911db94e8b --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/exception/WrapperException.java @@ -0,0 +1,67 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.exception; + +import org.jclouds.abiquo.domain.DomainWrapper; + +import com.abiquo.model.transport.SingleResourceTransportDto; + +/** + * Exception thrown during the wrapping process. + * + * @author Ignasi Barrera + */ +public class WrapperException extends RuntimeException { + private static final long serialVersionUID = 1L; + + private Class> wrapperClass; + + private SingleResourceTransportDto target; + + public WrapperException(final Class> wrapperClass, + final SingleResourceTransportDto target, Throwable cause) { + super(cause); + this.wrapperClass = wrapperClass; + this.target = target; + } + + @Override + public String getMessage() { + String msg = "Could not wrap object [" + target + "] in class " + wrapperClass.getName() + ": "; + return msg + super.getMessage(); + } + + public Class> getWrapperClass() { + return wrapperClass; + } + + public void setWrapperClass(Class> wrapperClass) { + this.wrapperClass = wrapperClass; + } + + public SingleResourceTransportDto getTarget() { + return target; + } + + public void setTarget(SingleResourceTransportDto target) { + this.target = target; + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/AbstractPhysicalMachine.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/AbstractPhysicalMachine.java new file mode 100644 index 0000000000..ecfcd49c70 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/AbstractPhysicalMachine.java @@ -0,0 +1,301 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.infrastructure; + +import static com.google.common.collect.Iterables.find; + +import java.util.List; +import java.util.StringTokenizer; + +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.domain.DomainWrapper; +import org.jclouds.abiquo.predicates.infrastructure.DatastorePredicates; +import org.jclouds.rest.RestContext; + +import com.abiquo.model.enumerator.HypervisorType; +import com.abiquo.model.enumerator.MachineIpmiState; +import com.abiquo.model.enumerator.MachineState; +import com.abiquo.server.core.infrastructure.DatastoresDto; +import com.abiquo.server.core.infrastructure.MachineDto; +import com.abiquo.server.core.infrastructure.MachineIpmiStateDto; +import com.abiquo.server.core.infrastructure.MachineStateDto; +import com.google.common.base.Predicates; +import com.google.common.collect.Lists; + +/** + * Adds high level functionality to {@link MachineDto}. This class defines + * common methods for unmanaged {@link Machine} and managed {@link Blade} + * physical machines. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + * @see API: + * http://community.abiquo.com/display/ABI20/MachineResource + */ +public abstract class AbstractPhysicalMachine extends DomainWrapper { + /** The default virtual ram used in MB. */ + protected static final int DEFAULT_VRAM_USED = 1; + + /** The default virtual cpu used in MB. */ + protected static final int DEFAULT_VCPU_USED = 1; + + /** List of available virtual switches provided by discover operation **/ + protected List virtualSwitches; + + /** + * Constructor to be used only by the builder. + */ + protected AbstractPhysicalMachine(final RestContext context, final MachineDto target) { + super(context, target); + extractVirtualSwitches(); + } + + public void delete() { + context.getApi().getInfrastructureApi().deleteMachine(target); + target = null; + } + + public void update() { + target = context.getApi().getInfrastructureApi().updateMachine(target); + } + + public MachineState check() { + MachineStateDto dto = context.getApi().getInfrastructureApi().checkMachineState(target, true); + MachineState state = dto.getState(); + target.setState(state); + return state; + } + + public MachineIpmiState checkIpmi() { + MachineIpmiStateDto dto = context.getApi().getInfrastructureApi().checkMachineIpmiState(target); + return dto.getState(); + } + + // Children access + + public List getDatastores() { + return wrap(context, Datastore.class, target.getDatastores().getCollection()); + } + + public Datastore findDatastore(final String name) { + return find(getDatastores(), DatastorePredicates.name(name), null); + } + + // Delegate methods + + public Integer getId() { + return target.getId(); + } + + public String getIp() { + return target.getIp(); + } + + public String getIpmiIp() { + return target.getIpmiIP(); + } + + public String getIpmiPassword() { + return target.getIpmiPassword(); + } + + public Integer getIpmiPort() { + return target.getIpmiPort(); + } + + public String getIpmiUser() { + return target.getIpmiUser(); + } + + public String getIpService() { + return target.getIpService(); + } + + public String getName() { + return target.getName(); + } + + public String getPassword() { + return target.getPassword(); + } + + public Integer getPort() { + return target.getPort(); + } + + public MachineState getState() { + return target.getState(); + } + + public HypervisorType getType() { + return target.getType(); + } + + public String getUser() { + return target.getUser(); + } + + public Integer getVirtualCpuCores() { + return target.getVirtualCpuCores(); + } + + public Integer getVirtualCpusUsed() { + return target.getVirtualCpusUsed(); + } + + public Integer getVirtualRamInMb() { + return target.getVirtualRamInMb(); + } + + public Integer getVirtualRamUsedInMb() { + return target.getVirtualRamUsedInMb(); + } + + public String getVirtualSwitch() { + return target.getVirtualSwitch(); + } + + public void setDatastores(final List datastores) { + DatastoresDto datastoresDto = new DatastoresDto(); + datastoresDto.getCollection().addAll(DomainWrapper.unwrap(datastores)); + target.setDatastores(datastoresDto); + } + + public void setDescription(final String description) { + target.setDescription(description); + } + + public void setIp(final String ip) { + target.setIp(ip); + } + + public void setIpmiIp(final String ipmiIp) { + target.setIpmiIP(ipmiIp); + } + + public void setIpmiPassword(final String ipmiPassword) { + target.setIpmiPassword(ipmiPassword); + } + + public void setIpmiPort(final Integer ipmiPort) { + target.setIpmiPort(ipmiPort); + } + + public void setIpmiUser(final String ipmiUser) { + target.setIpmiUser(ipmiUser); + } + + public void setIpService(final String ipService) { + target.setIpService(ipService); + } + + public void setName(final String name) { + target.setName(name); + } + + public void setPassword(final String password) { + target.setPassword(password); + } + + public void setPort(final Integer port) { + target.setPort(port); + } + + public void setState(final MachineState state) { + target.setState(state); + } + + public void setType(final HypervisorType type) { + target.setType(type); + } + + public void setUser(final String user) { + target.setUser(user); + } + + public void setVirtualCpuCores(final Integer virtualCpuCores) { + target.setVirtualCpuCores(virtualCpuCores); + } + + public void setVirtualCpusUsed(final Integer virtualCpusUsed) { + target.setVirtualCpusUsed(virtualCpusUsed); + } + + public void setVirtualRamInMb(final Integer virtualRamInMb) { + target.setVirtualRamInMb(virtualRamInMb); + } + + public void setVirtualRamUsedInMb(final Integer virtualRamUsedInMb) { + target.setVirtualRamUsedInMb(virtualRamUsedInMb); + } + + public void setVirtualSwitch(final String virtualSwitch) { + target.setVirtualSwitch(virtualSwitch); + } + + public String getDescription() { + return target.getDescription(); + } + + // Aux operations + + /** + * Converts the tokenized String provided by the node collector API to a list + * of Strings and stores it at the attribute switches. + */ + protected void extractVirtualSwitches() { + StringTokenizer st = new StringTokenizer(getVirtualSwitch(), "/"); + this.virtualSwitches = Lists.newArrayList(); + + while (st.hasMoreTokens()) { + this.virtualSwitches.add(st.nextToken()); + } + + if (virtualSwitches.size() > 0) { + this.setVirtualSwitch(virtualSwitches.get(0)); + } + } + + /** + * Returns the virtual switches available. One of them needs to be selected. + */ + public List getAvailableVirtualSwitches() { + return virtualSwitches; + } + + public String findAvailableVirtualSwitch(final String vswitch) { + return find(virtualSwitches, Predicates.equalTo(vswitch)); + } + + @Override + public String toString() { + return "Machine [id=" + getId() + ", ip=" + getIp() + ", ipmiIp=" + getIpmiIp() + ", ipmiPassword=" + + getIpmiPassword() + ", ipmiPort=" + getIpmiPort() + ", ipmiUser=" + getIpmiUser() + ", ipService=" + + getIpService() + ", name=" + getName() + ", password=" + getPassword() + ", port=" + getPort() + + ", state=" + getState() + ", type=" + getType() + ", user=" + getUser() + ", virtualCpuCores=" + + getVirtualCpuCores() + ", virtualCpusUsed=" + getVirtualCpusUsed() + ", getVirtualRamInMb()=" + + getVirtualRamInMb() + ", virtualRamUsedInMb=" + getVirtualRamUsedInMb() + ", virtualSwitch=" + + getVirtualSwitch() + ", description=" + getDescription() + ", availableVirtualSwitches=" + + getAvailableVirtualSwitches() + "]"; + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/Blade.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/Blade.java new file mode 100644 index 0000000000..b45a0bb926 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/Blade.java @@ -0,0 +1,173 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.infrastructure; + +import static com.google.common.base.Preconditions.checkNotNull; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.reference.ValidationErrors; +import org.jclouds.abiquo.reference.rest.ParentLinkName; +import org.jclouds.abiquo.rest.internal.ExtendedUtils; +import org.jclouds.http.HttpResponse; +import org.jclouds.http.functions.ParseXMLWithJAXB; +import org.jclouds.rest.RestContext; + +import com.abiquo.model.rest.RESTLink; +import com.abiquo.server.core.infrastructure.BladeLocatorLedDto; +import com.abiquo.server.core.infrastructure.LogicServerDto; +import com.abiquo.server.core.infrastructure.MachineDto; +import com.abiquo.server.core.infrastructure.UcsRackDto; +import com.google.inject.TypeLiteral; + +/** + * Adds high level functionality to a {@link MachineDto} managed in a UCS rack. + * This resource allows you to access blades in managed racks in the cloud + * infrastructure. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + * @see API: + * http://community.abiquo.com/display/ABI20/MachineResource + */ +public class Blade extends AbstractPhysicalMachine { + /** The rack where the machine belongs. */ + protected UcsRackDto rack; + + /** + * Constructor to be used only by the builder. + */ + protected Blade(final RestContext context, final MachineDto target) { + super(context, target); + } + + // Parent access + + /** + * Retrieve the UCS rack where the blade is. + * + * @see API: + * http://community.abiquo.com/display/ABI20/RackResource#RackResource- + * RetrieveaUCSRack + */ + public ManagedRack getRack() { + RESTLink link = checkNotNull(target.searchLink(ParentLinkName.RACK), ValidationErrors.MISSING_REQUIRED_LINK + " " + + ParentLinkName.RACK); + + ExtendedUtils utils = (ExtendedUtils) context.getUtils(); + HttpResponse response = utils.getAbiquoHttpClient().get(link); + + ParseXMLWithJAXB parser = new ParseXMLWithJAXB(utils.getXml(), + TypeLiteral.get(UcsRackDto.class)); + + return wrap(context, ManagedRack.class, parser.apply(response)); + } + + /** + * Retrieve the logic server associated with this machine in the Cisco UCS + * rack. + * + * @see API: http://community.abiquo.com/display/ABI20/MachineResource# + * MachineResource- + * RetrieveslogicserverassociatedwithamachineinaCiscoUCS + */ + public LogicServer getLogicServer() { + LogicServerDto server = context.getApi().getInfrastructureApi().getLogicServer(target); + + return wrap(context, LogicServer.class, server); + } + + // Actions + + /** + * Turn the blade associated to the provided logic server off. The blade must + * belong to a Logic Server. This action sets the state of a given machine to + * STOPPED. Also sends a stop request to Cisco UCS to shut down the machine. + * The given machine must be a Physical Machine inside a Cisco UCS. + * + * @see API: http://community.abiquo.com/display/ABI20/MachineResource# + * MachineResource- PoweroffanexistingmachineinCiscoUCS + */ + public void powerOff() { + context.getApi().getInfrastructureApi().powerOff(target); + } + + /** + * Turn the blade associated to the provided logic server on. The machine + * must belong to an UCS Rack. The blade must belong to a Logic Server. + * + * @see API: http://community.abiquo.com/display/ABI20/MachineResource# + * MachineResource- PoweronanexistingmachineinCiscoUCS + */ + public void powerOn() { + context.getApi().getInfrastructureApi().powerOn(target); + } + + /** + * Turn blade led on. The machine must belong to an UCS Rack. The blade must + * belong to a Logic Server. + * + * @see API: http://community.abiquo.com/display/ABI20/MachineResource# + * MachineResource- + * LightoffthelocatorledofanexistingmachineinaCiscoUCS + */ + public void ledOn() { + context.getApi().getInfrastructureApi().ledOn(target); + } + + /** + * Turn blade led off. The machine must belong to an UCS Rack. The blade must + * belong to a Logic Server. + * + * @see API: http://community.abiquo.com/display/ABI20/MachineResource- + * LightoffthelocatorledofanexistingmachineinaCiscoUCS + */ + public void ledOff() { + context.getApi().getInfrastructureApi().ledOff(target); + } + + /** + * Retrieve the led locator information as a {@link BladeLocatorLed}. + * + * @return Blade locator led representation. + * @see API: http://community.abiquo.com/display/ABI20/MachineResource# + * MachineResource- Retrievethelocatorledoftheblade + */ + public BladeLocatorLed getLocatorLed() { + BladeLocatorLedDto led = context.getApi().getInfrastructureApi().getLocatorLed(target); + + return wrap(context, BladeLocatorLed.class, led); + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/BladeLocatorLed.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/BladeLocatorLed.java new file mode 100644 index 0000000000..65d8f7a371 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/BladeLocatorLed.java @@ -0,0 +1,73 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.infrastructure; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.domain.DomainWrapper; +import org.jclouds.abiquo.reference.annotations.EnterpriseEdition; +import org.jclouds.rest.RestContext; + +import com.abiquo.server.core.infrastructure.BladeLocatorLedDto; + +/** + * Adds high level functionality to {@link BladeLocatorLedDto}. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + * @see API: http://community.abiquo.com/display/ABI20/MachineResource# + * MachineResource- Retrievethelocatorledoftheblade + */ +@EnterpriseEdition +public class BladeLocatorLed extends DomainWrapper { + /** + * Constructor to be used only by the builder. + */ + protected BladeLocatorLed(final RestContext context, final BladeLocatorLedDto target) { + super(context, target); + } + + // Delegate Methods + + public String getAdminStatus() { + return target.getAdminStatus(); + } + + public String getBladeDn() { + return target.getBladeDn(); + } + + public String getColor() { + return target.getColor(); + } + + public String getDn() { + return target.getDn(); + } + + @Override + public String toString() { + return "BladeLocatorLed [Dn=" + getDn() + ", BladeDn=" + getBladeDn() + ", Color=" + getColor() + + ", AdminStatus=" + getAdminStatus() + "]"; + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/Datacenter.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/Datacenter.java new file mode 100644 index 0000000000..4d3bc6d427 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/Datacenter.java @@ -0,0 +1,1204 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.infrastructure; + +import static com.google.common.collect.Iterables.filter; + +import java.util.List; + +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.config.AbiquoEdition; +import org.jclouds.abiquo.domain.DomainWrapper; +import org.jclouds.abiquo.domain.cloud.VirtualMachineTemplate; +import org.jclouds.abiquo.domain.enterprise.Enterprise; +import org.jclouds.abiquo.domain.enterprise.Limits; +import org.jclouds.abiquo.domain.infrastructure.options.DatacenterOptions; +import org.jclouds.abiquo.domain.infrastructure.options.IpmiOptions; +import org.jclouds.abiquo.domain.infrastructure.options.MachineOptions; +import org.jclouds.abiquo.domain.network.Network; +import org.jclouds.abiquo.domain.network.options.NetworkOptions; +import org.jclouds.abiquo.reference.annotations.EnterpriseEdition; +import org.jclouds.rest.RestContext; + +import com.abiquo.model.enumerator.HypervisorType; +import com.abiquo.model.enumerator.MachineIpmiState; +import com.abiquo.model.enumerator.MachineState; +import com.abiquo.model.enumerator.NetworkType; +import com.abiquo.model.enumerator.RemoteServiceType; +import com.abiquo.model.enumerator.VlanTagAvailabilityType; +import com.abiquo.server.core.appslibrary.VirtualMachineTemplateDto; +import com.abiquo.server.core.appslibrary.VirtualMachineTemplatesDto; +import com.abiquo.server.core.cloud.HypervisorTypeDto; +import com.abiquo.server.core.cloud.HypervisorTypesDto; +import com.abiquo.server.core.enterprise.DatacentersLimitsDto; +import com.abiquo.server.core.infrastructure.DatacenterDto; +import com.abiquo.server.core.infrastructure.MachineDto; +import com.abiquo.server.core.infrastructure.MachineIpmiStateDto; +import com.abiquo.server.core.infrastructure.MachineStateDto; +import com.abiquo.server.core.infrastructure.MachinesDto; +import com.abiquo.server.core.infrastructure.RackDto; +import com.abiquo.server.core.infrastructure.RacksDto; +import com.abiquo.server.core.infrastructure.RemoteServicesDto; +import com.abiquo.server.core.infrastructure.UcsRackDto; +import com.abiquo.server.core.infrastructure.UcsRacksDto; +import com.abiquo.server.core.infrastructure.network.VLANNetworkDto; +import com.abiquo.server.core.infrastructure.network.VLANNetworksDto; +import com.abiquo.server.core.infrastructure.network.VlanTagAvailabilityDto; +import com.abiquo.server.core.infrastructure.storage.StorageDeviceDto; +import com.abiquo.server.core.infrastructure.storage.StorageDevicesDto; +import com.abiquo.server.core.infrastructure.storage.StorageDevicesMetadataDto; +import com.abiquo.server.core.infrastructure.storage.TiersDto; +import com.google.common.base.Predicate; +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; + +/** + * Adds high level functionality to {@link DatacenterDto}. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + * @see API: + * http://community.abiquo.com/display/ABI20/DatacenterResource + */ +public class Datacenter extends DomainWrapper { + /** + * IP address of the datacenter (used to create all remote services with the + * same ip). + */ + private String ip; + + /** + * Indicates the Abiquo edition to create the available remote services. + * + * @see API: + * http://community.abiquo.com/display/ABI20/Introduction+-+The+Abiquo+ + * Platform + */ + private AbiquoEdition edition; + + /** + * Constructor to be used only by the builder. + */ + protected Datacenter(final RestContext context, final DatacenterDto target) { + super(context, target); + } + + // Domain operations + + /** + * Delete the datacenter. + * + * @see API: http://community.abiquo.com/display/ABI20/DatacenterResource# + * DatacenterResource- DeleteanexistingDatacenter + */ + public void delete() { + context.getApi().getInfrastructureApi().deleteDatacenter(target); + target = null; + } + + /** + * Create a datacenter in Abiquo. This method will perform several calls to + * the API if remote services have been defined in the builder. Different + * remote services will be created depending on the {@link AbiquoEdition}. + * + * @see API: http://community.abiquo.com/display/ABI20/DatacenterResource# + * DatacenterResource- CreateanewDatacenter + * @see API: http://community.abiquo.com/display/ABI20/RemoteServiceResource# + * RemoteServiceResource- CreateaRemoteService + */ + public void save() { + // Datacenter must be persisted first, so links get populated in the + // target object + target = context.getApi().getInfrastructureApi().createDatacenter(target); + + // If remote services data is set, create remote services. + if (ip != null && edition != null) { + createRemoteServices(); + } + } + + /** + * Update datacenter information in the server with the data from this + * datacenter. + * + * @see API: http://community.abiquo.com/display/ABI20/DatacenterResource# + * DatacenterResource- Updateanexistingdatacenter + */ + public void update() { + target = context.getApi().getInfrastructureApi().updateDatacenter(target); + } + + /** + * The cloud administrator will find it useful to know if a VLAN Tag is + * already assigned before creating a new Public or External Network. This + * method provides this functionality: Check if a tag is available inside the + * Datacenter. Please refer link for more information. + * + * @see API: http://community.abiquo.com/display/ABI20/PublicNetworkResource# + * PublicNetworkResource- Checkthetagavailability + * @return Availability state of the tag. + */ + public VlanTagAvailabilityType checkTagAvailability(final int tag) { + VlanTagAvailabilityDto availability = context.getApi().getInfrastructureApi().checkTagAvailability(target, tag); + + return availability.getAvailable(); + } + + // Children access + + /** + * Retrieve the list of unmanaged racks in this datacenter. + * + * @see API: http://community.abiquo.com/display/ABI20/RackResource#RackResource + * - RetrievealistofRacks + * @return List of unmanaged racks in this datacenter. + */ + public List listRacks() { + RacksDto racks = context.getApi().getInfrastructureApi().listRacks(target); + return wrap(context, Rack.class, racks.getCollection()); + } + + /** + * Retrieve a filtered list of unmanaged racks in this datacenter. + * + * @param filter + * Filter to be applied to the list. + * @see API: http://community.abiquo.com/display/ABI20/RackResource#RackResource + * - RetrievealistofRacks + * @return Filtered list of unmanaged racks in this datacenter. + */ + public List listRacks(final Predicate filter) { + return Lists.newLinkedList(filter(listRacks(), filter)); + } + + /** + * Retrieve the first unmanaged rack matching the filter within the list of + * racks in this datacenter. + * + * @param filter + * Filter to be applied to the list. + * @see API: http://community.abiquo.com/display/ABI20/RackResource#RackResource + * - RetrievealistofRacks + * @return First unmanaged rack matching the filter or null if + * the is none. + */ + public Rack findRack(final Predicate filter) { + return Iterables.getFirst(filter(listRacks(), filter), null); + } + + /** + * Retrieve a single unmanaged rack. + * + * @param id + * Unique ID of the rack in this datacenter. + * @see API: + * http://community.abiquo.com/display/ABI20/RackResource#RackResource- + * RetrieveaRack + * @return Unmanaged rack with the given id or null if it does + * not exist. + */ + public Rack getRack(final Integer id) { + RackDto rack = context.getApi().getInfrastructureApi().getRack(target, id); + return wrap(context, Rack.class, rack); + } + + /** + * Retrieve the list of managed racks in this datacenter. + * + * @see API: http://community.abiquo.com/display/ABI20/RackResource#RackResource + * - RetrievealistofUCSracks + * @return List of managed racks in this datacenter. + */ + @EnterpriseEdition + public List listManagedRacks() { + UcsRacksDto racks = context.getApi().getInfrastructureApi().listManagedRacks(target); + return wrap(context, ManagedRack.class, racks.getCollection()); + } + + /** + * Retrieve a filtered list of managed racks in this datacenter. + * + * @param filter + * Filter to be applied to the list. + * @see API: http://community.abiquo.com/display/ABI20/RackResource#RackResource + * - RetrievealistofUCSracks + * @return Filtered list of managed racks in this datacenter. + */ + @EnterpriseEdition + public List listManagedRacks(final Predicate filter) { + return Lists.newLinkedList(filter(listManagedRacks(), filter)); + } + + /** + * Retrieve the first managed rack matching the filter within the list of + * racks in this datacenter. + * + * @param filter + * Filter to be applied to the list. + * @see API: http://community.abiquo.com/display/ABI20/RackResource#RackResource + * - RetrievealistofUCSracks + * @return First managed rack matching the filter or null if + * there is none. + */ + @EnterpriseEdition + public ManagedRack findManagedRack(final Predicate filter) { + return Iterables.getFirst(filter(listManagedRacks(), filter), null); + } + + /** + * Retrieve a single managed rack. + * + * @param id + * Unique ID of the rack in this datacenter. + * @see API: + * http://community.abiquo.com/display/ABI20/RackResource#RackResource- + * RetrieveaUCSRack + * @return Unmanaged rack with the given id or null if it does + * not exist. + */ + @EnterpriseEdition + public ManagedRack getManagedRack(final Integer id) { + UcsRackDto rack = context.getApi().getInfrastructureApi().getManagedRack(target, id); + return wrap(context, ManagedRack.class, rack); + } + + /** + * Retrieve the list of supported storage devices. + *

+ * This method will get the list of the storage devices that are supported in + * the datacenter. + * + * @return List of supported storage devices. This list has only the default + * information for the storage devices, such as the management and + * iscsi ports, or the default credentials to access the device. + */ + @EnterpriseEdition + public List listSupportedStorageDevices() { + StorageDevicesMetadataDto devices = context.getApi().getInfrastructureApi().listSupportedStorageDevices(target); + return wrap(context, StorageDeviceMetadata.class, devices.getCollection()); + } + + /** + * Retrieve the list of supported storage devices matching the filter. + *

+ * This method will get the list of the storage devices that are supported in + * the datacenter. + * + * @param filter + * Filter to be applied to the list. + * @return List of supported storage devices. This list has only the default + * information for the storage devices, such as the management and + * iscsi ports, or the default credentials to access the device. + */ + @EnterpriseEdition + public List listSupportedStorageDevices(final Predicate filter) { + return Lists.newLinkedList(filter(listSupportedStorageDevices(), filter)); + } + + /** + * Retrieve a single supported storage devices matching the filter. + * + * @param filter + * Filter to be applied to the list. + * @return First supported storage device matching the filter or + * null if there is none. + */ + @EnterpriseEdition + public StorageDeviceMetadata findSupportedStorageDevice(final Predicate filter) { + return Iterables.getFirst(filter(listSupportedStorageDevices(), filter), null); + } + + /** + * Retrieve the list of storage devices in this datacenter. + * + * @see API: http://community.abiquo.com/display/ABI20/StorageDeviceResource# + * StorageDeviceResource- Retrievethelistofstoragedevices + * @return List of storage devices in this datacenter. + */ + @EnterpriseEdition + public List listStorageDevices() { + StorageDevicesDto devices = context.getApi().getInfrastructureApi().listStorageDevices(target); + return wrap(context, StorageDevice.class, devices.getCollection()); + } + + /** + * Retrieve a filtered list of storage devices in this datacenter. + * + * @param filter + * Filter to be applied to the list. + * @see API: http://community.abiquo.com/display/ABI20/StorageDeviceResource# + * StorageDeviceResource- Retrievethelistofstoragedevices + * @return Filtered list of storage devices in this datacenter. + */ + @EnterpriseEdition + public List listStorageDevices(final Predicate filter) { + return Lists.newLinkedList(filter(listStorageDevices(), filter)); + } + + /** + * Retrieve the first storage device matching the filter within the list of + * devices in this datacenter. + * + * @param filter + * Filter to be applied to the list. + * @see API: http://community.abiquo.com/display/ABI20/StorageDeviceResource# + * StorageDeviceResource- Retrievethelistofstoragedevices + * @return First storage device matching the filter or null if + * there is none. + */ + @EnterpriseEdition + public StorageDevice findStorageDevice(final Predicate filter) { + return Iterables.getFirst(filter(listStorageDevices(), filter), null); + } + + /** + * Retrieve a single storage device. + * + * @param id + * Unique ID of the storage device in this datacenter. + * @see API: http://community.abiquo.com/display/ABI20/StorageDeviceResource# + * StorageDeviceResource- Retrieveastoragedevice + * @return Storage device with the given id or null if it does + * not exist. + */ + @EnterpriseEdition + public StorageDevice getStorageDevice(final Integer id) { + StorageDeviceDto device = context.getApi().getInfrastructureApi().getStorageDevice(target, id); + return wrap(context, StorageDevice.class, device); + } + + /** + * Retrieve the list of remote services of this datacenter. + * + * @see API: http://community.abiquo.com/display/ABI20/RemoteServiceResource# + * RemoteServiceResource- RetrievealistofRemoteServices + * @return List of remote services in this datacenter. + */ + public List listRemoteServices() { + RemoteServicesDto remoteServices = context.getApi().getInfrastructureApi().listRemoteServices(target); + return wrap(context, RemoteService.class, remoteServices.getCollection()); + } + + /** + * Retrieve a filtered list of remote services of this datacenter. + * + * @param filter + * Filter to be applied to the list. + * @see API: http://community.abiquo.com/display/ABI20/RemoteServiceResource# + * RemoteServiceResource- RetrievealistofRemoteServices + * @return Filtered list of remote services in this datacenter. + */ + public List listRemoteServices(final Predicate filter) { + return Lists.newLinkedList(filter(listRemoteServices(), filter)); + } + + /** + * Retrieve the first remote service matching the filter within the list of + * remote services in this datacenter. + * + * @param filter + * Filter to be applied to the list. + * @see API: http://community.abiquo.com/display/ABI20/RemoteServiceResource# + * RemoteServiceResource- RetrievealistofRemoteServices + * @return First remote service matching the filter or null if + * there is none. + */ + public RemoteService findRemoteService(final Predicate filter) { + return Iterables.getFirst(filter(listRemoteServices(), filter), null); + } + + private void createRemoteServices() { + if (this.edition == AbiquoEdition.ENTERPRISE) { + createRemoteService(RemoteServiceType.BPM_SERVICE); + createRemoteService(RemoteServiceType.DHCP_SERVICE); + createRemoteService(RemoteServiceType.STORAGE_SYSTEM_MONITOR); + } + + createRemoteService(RemoteServiceType.APPLIANCE_MANAGER); + createRemoteService(RemoteServiceType.VIRTUAL_SYSTEM_MONITOR); + createRemoteService(RemoteServiceType.NODE_COLLECTOR); + createRemoteService(RemoteServiceType.VIRTUAL_FACTORY); + } + + private void createRemoteService(final RemoteServiceType type) { + RemoteService.builder(context, this).type(type).ip(this.ip).build().save(); + } + + /** + * Retrieve the list of datacenter limits by all enterprises. The Datacenter + * Limits resource allows you to assign datacenters and allocated resources + * in them to be used by an enterprise. + * + * @see API: http://community.abiquo.com/display/ABI20/DatacenterResource# + * DatacenterResource- Retrievelimitsbydatacenter + * @return List of datacenter limits by all enterprises. + */ + public List listLimits() { + DatacentersLimitsDto dto = context.getApi().getInfrastructureApi().listLimits(this.unwrap()); + return DomainWrapper.wrap(context, Limits.class, dto.getCollection()); + } + + /** + * Retrieve a filtered list of datacenter limits by enterprises. The + * Datacenter Limits resource allows you to assign datacenters and allocated + * resources in them to be used by an enterprise. + * + * @param filter + * Filter to be applied to the list. + * @see API: http://community.abiquo.com/display/ABI20/DatacenterResource# + * DatacenterResource- Retrievelimitsbydatacenter + * @return Filtered list of datacenter limits by all enterprises. + */ + public List listLimits(final Predicate filter) { + return Lists.newLinkedList(filter(listLimits(), filter)); + } + + /** + * Retrieve the first datacenter limits matching the filter within the list + * of datacenter limits by enterprise. The Datacenter Limits resource allows + * you to assign datacenters and allocated resources in them to be used by an + * enterprise. + * + * @param filter + * Filter to be applied to the list. + * @see API: http://community.abiquo.com/display/ABI20/DatacenterResource# + * DatacenterResource- Retrievelimitsbydatacenter + * @return First datacenter limits matching the filter or null + * if there is none. + */ + public Limits findLimits(final Predicate filter) { + return Iterables.getFirst(filter(listLimits(), filter), null); + } + + /** + * Retrieve the list of tiers in ths datacenter. + * + * @see API: + * http://community.abiquo.com/display/ABI20/TierResource#TierResource- + * Retrievethelistoftiers + * @return List of tiers in this datacenter. + */ + @EnterpriseEdition + public List listTiers() { + TiersDto dto = context.getApi().getInfrastructureApi().listTiers(this.unwrap()); + return DomainWrapper.wrap(context, Tier.class, dto.getCollection()); + } + + /** + * Retrieve a filtered list of tiers in this datacenter. + * + * @param filter + * Filter to be applied to the list. + * @see API: + * http://community.abiquo.com/display/ABI20/TierResource#TierResource- + * Retrievethelistoftiers + * @return Filtered list of tiers in this datacenter. + */ + @EnterpriseEdition + public List listTiers(final Predicate filter) { + return Lists.newLinkedList(filter(listTiers(), filter)); + } + + /** + * Retrieve the first tier matching the filter within the list of tiers in + * this datacenter. + * + * @param filter + * Filter to be applied to the list. + * @see API: http://community.abiquo.com/display/ABI20/StorageDeviceResource# + * StorageDeviceResource- Retrievethelistofstoragedevices + * @return First tier matching the filter or null if there is + * none. + */ + @EnterpriseEdition + public Tier findTier(final Predicate filter) { + return Iterables.getFirst(filter(listTiers(), filter), null); + } + + /** + * Retrieve the list of public, external and unmanaged networks in this + * datacenter. + * + * @see API: http://community.abiquo.com/display/ABI20/PublicNetworkResource# + * PublicNetworkResource- Getthelistofpublicnetworks + * @return List of public, external and unmanaged networks in this + * datacenter. + */ + public List> listNetworks() { + VLANNetworksDto networks = context.getApi().getInfrastructureApi().listNetworks(target); + return Network.wrapNetworks(context, networks.getCollection()); + } + + /** + * Retrieve a filtered list of public, external and unmanaged networks in + * this datacenter. + * + * @param filter + * Filter to be applied to the list. + * @see API: http://community.abiquo.com/display/ABI20/PublicNetworkResource# + * PublicNetworkResource- Getthelistofpublicnetworks + */ + public List> listNetworks(final Predicate> filter) { + return Lists.newLinkedList(filter(listNetworks(), filter)); + } + + /** + * Retrieve the first network matching the filter within the list of + * networks. + * + * @param filter + * Filter to be applied to the list. + * @see API: http://community.abiquo.com/display/ABI20/PublicNetworkResource# + * PublicNetworkResource- Getthelistofpublicnetworks + * @return Filtered list of public, external and unmanaged networks in this + * datacenter. + */ + public Network findNetwork(final Predicate> filter) { + return Iterables.getFirst(filter(listNetworks(), filter), null); + } + + /** + * Retrieve the list of networks of this datacenter matching the given type. + * + * @param type + * Network type filter. + * @see API: http://community.abiquo.com/display/ABI20/PublicNetworkResource# + * PublicNetworkResource- Getthelistofpublicnetworks + * @return List of networks of this datacenter matching the given type. + */ + public List> listNetworks(final NetworkType type) { + NetworkOptions options = NetworkOptions.builder().type(type).build(); + VLANNetworksDto networks = context.getApi().getInfrastructureApi().listNetworks(target, options); + return Network.wrapNetworks(context, networks.getCollection()); + } + + /** + * Retrieve a filtered list of networks of this datacenter matching the given + * type. + * + * @param type + * Network type filter. + * @param filter + * Filter to be applied to the list. + * @see API: http://community.abiquo.com/display/ABI20/PublicNetworkResource# + * PublicNetworkResource- Getthelistofpublicnetworks + * @return Filtered list of networks of this datacenter matching the given + * type. + */ + public List> listNetworks(final NetworkType type, final Predicate> filter) { + return Lists.newLinkedList(filter(listNetworks(type), filter)); + } + + /** + * Retrieve the first network of the given type matching the filter. + * + * @param type + * Network type filter. + * @param filter + * Filter to be applied to the list. + * @see API: http://community.abiquo.com/display/ABI20/PublicNetworkResource# + * PublicNetworkResource- Getthelistofpublicnetworks + * @return First network of the given type matching the filter or + * null if there is none. + */ + public Network findNetwork(final NetworkType type, final Predicate> filter) { + return Iterables.getFirst(filter(listNetworks(type), filter), null); + } + + /** + * Retrieve a single public, external or unmanaged network from this + * datacenter. + * {@link org.jclouds.abiquo.domain.network.Network#toExternalNetwork}, + * {@link org.jclouds.abiquo.domain.network.Network#toPublicNetwork} and + * {@link org.jclouds.abiquo.domain.network.Network#toUnmanagedNetwork} can + * be used to convert the Network into the appropiate domain object. + * + * @param id + * Unique ID of the network in this datacenter. + * @see API: http://community.abiquo.com/display/ABI20/StorageDeviceResource# + * PublicNetworkResource# + * PublicNetworkResource-Getthelistofpublicnetworks + * @return Network with the given id or null if it does not + * exist. + */ + public Network getNetwork(final Integer id) { + VLANNetworkDto network = context.getApi().getInfrastructureApi().getNetwork(target, id); + return Network.wrapNetwork(context, network); + } + + // Actions + + /** + * Retrieve the hypervisor type from remote machine. + * + * @param ip + * IP address of the physical machine. + * @see API: + * @return Hypervisor type of the remote machine. + * @throws Exception + * If the hypervisor type information cannot be retrieved. + */ + public HypervisorType getHypervisorType(final String ip) { + DatacenterOptions options = DatacenterOptions.builder().ip(ip).build(); + + String type = context.getApi().getInfrastructureApi().getHypervisorTypeFromMachine(target, options); + + return HypervisorType.valueOf(type); + } + + /** + * Retrieve the list of available hypervisor types in the datacenter. + * + * @see API: + * @return List of available hypervisor types in the datacenter. + */ + @EnterpriseEdition + public List listAvailableHypervisors() { + HypervisorTypesDto types = context.getApi().getInfrastructureApi().getHypervisorTypes(target); + + return getHypervisorTypes(types); + } + + /** + * Retrieve a filtered list of available hypervisor types in the datacenter. + * + * @param filter + * Filter to be applied to the list. + * @see API: + * @return Filtered list of available hypervisor types in the datacenter. + */ + @EnterpriseEdition + public List listAvailableHypervisors(final Predicate filter) { + return Lists.newLinkedList(filter(listAvailableHypervisors(), filter)); + } + + /** + * Retrieve the first hypervisor type matching the filter within the list of + * types. + * + * @param filter + * Filter to be applied to the list. + * @see API: http://community.abiquo.com/display/ABI20/DatacenterResource# + * DatacenterResource- Retrieveavailablehypervisortypes + * @return First hypervisor type matching the filter or null if + * there is none. + */ + @EnterpriseEdition + public HypervisorType findHypervisor(final Predicate filter) { + return Iterables.getFirst(filter(listAvailableHypervisors(), filter), null); + } + + private List getHypervisorTypes(final HypervisorTypesDto dtos) { + List types = Lists.newArrayList(); + + for (HypervisorTypeDto dto : dtos.getCollection()) { + types.add(HypervisorType.fromId(dto.getId())); + } + + return types; + } + + /** + * Searches a remote machine and retrieves an Machine object with its + * information. + * + * @param ip + * IP address of the remote hypervisor to connect. + * @param hypervisorType + * Kind of hypervisor we want to connect. Valid values are {vbox, + * kvm, xen-3, vmx-04, hyperv-301, xenserver}. + * @param user + * User to log in. + * @param password + * Password to authenticate. + * @return A physical machine if found or null. + * @see API: http://community.abiquo.com/display/ABI20/DatacenterResource# + * DatacenterResource- Retrieveremotemachineinformation + */ + public Machine discoverSingleMachine(final String ip, final HypervisorType hypervisorType, final String user, + final String password) { + return discoverSingleMachine(ip, hypervisorType, user, password, hypervisorType.defaultPort); + } + + /** + * Searches a remote machine and retrieves an Machine object with its + * information. + * + * @param ip + * IP address of the remote hypervisor to connect. + * @param hypervisorType + * Kind of hypervisor we want to connect. Valid values are {vbox, + * kvm, xen-3, vmx-04, hyperv-301, xenserver}. + * @param user + * User to log in. + * @param password + * Password to authenticate. + * @param port + * Port to connect. + * @return A physical machine if found or null. + * @see API: http://community.abiquo.com/display/ABI20/DatacenterResource# + * DatacenterResource- Retrieveremotemachineinformation + */ + public Machine discoverSingleMachine(final String ip, final HypervisorType hypervisorType, final String user, + final String password, final int port) { + MachineDto dto = context + .getApi() + .getInfrastructureApi() + .discoverSingleMachine(target, ip, hypervisorType, user, password, + MachineOptions.builder().port(port).build()); + + // Credentials are not returned by the API + dto.setUser(user); + dto.setPassword(password); + + return wrap(context, Machine.class, dto); + } + + /** + * Searches multiple remote machines and retrieves an Machine list with its + * information. + * + * @param ipFrom + * IP address of the remote first hypervisor to check. + * @param ipTo + * IP address of the remote last hypervisor to check. + * @param hypervisorType + * Kind of hypervisor we want to connect. Valid values are {vbox, + * kvm, xen-3, vmx-04, hyperv-301, xenserver}. + * @param user + * User to log in. + * @param password + * Password to authenticate. + * @return The physical machine list. + * @see API: http://community.abiquo.com/display/ABI20/DatacenterResource# + * DatacenterResource- Retrievealistofremotemachineinformation + */ + public List discoverMultipleMachines(final String ipFrom, final String ipTo, + final HypervisorType hypervisorType, final String user, final String password) { + return discoverMultipleMachines(ipFrom, ipTo, hypervisorType, user, password, hypervisorType.defaultPort); + } + + /** + * Searches multiple remote machines and retrieves an Machine list with its + * information. + * + * @param ipFrom + * IP address of the remote first hypervisor to check. + * @param ipTo + * IP address of the remote last hypervisor to check. + * @param hypervisorType + * Kind of hypervisor we want to connect. Valid values are {vbox, + * kvm, xen-3, vmx-04, hyperv-301, xenserver}. + * @param user + * User to log in. + * @param password + * Password to authenticate. + * @param port + * Port to connect. + * @return The physical machine list. + * @see API: http://community.abiquo.com/display/ABI20/DatacenterResource# + * DatacenterResource- Retrievealistofremotemachineinformation + */ + public List discoverMultipleMachines(final String ipFrom, final String ipTo, + final HypervisorType hypervisorType, final String user, final String password, final int port) { + MachinesDto dto = context + .getApi() + .getInfrastructureApi() + .discoverMultipleMachines(target, ipFrom, ipTo, hypervisorType, user, password, + MachineOptions.builder().port(port).build()); + + // Credentials are not returned by the API + for (MachineDto machine : dto.getCollection()) { + machine.setUser(user); + machine.setPassword(password); + } + + return wrap(context, Machine.class, dto.getCollection()); + } + + /** + * Check the state of a remote machine. This feature is used to check the + * state from a remote machine giving its location, user, password and + * hypervisor type. This machine does not need to be managed by Abiquo. + * + * @param ip + * IP address of the remote hypervisor to connect. + * @param hypervisorType + * Kind of hypervisor we want to connect. Valid values are {vbox, + * kvm, xen-3, vmx-04, hyperv-301, xenserver}. + * @param user + * User to log in. + * @param password + * Password to authenticate. + * @return The physical machine state if the machine is found or + * null. + * @see API: http://community.abiquo.com/display/ABI20/DatacenterResource# + * DatacenterResource- Checkthestatefromremotemachine + */ + public MachineState checkMachineState(final String ip, final HypervisorType hypervisorType, final String user, + final String password) { + return checkMachineState(ip, hypervisorType, user, password, + MachineOptions.builder().port(hypervisorType.defaultPort).build()); + } + + /** + * Check the state of a remote machine. This feature is used to check the + * state from a remote machine giving its location, user, password and + * hypervisor type. This machine does not need to be managed by Abiquo. + * + * @param ip + * IP address of the remote hypervisor to connect. + * @param hypervisorType + * Kind of hypervisor we want to connect. Valid values are {vbox, + * kvm, xen-3, vmx-04, hyperv-301, xenserver}. + * @param user + * User to log in. + * @param password + * Password to authenticate. + * @param options + * . + * @return The physical machine state if the machine is found or + * null. + * @see API: http://community.abiquo.com/display/ABI20/DatacenterResource# + * DatacenterResource- Checkthestatefromremotemachine + */ + public MachineState checkMachineState(final String ip, final HypervisorType hypervisorType, final String user, + final String password, final MachineOptions options) { + MachineStateDto dto = context.getApi().getInfrastructureApi() + .checkMachineState(target, ip, hypervisorType, user, password, options); + + return dto.getState(); + } + + /** + * Check the ipmi configuration state of a remote machine. This feature is + * used to check the ipmi configuration state from a remote machine giving + * its location, user and password. This machine does not need to be managed + * by Abiquo. + * + * @param ip + * IP address of the remote hypervisor to connect. + * @param user + * User to log in. + * @param password + * Password to authenticate. + * @return The physical machine state if the machine is found or + * null. + * @see API: http://community.abiquo.com/display/ABI20/DatacenterResource# + * DatacenterResource- Checktheipmistatefromremotemachine + */ + public MachineIpmiState checkMachineIpmiState(final String ip, final String user, final String password) { + MachineIpmiStateDto dto = context.getApi().getInfrastructureApi() + .checkMachineIpmiState(target, ip, user, password); + return dto.getState(); + } + + /** + * Check the ipmi configuration state of a remote machine. This feature is + * used to check the ipmi configuration state from a remote machine giving + * its location, user and password. This machine does not need to be managed + * by Abiquo. + * + * @param ip + * IP address of the remote hypervisor to connect. + * @param user + * User to log in. + * @param password + * Password to authenticate. + * @return The physical machine state if the machine is found or + * null. + * @see API: http://community.abiquo.com/display/ABI20/DatacenterResource# + * DatacenterResource- Checktheipmistatefromremotemachine + */ + public MachineIpmiState checkMachineIpmiState(final String ip, final String user, final String password, + final IpmiOptions options) { + MachineIpmiStateDto dto = context.getApi().getInfrastructureApi() + .checkMachineIpmiState(target, ip, user, password, options); + return dto.getState(); + } + + /** + * Retrieve the list of virtual machine templates in the repository of this + * datacenter. + * + * @param enterprise + * Owner of the templates. + * @see API: http://community.abiquo.com/display/ABI20/ + * VirtualMachineTemplateResource# + * VirtualMachineTemplateResource-Retrieveallvirtualmachinetemplates + * @return List of virtual machine templates in the repository of this + * datacenter. + */ + public List listTemplatesInRepository(final Enterprise enterprise) { + VirtualMachineTemplatesDto dto = context.getApi().getVirtualMachineTemplateApi() + .listVirtualMachineTemplates(enterprise.getId(), target.getId()); + return wrap(context, VirtualMachineTemplate.class, dto.getCollection()); + } + + /** + * Retrieve a filtered list of virtual machine templates in the repository of + * this datacenter. + * + * @param enterprise + * Owner of the templates. + * @param filter + * Filter to be applied to the list. + * @see API: http://community.abiquo.com/display/ABI20/ + * VirtualMachineTemplateResource# + * VirtualMachineTemplateResource-Retrieveallvirtualmachinetemplates + * @return Filtered list of virtual machine templates in the repository of + * this datacenter. + */ + public List listTemplatesInRepository(final Enterprise enterprise, + final Predicate filter) { + return Lists.newLinkedList(filter(listTemplatesInRepository(enterprise), filter)); + } + + /** + * Retrieve the first virtual machine template within the list of templates + * of this datacenter from the given enterprise. + * + * @param enterprise + * Owner of the templates. + * @param filter + * Filter to be applied to the list. + * @see API: http://community.abiquo.com/display/ABI20/ + * VirtualMachineTemplateResource# + * VirtualMachineTemplateResource-Retrieveallvirtualmachinetemplates + * @return First virtual machine template matching the filter or + * null if there is none. + */ + public VirtualMachineTemplate findTemplateInRepository(final Enterprise enterprise, + final Predicate filter) { + return Iterables.getFirst(filter(listTemplatesInRepository(enterprise), filter), null); + } + + /** + * Retrieve a single virtual machine template in of this datacenter from the + * given enterprise. + * + * @param enterprise + * Owner of the templates. + * @param id + * Unique ID of the template in the datacenter repository for the + * given enterprise. + * @see API: http://community.abiquo.com/display/ABI20/ + * VirtualMachineTemplateResource# + * VirtualMachineTemplateResource-Retrieveallvirtualmachinetemplates + * @return Virtual machine template with the given id in the given + * enterpriess or null if it does not exist. + */ + public VirtualMachineTemplate getTemplateInRepository(final Enterprise enterprise, final Integer id) { + VirtualMachineTemplateDto template = context.getApi().getVirtualMachineTemplateApi() + .getVirtualMachineTemplate(enterprise.getId(), target.getId(), id); + return wrap(context, VirtualMachineTemplate.class, template); + } + + // Builder + + public static Builder builder(final RestContext context) { + return new Builder(context); + } + + public static class Builder { + private RestContext context; + + private String name; + + private String location; + + private String ip; + + private AbiquoEdition edition; + + public Builder(final RestContext context) { + super(); + this.context = context; + } + + public Builder remoteServices(final String ip, final AbiquoEdition edition) { + this.ip = ip; + this.edition = edition; + return this; + } + + public Builder name(final String name) { + this.name = name; + return this; + } + + public Builder location(final String location) { + this.location = location; + return this; + } + + public Datacenter build() { + DatacenterDto dto = new DatacenterDto(); + dto.setName(name); + dto.setLocation(location); + Datacenter datacenter = new Datacenter(context, dto); + datacenter.edition = edition; + datacenter.ip = ip; + return datacenter; + } + + public static Builder fromDatacenter(final Datacenter in) { + return Datacenter.builder(in.context).name(in.getName()).location(in.getLocation()); + } + } + + // Delegate methods + + public Integer getId() { + return target.getId(); + } + + public String getLocation() { + return target.getLocation(); + } + + public String getName() { + return target.getName(); + } + + public void setLocation(final String location) { + target.setLocation(location); + } + + public void setName(final String name) { + target.setName(name); + } + + public String getUUID() { + return target.getUuid(); + } + + @Override + public String toString() { + return "Datacenter [id=" + getId() + ", location=" + getLocation() + ", name=" + getName() + ", uuid=" + + getUUID() + "]"; + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/Datastore.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/Datastore.java new file mode 100644 index 0000000000..825583c7f7 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/Datastore.java @@ -0,0 +1,89 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.infrastructure; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.domain.DomainWrapper; +import org.jclouds.rest.RestContext; + +import com.abiquo.server.core.infrastructure.DatastoreDto; + +/** + * Adds high level functionality to {@link DatastoreDto}. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +public class Datastore extends DomainWrapper { + /** + * Constructor to be used only by the builder. This resource cannot be + * created. + */ + private Datastore(final RestContext context, final DatastoreDto target) { + super(context, target); + } + + // Delegate methods + + public String getDatastoreUUID() { + return target.getDatastoreUUID(); + } + + public String getDirectory() { + return target.getDirectory(); + } + + public Integer getId() { + return target.getId(); + } + + public String getName() { + return target.getName(); + } + + public String getRootPath() { + return target.getRootPath(); + } + + public long getSize() { + return target.getSize(); + } + + public long getUsedSize() { + return target.getUsedSize(); + } + + public boolean isEnabled() { + return target.isEnabled(); + } + + public void setEnabled(final boolean enabled) { + target.setEnabled(enabled); + } + + @Override + public String toString() { + return "Datastore [id=" + getId() + ", uuid=" + getDatastoreUUID() + ", directory=" + getDirectory() + ", name=" + + getName() + ", rootPath=" + getRootPath() + ", size=" + getSize() + ", usedSize=" + getUsedSize() + + ", enabled=" + isEnabled() + "]"; + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/Fsm.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/Fsm.java new file mode 100644 index 0000000000..549c5af49d --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/Fsm.java @@ -0,0 +1,75 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.infrastructure; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.domain.DomainWrapper; +import org.jclouds.abiquo.reference.annotations.EnterpriseEdition; +import org.jclouds.rest.RestContext; + +import com.abiquo.server.core.infrastructure.FsmDto; + +/** + * Adds high level functionality to {@link FsmDto}. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + * @see API: + * http://community.abiquo.com/display/ABI20/Rack+Resource + */ +@EnterpriseEdition +public class Fsm extends DomainWrapper { + /** + * Constructor to be used only by the builder. + */ + protected Fsm(final RestContext context, final FsmDto target) { + super(context, target); + } + + // Delegate Methods + + public String getDescription() { + return target.getDescription(); + } + + public String getDn() { + return target.getDn(); + } + + public String getError() { + return target.getError(); + } + + public String getProgress() { + return target.getProgress(); + } + + public String getStatus() { + return target.getStatus(); + } + + @Override + public String toString() { + return "Fsm [Dn=" + getDn() + ", Description=" + getDescription() + ", Error=" + getError() + ", Progress=" + + getProgress() + ", Status=" + getStatus() + "]"; + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/LogicServer.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/LogicServer.java new file mode 100644 index 0000000000..8c668bc645 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/LogicServer.java @@ -0,0 +1,90 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.infrastructure; + +import java.util.List; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.domain.DomainWrapper; +import org.jclouds.abiquo.reference.annotations.EnterpriseEdition; +import org.jclouds.rest.RestContext; + +import com.abiquo.server.core.infrastructure.LogicServerDto; +import com.abiquo.server.core.infrastructure.LogicServerPolicyDto; + +/** + * Adds high level functionality to {@link LogicServerDto}. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + * @see API: + * http://community.abiquo.com/display/ABI20/Rack+Resource + */ +@EnterpriseEdition +public class LogicServer extends DomainWrapper { + /** + * Constructor to be used only by the builder. + */ + protected LogicServer(final RestContext context, final LogicServerDto target) { + super(context, target); + } + + // Delegate Methods + + public String getName() { + return target.getName(); + } + + public void setType(final String value) { + target.setType(value); + } + + public String getAssociated() { + return target.getAssociated(); + } + + public String getType() { + return target.getType(); + } + + public String getAssociatedTo() { + return target.getAssociatedTo(); + } + + public String getDescription() { + return target.getDescription(); + } + + public void setDescription(final String value) { + target.setDescription(value); + } + + public List getCollection() { + return target.getCollection(); + } + + @Override + public String toString() { + return "LogicServer [name=" + getName() + ", associated=" + getAssociated() + ", type=" + getType() + + ", associatedTo=" + getAssociatedTo() + ", description=" + getDescription() + "]"; + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/Machine.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/Machine.java new file mode 100644 index 0000000000..177ba0dee1 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/Machine.java @@ -0,0 +1,509 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.infrastructure; + +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.collect.Iterables.filter; +import static com.google.common.collect.Iterables.find; + +import java.util.List; + +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.domain.cloud.VirtualMachine; +import org.jclouds.abiquo.domain.enterprise.Enterprise; +import org.jclouds.abiquo.domain.infrastructure.options.MachineOptions; +import org.jclouds.abiquo.predicates.infrastructure.DatastorePredicates; +import org.jclouds.abiquo.reference.ValidationErrors; +import org.jclouds.abiquo.reference.rest.ParentLinkName; +import org.jclouds.abiquo.rest.internal.ExtendedUtils; +import org.jclouds.http.HttpResponse; +import org.jclouds.http.functions.ParseXMLWithJAXB; +import org.jclouds.rest.RestContext; + +import com.abiquo.model.enumerator.HypervisorType; +import com.abiquo.model.enumerator.MachineState; +import com.abiquo.model.rest.RESTLink; +import com.abiquo.server.core.cloud.VirtualMachineWithNodeExtendedDto; +import com.abiquo.server.core.cloud.VirtualMachinesWithNodeExtendedDto; +import com.abiquo.server.core.enterprise.EnterpriseDto; +import com.abiquo.server.core.infrastructure.DatastoresDto; +import com.abiquo.server.core.infrastructure.MachineDto; +import com.abiquo.server.core.infrastructure.MachineStateDto; +import com.abiquo.server.core.infrastructure.RackDto; +import com.google.common.base.Predicate; +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; +import com.google.inject.TypeLiteral; + +/** + * Adds high level functionality to {@link MachineDto}. This resource allows you + * to manage physical machines in the cloud infrastructure. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + * @see API: + * http://community.abiquo.com/display/ABI20/MachineResource + */ +public class Machine extends AbstractPhysicalMachine { + /** The rack where the machine belongs. */ + protected Rack rack; + + /** + * Constructor to be used only by the builder. + */ + protected Machine(final RestContext context, final MachineDto target) { + super(context, target); + } + + /** + * Create a new physical machine in Abiquo. The best way to create a machine + * if first calling {@link Datacenter#discoverSingleMachine} or + * {@link Datacenter#discoverMultipleMachines}. This will return a new + * {@link Machine}. The following steps are: enabling a datastore, selecting + * a virtual switch and choosing a rack. Refer link for more information. + * + * @see API: http://community.abiquo.com/display/ABI20/DatacenterResource# + * DatacenterResource- Retrieveremotemachineinformation + * @see API: http://community.abiquo.com/display/ABI20/MachineResource# + * MachineResource- Createamachine + */ + public void save() { + target = context.getApi().getInfrastructureApi().createMachine(rack.unwrap(), target); + } + + @Override + public MachineState check() { + MachineStateDto dto = context.getApi().getInfrastructureApi().checkMachineState(target, true); + MachineState state = dto.getState(); + target.setState(state); + return state; + } + + // Parent access + /** + * Retrieve the unmanaged rack where the machine is. + * + * @see API: + * http://community.abiquo.com/display/ABI20/RackResource#RackResource- + * RetrieveaRack + */ + public Rack getRack() { + RESTLink link = checkNotNull(target.searchLink(ParentLinkName.RACK), ValidationErrors.MISSING_REQUIRED_LINK + " " + + ParentLinkName.RACK); + + ExtendedUtils utils = (ExtendedUtils) context.getUtils(); + HttpResponse response = utils.getAbiquoHttpClient().get(link); + + ParseXMLWithJAXB parser = new ParseXMLWithJAXB(utils.getXml(), TypeLiteral.get(RackDto.class)); + + return wrap(context, Rack.class, parser.apply(response)); + } + + // Children access + + @Override + public List getDatastores() { + return wrap(context, Datastore.class, target.getDatastores().getCollection()); + } + + @Override + public Datastore findDatastore(final String name) { + return find(getDatastores(), DatastorePredicates.name(name), null); + } + + /** + * Gets the list of virtual machines in the physical machine. + * + * @return The list of virtual machines in the physical machine. + * @see API: http://community.abiquo.com/display/ABI20/Machine+Resource# + * MachineResource- + * Retrievethelistofvirtualmachinesbymachine'shypervisor + */ + public List listVirtualMachines() { + MachineOptions options = MachineOptions.builder().sync(false).build(); + VirtualMachinesWithNodeExtendedDto vms = context.getApi().getInfrastructureApi() + .listVirtualMachinesByMachine(target, options); + return wrap(context, VirtualMachine.class, vms.getCollection()); + } + + /** + * Gets the list of virtual machines in the physical machine matching the + * given filter. + * + * @param filter + * The filter to apply. + * @return The list of virtual machines in the physical machine matching the + * given filter. + */ + public List listVirtualMachines(final Predicate filter) { + return Lists.newLinkedList(filter(listVirtualMachines(), filter)); + } + + /** + * Gets a single virtual machine in the physical machine matching the given + * filter. + * + * @param filter + * The filter to apply. + * @return The virtual machine or null if none matched the given + * filter. + */ + public VirtualMachine findVirtualMachine(final Predicate filter) { + return Iterables.getFirst(filter(listVirtualMachines(), filter), null); + } + + /** + * Gets the list of virtual machines in the physical machine sinchronizing + * virtual machines from remote hypervisor with abiquo's database. + * + * @return The list of virtual machines in the physical machine. + * @see API: http://community.abiquo.com/display/ABI20/Machine+Resource# + * MachineResource- + * Retrievethelistofvirtualmachinesbymachine'shypervisor + */ + public List listRemoteVirtualMachines() { + MachineOptions options = MachineOptions.builder().sync(true).build(); + VirtualMachinesWithNodeExtendedDto vms = context.getApi().getInfrastructureApi() + .listVirtualMachinesByMachine(target, options); + return wrap(context, VirtualMachine.class, vms.getCollection()); + } + + /** + * Gets the list of virtual machines in the physical machine matching the + * given filter sinchronizing virtual machines from remote hypervisor with + * abiquo's database. + * + * @param filter + * The filter to apply. + * @return The list of remote virtual machines in the physical machine + * matching the given filter. + */ + public List listRemoteVirtualMachines(final Predicate filter) { + return Lists.newLinkedList(filter(listVirtualMachines(), filter)); + } + + /** + * Gets a single virtual machine in the physical machine matching the given + * filter sinchronizing virtual machines from remote hypervisor with abiquo's + * database. + * + * @param filter + * The filter to apply. + * @return The virtual machine or null if none matched the given + * filter. + */ + public VirtualMachine findRemoteVirtualMachine(final Predicate filter) { + return Iterables.getFirst(filter(listVirtualMachines(), filter), null); + } + + /** + * Reserve the machine for the given enterprise. + *

+ * When a {@link Machine} is reserved for an {@link Enterprise}, only the + * users of that enterprise will be able to deploy {@link VirtualMachine}s in + * it. + * + * @param enterprise + * The enterprise reserving the machine. + */ + public void reserveFor(final Enterprise enterprise) { + target = context.getApi().getInfrastructureApi().reserveMachine(enterprise.unwrap(), target); + } + + /** + * Cancels the machine reservation for the given enterprise. + * + * @param enterprise + * The enterprise to cancel reservation for. + */ + public void cancelReservationFor(final Enterprise enterprise) { + context.getApi().getInfrastructureApi().cancelReservation(enterprise.unwrap(), target); + target.getLinks().remove(target.searchLink(ParentLinkName.ENTERPRISE)); + } + + /** + * Check if the machine is reserved. + * + * @return Boolean indicating if the machine is reserved for an enterprise. + */ + public boolean isReserved() { + return target.searchLink(ParentLinkName.ENTERPRISE) != null; + } + + /** + * Get the enterprise that has reserved the machine or null if + * the machine is not reserved. + * + * @return The enterprise that has reserved the machine or null + * if the machine is not reserved. + */ + public Enterprise getOwnerEnterprise() { + if (!isReserved()) { + return null; + } + + EnterpriseDto enterprise = context.getApi().getEnterpriseApi() + .getEnterprise(target.getIdFromLink(ParentLinkName.ENTERPRISE)); + + return wrap(context, Enterprise.class, enterprise); + } + + // Builder + + public static Builder builder(final RestContext context, final Rack rack) { + return new Builder(context, rack); + } + + public static class Builder { + private RestContext context; + + private String name, description; + + private Integer virtualRamInMb; + + private Integer virtualRamUsedInMb = DEFAULT_VRAM_USED; + + private Integer virtualCpuCores; + + private Integer virtualCpusUsed = DEFAULT_VCPU_USED; + + private String virtualSwitch; + + private Integer port; + + private String ip; + + private MachineState state = MachineState.STOPPED; + + private String ipService; + + private HypervisorType type; + + private String user; + + private String password; + + private Iterable datastores; + + private String ipmiIp; + + private Integer ipmiPort; + + private String ipmiUser; + + private String ipmiPassword; + + private Rack rack; + + public Builder(final RestContext context, final Rack rack) { + super(); + checkNotNull(rack, ValidationErrors.NULL_RESOURCE + Rack.class); + this.rack = rack; + this.context = context; + } + + public Builder state(final MachineState state) { + this.state = state; + return this; + } + + public Builder ipmiPassword(final String ipmiPassword) { + this.ipmiPassword = ipmiPassword; + return this; + } + + public Builder ipmiUser(final String ipmiUser) { + this.ipmiUser = ipmiUser; + return this; + } + + public Builder ipmiPort(final int ipmiPort) { + this.ipmiPort = ipmiPort; + return this; + } + + public Builder ipmiIp(final String ipmiIp) { + this.ipmiIp = ipmiIp; + return this; + } + + public Builder user(final String user) { + this.user = user; + return this; + } + + public Builder ip(final String ip) { + this.ip = ip; + if (ipService == null) { + ipService = ip; + } + return this; + } + + public Builder ipService(final String ipService) { + this.ipService = ipService; + return this; + } + + public Builder password(final String password) { + this.password = password; + return this; + } + + public Builder virtualSwitch(final String virtualSwitch) { + this.virtualSwitch = virtualSwitch; + return this; + } + + public Builder name(final String name) { + this.name = name; + return this; + } + + public Builder description(final String description) { + this.description = description; + return this; + } + + public Builder port(final int port) { + this.port = port; + return this; + } + + public Builder datastores(final Iterable datastores) { + this.datastores = datastores; + return this; + } + + public Builder virtualRamInMb(final int virtualRamInMb) { + this.virtualRamInMb = virtualRamInMb; + return this; + } + + public Builder virtualRamUsedInMb(final int virtualRamUsedInMb) { + this.virtualRamUsedInMb = virtualRamUsedInMb; + return this; + } + + public Builder virtualCpuCores(final int virtualCpuCores) { + this.virtualCpuCores = virtualCpuCores; + return this; + } + + public Builder virtualCpusUsed(final int virtualCpusUsed) { + this.virtualCpusUsed = virtualCpusUsed; + return this; + } + + public Builder hypervisorType(final HypervisorType hypervisorType) { + this.type = hypervisorType; + + // Sets default hypervisor port + if (this.port == null) { + this.port = hypervisorType.defaultPort; + } + + return this; + } + + public Builder rack(final Rack rack) { + checkNotNull(rack, ValidationErrors.NULL_RESOURCE + Datacenter.class); + this.rack = rack; + return this; + } + + public Machine build() { + MachineDto dto = new MachineDto(); + dto.setName(name); + dto.setDescription(description); + dto.setVirtualRamInMb(virtualRamInMb); + dto.setVirtualRamUsedInMb(virtualRamUsedInMb); + dto.setVirtualCpuCores(virtualCpuCores); + dto.setVirtualCpusUsed(virtualCpusUsed); + dto.setVirtualSwitch(virtualSwitch); + if (port != null) { + dto.setPort(port); + } + dto.setIp(ip); + dto.setIpService(ipService); + dto.setType(type); + dto.setUser(user); + dto.setPassword(password); + dto.setIpmiIP(ipmiIp); + dto.setIpmiPassword(ipmiPassword); + if (ipmiPort != null) { + dto.setIpmiPort(ipmiPort); + } + dto.setIpmiUser(ipmiUser); + dto.setState(state); + + DatastoresDto datastoresDto = new DatastoresDto(); + datastoresDto.getCollection().addAll(unwrap(datastores)); + dto.setDatastores(datastoresDto); + + Machine machine = new Machine(context, dto); + machine.rack = rack; + + return machine; + } + + public static Builder fromMachine(final Machine in) { + Builder builder = Machine.builder(in.context, in.rack).name(in.getName()).description(in.getDescription()) + .virtualCpuCores(in.getVirtualCpuCores()).virtualCpusUsed(in.getVirtualCpusUsed()) + .virtualRamInMb(in.getVirtualRamInMb()).virtualRamUsedInMb(in.getVirtualRamUsedInMb()) + .virtualSwitch(in.getVirtualSwitch()).port(in.getPort()).ip(in.getIp()).ipService(in.getIpService()) + .hypervisorType(in.getType()).user(in.getUser()).password(in.getPassword()).ipmiIp(in.getIpmiIp()) + .ipmiPassword(in.getIpmiPassword()).ipmiUser(in.getIpmiUser()).state(in.getState()) + .datastores(in.getDatastores()); + + // Parameters that can be null + if (in.getIpmiPort() != null) { + builder.ipmiPort(in.getIpmiPort()); + } + + return builder; + } + } + + // Delegate methods + + public void setRack(final Rack rack) { + this.rack = rack; + } + + public VirtualMachine getVirtualMachine(final Integer virtualMachineId) { + VirtualMachineWithNodeExtendedDto vm = context.getApi().getInfrastructureApi() + .getVirtualMachine(target, virtualMachineId); + return wrap(context, VirtualMachine.class, vm); + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/ManagedRack.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/ManagedRack.java new file mode 100644 index 0000000000..2d5bd09735 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/ManagedRack.java @@ -0,0 +1,713 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.infrastructure; + +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.collect.Iterables.filter; + +import java.util.List; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.domain.DomainWrapper; +import org.jclouds.abiquo.reference.ValidationErrors; +import org.jclouds.abiquo.reference.annotations.EnterpriseEdition; +import org.jclouds.abiquo.reference.rest.ParentLinkName; +import org.jclouds.rest.RestContext; + +import com.abiquo.server.core.infrastructure.FsmsDto; +import com.abiquo.server.core.infrastructure.LogicServersDto; +import com.abiquo.server.core.infrastructure.MachinesDto; +import com.abiquo.server.core.infrastructure.OrganizationsDto; +import com.abiquo.server.core.infrastructure.RackDto; +import com.abiquo.server.core.infrastructure.UcsRackDto; +import com.google.common.base.Predicate; +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; + +/** + * Adds high level functionality to {@link RackDto}. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + * @see API: + * http://community.abiquo.com/display/ABI20/RackResource + */ +@EnterpriseEdition +public class ManagedRack extends DomainWrapper { + /** The default minimum VLAN id. */ + private static final int DEFAULT_VLAN_ID_MIN = 2; + + /** The default maximum VLAN id. */ + private static final int DEFAULT_VLAN_ID_MAX = 4094; + + /** The default maximum VLAN per virtual datacenter. */ + private static final int DEFAULT_VLAN_PER_VDC = 1; + + /** The default nrsq factor. */ + private static final int DEFAULT_NRSQ = 10; + + /** The datacenter where the rack belongs. */ + private Datacenter datacenter; + + /** + * Constructor to be used only by the builder. + */ + protected ManagedRack(final RestContext context, final UcsRackDto target) { + super(context, target); + } + + // Domain operations + + /** + * Delete the managed rack. + * + * @see API: + * http://community.abiquo.com/display/ABI20/Rack+Resource#RackResource + * #RackResource- DeleteaRack + */ + public void delete() { + context.getApi().getInfrastructureApi().deleteRack(target); + target = null; + } + + /** + * Create a new managed rack in Abiquo. This method wil discover the blades + * configured in the UCS. If the data provided for the connection is invalid + * a UcsRack will be created in Abiquo but with no Physical Machines attached + * to it. + * + * @see API: http://community.abiquo.com/display/ABI20/RackResource#RackResource + * -CreateanewUCSRack< /a> + */ + public void save() { + target = context.getApi().getInfrastructureApi().createManagedRack(datacenter.unwrap(), target); + } + + /** + * Update rack information in the server with the data from this rack. The IP + * data member cannot be updated. If changed will be ignored and the old IP + * will remain. + * + * @see API: http://community.abiquo.com/display/ABI20/RackResource#RackResource + * #RackResource- UpdateanexistingUCSrack + */ + public void update() { + target = context.getApi().getInfrastructureApi().updateManagedRack(target); + } + + // Parent access + /** + * Retrieve the datacenter where this rack is. + * + * @see API: http://community.abiquo.com/display/ABI20/DatacenterResource# + * DatacenterResource- Retrieveadatacenter + */ + public Datacenter getDatacenter() { + Integer datacenterId = target.getIdFromLink(ParentLinkName.DATACENTER); + return wrap(context, Datacenter.class, context.getApi().getInfrastructureApi().getDatacenter(datacenterId)); + } + + // Children access + + /** + * Retrieve the list of blades in this rack. + * + * @see API: http://community.abiquo.com/display/ABI20/MachineResource# + * MachineResource- RetrievealistofMachines + */ + public List listMachines() { + MachinesDto machines = context.getApi().getInfrastructureApi().listMachines(target); + return wrap(context, Blade.class, machines.getCollection()); + } + + /** + * Retrieve a filtered list of blades in this rack. + * + * @param filter + * Filter to be applied to the list. + * @see API: http://community.abiquo.com/display/ABI20/MachineResource# + * MachineResource- RetrievealistofMachines + */ + public List listMachines(final Predicate filter) { + return Lists.newLinkedList(filter(listMachines(), filter)); + } + + /** + * Retrieve the first blade matching the filter within the list of machines + * in this rack. + * + * @param filter + * Filter to be applied to the list. + * @see API: http://community.abiquo.com/display/ABI20/MachineResource# + * MachineResource- RetrievealistofMachines + */ + public Blade findMachine(final Predicate filter) { + return Iterables.getFirst(filter(listMachines(), filter), null); + } + + /** + * Retrieve the list of service profiles in this UCS rack. + * + * @see API: http://community.abiquo.com/display/ABI20/RackResource#RackResource + * - RetrievealistofallservicesprofilesinaUCSrack + */ + public List listServiceProfiles() { + LogicServersDto profiles = context.getApi().getInfrastructureApi().listServiceProfiles(target); + return wrap(context, LogicServer.class, profiles.getCollection()); + } + + /** + * Retrieve a filtered list of service profiles in this UCS rack. + * + * @param filter + * Filter to be applied to the list. + * @see API: http://community.abiquo.com/display/ABI20/RackResource#RackResource + * - RetrievealistofallservicesprofilesinaUCSrack + */ + public List listServiceProfiles(final Predicate filter) { + return Lists.newLinkedList(filter(listServiceProfiles(), filter)); + } + + /** + * Retrieve the first service profile matching the filter within the list of + * profiles in this rack. + * + * @param filter + * Filter to be applied to the list. + * @see API: http://community.abiquo.com/display/ABI20/RackResource#RackResource + * - RetrievealistofallservicesprofilesinaUCSrack + */ + public LogicServer findServiceProfile(final Predicate filter) { + return Iterables.getFirst(filter(listServiceProfiles(), filter), null); + } + + /** + * Retrieve the list of service profile templates in this UCS rack. + * + * @see API: http://community.abiquo.com/display/ABI20/RackResource- + * RetrievealistofallServicesProfilesTemplatesinaUCSRack + */ + public List listServiceProfileTemplates() { + LogicServersDto templates = context.getApi().getInfrastructureApi().listServiceProfileTemplates(target); + return wrap(context, LogicServer.class, templates.getCollection()); + } + + /** + * Retrieve a filtered list of service profile templates in this UCS rack. + * + * @param filter + * Filter to be applied to the list. + * @see API: http://community.abiquo.com/display/ABI20/RackResource- + * RetrievealistofallServicesProfilesTemplatesinaUCSRack + */ + public List listServiceProfileTemplates(final Predicate filter) { + return Lists.newLinkedList(filter(listServiceProfileTemplates(), filter)); + } + + /** + * Retrieve the first service profile template matching the filter within the + * list of templates in this rack. + * + * @param filter + * Filter to be applied to the list. + * @see API: http://community.abiquo.com/display/ABI20/RackResource- + * RetrievealistofallServicesProfilesTemplatesinaUCSRack + */ + public LogicServer findServiceProfileTemplate(final Predicate filter) { + return Iterables.getFirst(filter(listServiceProfileTemplates(), filter), null); + } + + /** + * Retrieve the list of organization in this UCS rack. The credentials in the + * UcsRack configuration might not have enough rights in the UCS to retrieve + * all organizations. Then only the allowed ones are returned. This data is + * not persisted in Abiquo. + * + * @see API: + * http://community.abiquo.com/display/ABI20/ + */ + public List listOrganizations() { + OrganizationsDto organizations = context.getApi().getInfrastructureApi().listOrganizations(target); + return wrap(context, Organization.class, organizations.getCollection()); + } + + /** + * Retrieve a filtered list of organization in this UCS rack. The credentials + * in the UcsRack configuration might not have enough rights in the UCS to + * retrieve all organizations. Then only the allowed ones are returned. This + * data is not persisted in Abiquo. + * + * @param filter + * Filter to be applied to the list. + * @see API: + * http://community.abiquo.com/display/ABI20/RackResource#RackResource- + * RetrieveallorganizationsfromaUCS + */ + public List listOrganizations(final Predicate filter) { + return Lists.newLinkedList(filter(listOrganizations(), filter)); + } + + /** + * Retrieve the first organization matching the filter within the list of + * organization in this rack. The credentials in the UcsRack configuration + * might not have enough rights in the UCS to retrieve all organizations. + * Then only the allowed ones are returned. This data is not persisted in + * Abiquo. + * + * @param filter + * Filter to be applied to the list. + * @see API: + * http://community.abiquo.com/display/ABI20/RackResource#RackResource- + * RetrieveallorganizationsfromaUCS + */ + public Organization findOrganization(final Predicate filter) { + return Iterables.getFirst(filter(listOrganizations(), filter), null); + } + + /** + * @see API: http://community.abiquo.com/display/ABI20/RackResource#RackResource + * - RetrieveFSMofanentityinUCS + */ + public List listFsm(final String entityName) { + FsmsDto fsms = context.getApi().getInfrastructureApi().listFsms(target, entityName); + return wrap(context, Fsm.class, fsms.getCollection()); + } + + // Actions + + /** + * Clone a Service Profile this rack. This data is not persisted in Abiquo. + * + * @see API: http://community.abiquo.com/display/ABI20/RackResource#RackResource + * - ClonelogicserverinUCS + */ + public void cloneLogicServer(final LogicServer logicServer, final Organization organization, final String newName) { + context.getApi().getInfrastructureApi() + .cloneLogicServer(this.unwrap(), logicServer.unwrap(), organization.unwrap(), newName); + } + + /** + * Associate a Service Profile and a Blade in UCS. If the Service Profile is + * already associated then the request cannot be completed. This data is not + * persisted in Abiquo. + * + * @see API: http://community.abiquo.com/display/ABI20/RackResource#RackResource + * - AssociatelogicserverwithabladeinUCS + */ + public void associateLogicServer(final String bladeName, final LogicServer logicServer, + final Organization organization) { + context.getApi().getInfrastructureApi() + .associateLogicServer(this.unwrap(), logicServer.unwrap(), organization.unwrap(), bladeName); + } + + /** + * Clone and associate a Service Profile and a Blade in UCS. If the Blade is + * already associated then Abiquo will dissociate it first. If the request + * cannot be completed successfully the Blade might be left with no Service + * Profile associated. This data is not persisted in Abiquo. + * + * @see API: http://community.abiquo.com/display/ABI20/RackResource#RackResource + * - CloneandassociateLogicServerwithabladeinUCS + */ + public void cloneAndAssociateLogicServer(final String bladeName, final LogicServer logicServer, + final Organization organization, final String logicServerName) { + context + .getApi() + .getInfrastructureApi() + .cloneAndAssociateLogicServer(this.unwrap(), logicServer.unwrap(), organization.unwrap(), bladeName, + logicServerName); + } + + /** + * Instantiate and associate a Service Profile Template and a Blade in UCS. + * If the Service Profile is already associated the request cannot be + * successful. If the Blade is already associated then Abiquo will dissociate + * it first. If the request cannot be completed successfully the Blade might + * be left with no Service Profile associated. This data is not persisted in + * Abiquo. + * + * @see API: http://community.abiquo.com/display/ABI20/RackResource#RackResource + * - AssociateabladewithaLogicServerTemplate + */ + public void associateLogicServerTemplate(final String bladeName, final LogicServer logicServer, + final Organization organization, final String logicServerName) { + context.getApi().getInfrastructureApi() + .associateTemplate(this.unwrap(), logicServer.unwrap(), organization.unwrap(), bladeName, logicServerName); + } + + /** + * Dissociates a Service Profile and a Blade in UCS. This data is not + * persisted in Abiquo. + * + * @see API: http://community.abiquo.com/display/ABI20/RackResource#RackResource + * - DisassociatelogicserverfromabladeinUCS + */ + public void disassociateLogicServer(final LogicServer logicServer) { + context.getApi().getInfrastructureApi().dissociateLogicServer(this.unwrap(), logicServer.unwrap()); + } + + /** + * Deletes a Service Profile in UCS. This data is not persisted in Abiquo. + * + * @see API: http://community.abiquo.com/display/ABI20/RackResource#RackResource + * - DeletelogicserverwithabladeinUCS + */ + public void deleteLogicServer(final LogicServer logicServer) { + context.getApi().getInfrastructureApi().deleteLogicServer(this.unwrap(), logicServer.unwrap()); + } + + // Builder + + public static Builder builder(final RestContext context, final Datacenter datacenter) { + return new Builder(context, datacenter); + } + + public static class Builder { + private RestContext context; + + private Integer id; + + private String name; + + private String shortDescription; + + private boolean haEnabled = false; + + private Integer nrsq = DEFAULT_NRSQ; + + private Integer vlanIdMax = DEFAULT_VLAN_ID_MAX; + + private Integer vlanIdMin = DEFAULT_VLAN_ID_MIN; + + private Integer vlanPerVdcReserved = DEFAULT_VLAN_PER_VDC; + + private String vlansIdAvoided; + + private Integer port; + + private String ip; + + private String password; + + private String user; + + private String defaultTemplate; + + private Integer maxMachinesOn; + + private Datacenter datacenter; + + public Builder(final RestContext context, final Datacenter datacenter) { + super(); + checkNotNull(datacenter, ValidationErrors.NULL_RESOURCE + Datacenter.class); + this.datacenter = datacenter; + this.context = context; + } + + public Builder port(final Integer port) { + this.port = port; + return this; + } + + public Builder ipAddress(final String ip) { + this.ip = ip; + return this; + } + + public Builder password(final String password) { + this.password = password; + return this; + } + + public Builder user(final String user) { + this.user = user; + return this; + } + + public Builder defaultTemplate(final String defaultTemplate) { + this.defaultTemplate = defaultTemplate; + return this; + } + + public Builder maxMachinesOn(final Integer maxMachinesOn) { + this.maxMachinesOn = maxMachinesOn; + return this; + } + + public Builder id(final Integer id) { + this.id = id; + return this; + } + + public Builder name(final String name) { + this.name = name; + return this; + } + + public Builder shortDescription(final String shortDescription) { + this.shortDescription = shortDescription; + return this; + } + + public Builder haEnabled(final boolean haEnabled) { + this.haEnabled = haEnabled; + return this; + } + + public Builder nrsq(final int nrsq) { + this.nrsq = nrsq; + return this; + } + + public Builder vlanIdMax(final int vlanIdMax) { + this.vlanIdMax = vlanIdMax; + return this; + } + + public Builder vlanIdMin(final int vlanIdMin) { + this.vlanIdMin = vlanIdMin; + return this; + } + + public Builder vlanPerVdcReserved(final int vlanPerVdcExpected) { + this.vlanPerVdcReserved = vlanPerVdcExpected; + return this; + } + + public Builder VlansIdAvoided(final String vlansIdAvoided) { + this.vlansIdAvoided = vlansIdAvoided; + return this; + } + + public Builder datacenter(final Datacenter datacenter) { + checkNotNull(datacenter, ValidationErrors.NULL_RESOURCE + Datacenter.class); + this.datacenter = datacenter; + return this; + } + + public ManagedRack build() { + UcsRackDto dto = new UcsRackDto(); + dto.setId(id); + dto.setName(name); + dto.setShortDescription(shortDescription); + dto.setHaEnabled(haEnabled); + dto.setNrsq(nrsq); + dto.setVlanIdMax(vlanIdMax); + dto.setVlanIdMin(vlanIdMin); + dto.setVlanPerVdcReserved(vlanPerVdcReserved); + dto.setVlansIdAvoided(vlansIdAvoided); + dto.setPort(port); + dto.setIp(ip); + dto.setPassword(password); + dto.setUser(user); + dto.setDefaultTemplate(defaultTemplate); + dto.setMaxMachinesOn(maxMachinesOn); + + ManagedRack rack = new ManagedRack(context, dto); + rack.datacenter = datacenter; + return rack; + } + + public static Builder fromRack(final ManagedRack in) { + return ManagedRack.builder(in.context, in.datacenter).id(in.getId()).name(in.getName()) + .shortDescription(in.getShortDescription()).haEnabled(in.isHaEnabled()).nrsq(in.getNrsq()) + .vlanIdMax(in.getVlanIdMax()).vlanIdMin(in.getVlanIdMin()) + .vlanPerVdcReserved(in.getVlanPerVdcReserved()).VlansIdAvoided(in.getVlansIdAvoided()) + .port(in.getPort()).ipAddress(in.getIp()).password(in.getPassword()).user(in.getUser()) + .defaultTemplate(in.getDefaultTemplate()).maxMachinesOn(in.getMaxMachinesOn()); + } + } + + // Delegate methods + + public Integer getId() { + return target.getId(); + } + + public String getName() { + return target.getName(); + } + + public String getShortDescription() { + return target.getShortDescription(); + } + + public void setShortDescription(final String description) { + target.setShortDescription(description); + } + + public void setHaEnabled(final boolean haEnabled) { + target.setHaEnabled(haEnabled); + } + + public boolean isHaEnabled() { + return target.isHaEnabled(); + } + + public Integer getNrsq() { + return target.getNrsq(); + } + + public Integer getVlanIdMax() { + return target.getVlanIdMax(); + } + + public Integer getVlanIdMin() { + return target.getVlanIdMin(); + } + + public Integer getVlanPerVdcReserved() { + return target.getVlanPerVdcReserved(); + } + + public String getVlansIdAvoided() { + return target.getVlansIdAvoided(); + } + + public void setNrsq(final Integer nrsq) { + target.setNrsq(nrsq); + } + + public void setVlanIdMax(final Integer vlanIdMax) { + target.setVlanIdMax(vlanIdMax); + } + + public void setVlanIdMin(final Integer vlanIdMin) { + target.setVlanIdMin(vlanIdMin); + } + + public void setVlanPerVdcReserved(final Integer vlanPerVdcReserved) { + target.setVlanPerVdcReserved(vlanPerVdcReserved); + } + + public void setVlansIdAvoided(final String vlansIdAvoided) { + target.setVlansIdAvoided(vlansIdAvoided); + } + + public String getIp() { + return target.getIp(); + } + + public String getLongDescription() { + return target.getLongDescription(); + } + + public Integer getMaxMachinesOn() { + return target.getMaxMachinesOn(); + } + + public String getPassword() { + return target.getPassword(); + } + + public Integer getPort() { + return target.getPort(); + } + + public String getUser() { + return target.getUser(); + } + + public void setDefaultTemplate(final String defaultTemplate) { + target.setDefaultTemplate(defaultTemplate); + } + + public String getDefaultTemplate() { + return target.getDefaultTemplate(); + } + + public void setIp(final String ip) { + target.setIp(ip); + } + + public void setMaxMachinesOn(final Integer maxMachinesOn) { + target.setMaxMachinesOn(maxMachinesOn); + } + + public void setPassword(final String password) { + target.setPassword(password); + } + + public void setPort(final Integer port) { + target.setPort(port); + } + + public void setUser(final String user) { + target.setUser(user); + } + + @Override + public String toString() { + return "ManagedRack [id=" + getId() + ", name=" + getName() + ", shortDescription=" + getShortDescription() + + ", haEnabled=" + isHaEnabled() + ", nrsq=" + getNrsq() + ", vlanIdMax=" + getVlanIdMax() + ", vlanIdMin=" + + getVlanIdMin() + ", vlanPerVdcReserved=" + getVlanPerVdcReserved() + ", vlansIdAvoided=" + + getVlansIdAvoided() + ", ip=" + getIp() + ", longDescription=" + getLongDescription() + + ", maxMachinesOn=" + getMaxMachinesOn() + ", password=**PROTECTED**, port=" + getPort() + ", user=" + + getUser() + ", defaultTemplate=" + getDefaultTemplate() + "]"; + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/Organization.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/Organization.java new file mode 100644 index 0000000000..f25c104804 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/Organization.java @@ -0,0 +1,94 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.infrastructure; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.domain.DomainWrapper; +import org.jclouds.abiquo.reference.annotations.EnterpriseEdition; +import org.jclouds.rest.RestContext; + +import com.abiquo.server.core.infrastructure.OrganizationDto; + +/** + * Adds high level functionality to {@link OrganizationDto}. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + * @see API: + * http://community.abiquo.com/display/ABI20/RackResource + */ +@EnterpriseEdition +public class Organization extends DomainWrapper { + /** + * Constructor to be used only by the builder. + */ + protected Organization(final RestContext context, final OrganizationDto target) { + super(context, target); + } + + // Delegate Methods + + public String getDescription() { + return target.getDescription(); + } + + public String getDn() { + return target.getDn(); + } + + public String getLevel() { + return target.getLevel(); + } + + public String getName() { + return target.getName(); + } + + public String getStatus() { + return target.getStatus(); + } + + public void setDescription(final String value) { + target.setDescription(value); + } + + public void setDn(final String dn) { + target.setDn(dn); + } + + public void setLevel(final String value) { + target.setLevel(value); + } + + public void setName(final String value) { + target.setName(value); + } + + public void setStatus(final String value) { + target.setStatus(value); + } + + @Override + public String toString() { + return "Organization [name=" + getName() + ", description=" + getDescription() + ", dn=" + getDn() + ", level=" + + getLevel() + ", status=" + getStatus() + "]"; + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/Rack.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/Rack.java new file mode 100644 index 0000000000..945853f042 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/Rack.java @@ -0,0 +1,377 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.infrastructure; + +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.collect.Iterables.filter; + +import java.util.List; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.domain.DomainWrapper; +import org.jclouds.abiquo.reference.ValidationErrors; +import org.jclouds.abiquo.reference.rest.ParentLinkName; +import org.jclouds.rest.RestContext; + +import com.abiquo.server.core.infrastructure.MachineDto; +import com.abiquo.server.core.infrastructure.MachinesDto; +import com.abiquo.server.core.infrastructure.RackDto; +import com.google.common.base.Predicate; +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; + +/** + * Adds high level functionality to {@link RackDto}. Represents unmanaged racks + * in the Abiquo platform. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + * @see API: + * http://community.abiquo.com/display/ABI20/RackResource + */ +public class Rack extends DomainWrapper { + /** The default minimum VLAN id. */ + private static final int DEFAULT_VLAN_ID_MIN = 2; + + /** The default maximum VLAN id. */ + private static final int DEFAULT_VLAN_ID_MAX = 4094; + + /** The default maximum VLAN per virtual datacenter. */ + private static final int DEFAULT_VLAN_PER_VDC = 1; + + /** The default nrsq factor. */ + private static final int DEFAULT_NRSQ = 10; + + /** The datacenter where the rack belongs. */ + private Datacenter datacenter; + + /** + * Constructor to be used only by the builder. + */ + protected Rack(final RestContext context, final RackDto target) { + super(context, target); + } + + // Domain operations + + /** + * Delete the unmanaged rack. + * + * @see API: + * http://community.abiquo.com/display/ABI20/Rack+Resource#RackResource + * #RackResource- DeleteaRack + */ + public void delete() { + context.getApi().getInfrastructureApi().deleteRack(target); + target = null; + } + + /** + * Create a new unmanaged rack in Abiquo. + * + * @see API: http://community.abiquo.com/display/ABI20/RackResource#RackResource + * -CreateanewRack + */ + public void save() { + target = context.getApi().getInfrastructureApi().createRack(datacenter.unwrap(), target); + } + + /** + * Update rack information in the server with the data from this rack. + * + * @see API: + * http://community.abiquo.com/display/ABI20/RackResource#RackResource- + * UpdateanexistingRack + */ + public void update() { + target = context.getApi().getInfrastructureApi().updateRack(target); + } + + // Parent access + /** + * Retrieve the datacenter where this rack is. + * + * @see API: http://community.abiquo.com/display/ABI20/DatacenterResource# + * DatacenterResource- Retrieveadatacenter + */ + public Datacenter getDatacenter() { + Integer datacenterId = target.getIdFromLink(ParentLinkName.DATACENTER); + return wrap(context, Datacenter.class, context.getApi().getInfrastructureApi().getDatacenter(datacenterId)); + } + + // Children access + + /** + * Retrieve the list of physical machines in this rack. + * + * @see API: http://community.abiquo.com/display/ABI20/MachineResource# + * MachineResource- RetrievealistofMachines + */ + public List listMachines() { + MachinesDto machines = context.getApi().getInfrastructureApi().listMachines(target); + return wrap(context, Machine.class, machines.getCollection()); + } + + /** + * Retrieve a filtered list of physical machines in this rack. + * + * @param filter + * Filter to be applied to the list. + * @see API: http://community.abiquo.com/display/ABI20/MachineResource# + * MachineResource- RetrievealistofMachines + */ + public List listMachines(final Predicate filter) { + return Lists.newLinkedList(filter(listMachines(), filter)); + } + + /** + * Retrieve the first physical machine matching the filter within the list of + * machines in this rack. + * + * @param filter + * Filter to be applied to the list. + * @see API: http://community.abiquo.com/display/ABI20/MachineResource# + * MachineResource- RetrievealistofMachines + */ + public Machine findMachine(final Predicate filter) { + return Iterables.getFirst(filter(listMachines(), filter), null); + } + + /** + * Retrieve a single physical machine. + * + * @param id + * Unique ID of the physical machine in this rack. + * @see API: http://community.abiquo.com/display/ABI20/MachineResource# + * MachineResource-RetrieveaMachine + * @return Unmanaged rack with the given id or null if it does + * not exist. + */ + public Machine getMachine(final Integer id) { + MachineDto machine = context.getApi().getInfrastructureApi().getMachine(target, id); + return wrap(context, Machine.class, machine); + } + + // Builder + + public static Builder builder(final RestContext context, final Datacenter datacenter) { + return new Builder(context, datacenter); + } + + public static class Builder { + private RestContext context; + + private Integer id; + + private String name; + + private String shortDescription; + + private boolean haEnabled = false; + + private Integer nrsq = DEFAULT_NRSQ; + + private Integer vlanIdMax = DEFAULT_VLAN_ID_MAX; + + private Integer vlanIdMin = DEFAULT_VLAN_ID_MIN; + + private Integer vlanPerVdcReserved = DEFAULT_VLAN_PER_VDC; + + private String vlansIdAvoided; + + private Datacenter datacenter; + + public Builder(final RestContext context, final Datacenter datacenter) { + super(); + checkNotNull(datacenter, ValidationErrors.NULL_RESOURCE + Datacenter.class); + this.datacenter = datacenter; + this.context = context; + } + + public Builder id(final Integer id) { + this.id = id; + return this; + } + + public Builder name(final String name) { + this.name = name; + return this; + } + + public Builder shortDescription(final String shortDescription) { + this.shortDescription = shortDescription; + return this; + } + + public Builder haEnabled(final boolean haEnabled) { + this.haEnabled = haEnabled; + return this; + } + + public Builder nrsq(final int nrsq) { + this.nrsq = nrsq; + return this; + } + + public Builder vlanIdMax(final int vlanIdMax) { + this.vlanIdMax = vlanIdMax; + return this; + } + + public Builder vlanIdMin(final int vlanIdMin) { + this.vlanIdMin = vlanIdMin; + return this; + } + + public Builder vlanPerVdcReserved(final int vlanPerVdcExpected) { + this.vlanPerVdcReserved = vlanPerVdcExpected; + return this; + } + + public Builder VlansIdAvoided(final String vlansIdAvoided) { + this.vlansIdAvoided = vlansIdAvoided; + return this; + } + + public Builder datacenter(final Datacenter datacenter) { + checkNotNull(datacenter, ValidationErrors.NULL_RESOURCE + Datacenter.class); + this.datacenter = datacenter; + return this; + } + + public Rack build() { + RackDto dto = new RackDto(); + dto.setId(id); + dto.setName(name); + dto.setShortDescription(shortDescription); + dto.setHaEnabled(haEnabled); + dto.setNrsq(nrsq); + dto.setVlanIdMax(vlanIdMax); + dto.setVlanIdMin(vlanIdMin); + dto.setVlanPerVdcReserved(vlanPerVdcReserved); + dto.setVlansIdAvoided(vlansIdAvoided); + Rack rack = new Rack(context, dto); + rack.datacenter = datacenter; + return rack; + } + + public static Builder fromRack(final Rack in) { + return Rack.builder(in.context, in.datacenter).id(in.getId()).name(in.getName()) + .shortDescription(in.getShortDescription()).haEnabled(in.isHaEnabled()).nrsq(in.getNrsq()) + .vlanIdMax(in.getVlanIdMax()).vlanIdMin(in.getVlanIdMin()) + .vlanPerVdcReserved(in.getVlanPerVdcReserved()).VlansIdAvoided(in.getVlansIdAvoided()); + } + } + + // Delegate methods + + public Integer getId() { + return target.getId(); + } + + public String getName() { + return target.getName(); + } + + public String getShortDescription() { + return target.getShortDescription(); + } + + public void setName(final String name) { + target.setName(name); + } + + public void setShortDescription(final String description) { + target.setShortDescription(description); + } + + public void setHaEnabled(final boolean haEnabled) { + target.setHaEnabled(haEnabled); + } + + public boolean isHaEnabled() { + return target.isHaEnabled(); + } + + public Integer getNrsq() { + return target.getNrsq(); + } + + public Integer getVlanIdMax() { + return target.getVlanIdMax(); + } + + public Integer getVlanIdMin() { + return target.getVlanIdMin(); + } + + public Integer getVlanPerVdcReserved() { + return target.getVlanPerVdcReserved(); + } + + public String getVlansIdAvoided() { + return target.getVlansIdAvoided(); + } + + public void setNrsq(final Integer nrsq) { + target.setNrsq(nrsq); + } + + public void setVlanIdMax(final Integer vlanIdMax) { + target.setVlanIdMax(vlanIdMax); + } + + public void setVlanIdMin(final Integer vlanIdMin) { + target.setVlanIdMin(vlanIdMin); + } + + public void setVlanPerVdcReserved(final Integer vlanPerVdcReserved) { + target.setVlanPerVdcReserved(vlanPerVdcReserved); + } + + public void setVlansIdAvoided(final String vlansIdAvoided) { + target.setVlansIdAvoided(vlansIdAvoided); + } + + @Override + public String toString() { + return "Rack [id=" + getId() + ", name=" + getName() + ", description=" + getShortDescription() + ", haEnabled=" + + isHaEnabled() + ", nrsq=" + getNrsq() + ", vlanIdMax=" + getVlanIdMax() + ", vlanIdMin=" + getVlanIdMin() + + ", vlanPerVdcReserved=" + getVlanPerVdcReserved() + ", vlansIdAvoided=" + getVlansIdAvoided() + "]"; + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/RemoteService.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/RemoteService.java new file mode 100644 index 0000000000..aa58936208 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/RemoteService.java @@ -0,0 +1,249 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.infrastructure; + +import static com.google.common.base.Preconditions.checkNotNull; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.domain.DomainWrapper; +import org.jclouds.abiquo.reference.ValidationErrors; +import org.jclouds.abiquo.reference.rest.ParentLinkName; +import org.jclouds.rest.RestContext; + +import com.abiquo.model.enumerator.RemoteServiceType; +import com.abiquo.server.core.infrastructure.DatacenterDto; +import com.abiquo.server.core.infrastructure.RemoteServiceDto; + +/** + * Adds high level functionality to {@link RemoteServiceDto}. The Remote Service + * resource offers the functionality of managing the remote services of a + * datacenter in a logical way. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + * @see API: + * http://community.abiquo.com/display/ABI20/RemoteServiceResource + */ +public class RemoteService extends DomainWrapper { + /** The default status. */ + private static final int DEFAULT_STATUS = 0; + + /** The datacenter using the remote service. */ + private Datacenter datacenter; + + /** + * Constructor to be used only by the builder. + */ + protected RemoteService(final RestContext context, final RemoteServiceDto target) { + super(context, target); + } + + /** + * Delete the remote service. + * + * @see API: http://community.abiquo.com/display/ABI20/RemoteServiceResource# + * RemoteServiceResource- DeleteaRemoteService + */ + public void delete() { + context.getApi().getInfrastructureApi().deleteRemoteService(target); + target = null; + } + + /** + * Create the remote service. + * + * @see API: http://community.abiquo.com/display/ABI20/RemoteServiceResource# + * RemoteServiceResource- CreateaRemoteService + */ + public void save() { + target = context.getApi().getInfrastructureApi().createRemoteService(datacenter.unwrap(), target); + } + + /** + * Update remote service information in the server with the data from this + * remote service. + * + * @see API: http://community.abiquo.com/display/ABI20/RemoteServiceResource# + * RemoteServiceResource- UpdateanexistingRemoteService + */ + public void update() { + target = context.getApi().getInfrastructureApi().updateRemoteService(target); + } + + /** + * Check remote service availability. + * + * @see API: http://community.abiquo.com/display/ABI20/RemoteServiceResource# + * RemoteServiceResource- CheckthestatusofaRemoteService + */ + public boolean isAvailable() { + // If the remote service can not be checked, assume it is available + return !getType().canBeChecked() ? true : context.getApi().getInfrastructureApi().isAvailable(target); + } + + // Parent access + + /** + * Retrieve the datacenter using this remotes service. + * + * @see API: http://community.abiquo.com/display/ABI20/DatacenterResource# + * DatacenterResource- Retrieveadatacenter + */ + public Datacenter getDatacenter() { + Integer datacenterId = target.getIdFromLink(ParentLinkName.DATACENTER); + DatacenterDto dto = context.getApi().getInfrastructureApi().getDatacenter(datacenterId); + datacenter = wrap(context, Datacenter.class, dto); + return datacenter; + } + + public static Builder builder(final RestContext context, final Datacenter datacenter) { + return new Builder(context, datacenter); + } + + public static class Builder { + private RestContext context; + + private Integer id; + + private Datacenter datacenter; + + private String ip; + + private Integer port; + + private RemoteServiceType type; + + private Integer status = DEFAULT_STATUS; + + // To be used only internally by the builder + private String uri; + + public Builder(final RestContext context, final Datacenter datacenter) { + super(); + checkNotNull(datacenter, ValidationErrors.NULL_RESOURCE + Datacenter.class); + this.datacenter = datacenter; + this.context = context; + } + + public Builder datacenter(final Datacenter datacenter) { + checkNotNull(datacenter, ValidationErrors.NULL_RESOURCE + Datacenter.class); + this.datacenter = datacenter; + return this; + } + + public Builder status(final int status) { + this.status = status; + return this; + } + + public Builder type(final RemoteServiceType type) { + this.type = type; + return this; + } + + public Builder ip(final String ip) { + this.ip = ip; + return this; + } + + public Builder port(final int port) { + this.port = port; + return this; + } + + private String generateUri(final String ip, final Integer port, final RemoteServiceType type) { + return type.getDefaultProtocol() + ip + ":" + port + "/" + type.getServiceMapping(); + } + + public RemoteService build() { + if (uri == null) { + checkNotNull(ip, ValidationErrors.MISSING_REQUIRED_FIELD + "ip"); + checkNotNull(type, ValidationErrors.MISSING_REQUIRED_FIELD + "type"); + + uri = generateUri(ip, port == null ? type.getDefaultPort() : port, type); + } + + RemoteServiceDto dto = new RemoteServiceDto(); + dto.setId(id); + dto.setType(type); + dto.setUri(uri); + dto.setStatus(status); + RemoteService remoteservice = new RemoteService(context, dto); + remoteservice.datacenter = datacenter; + return remoteservice; + } + + public static Builder fromRemoteService(final RemoteService in) { + Builder builder = RemoteService.builder(in.context, in.getDatacenter()).status(in.getStatus()) + .type(in.getType()); + builder.uri = in.getUri(); + return builder; + } + } + + // Delegate methods + + public Integer getId() { + return target.getId(); + } + + public RemoteServiceType getType() { + return target.getType(); + } + + public int getStatus() { + return target.getStatus(); + } + + public String getUri() { + return target.getUri(); + } + + public void setStatus(final int status) { + target.setStatus(status); + } + + public void setType(final RemoteServiceType type) { + target.setType(type); + } + + public void setUri(final String uri) { + target.setUri(uri); + } + + @Override + public String toString() { + return "RemoteService [id=" + getId() + ", available=" + isAvailable() + ", type=" + getType() + ", status=" + + getStatus() + ", uri" + getUri() + "]"; + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/StorageDevice.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/StorageDevice.java new file mode 100644 index 0000000000..a56d74962e --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/StorageDevice.java @@ -0,0 +1,482 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.infrastructure; + +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.collect.Iterables.filter; + +import java.util.List; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.domain.DomainWrapper; +import org.jclouds.abiquo.domain.infrastructure.options.StoragePoolOptions; +import org.jclouds.abiquo.reference.ValidationErrors; +import org.jclouds.abiquo.reference.annotations.EnterpriseEdition; +import org.jclouds.abiquo.reference.rest.ParentLinkName; +import org.jclouds.rest.RestContext; + +import com.abiquo.server.core.infrastructure.DatacenterDto; +import com.abiquo.server.core.infrastructure.storage.StorageDeviceDto; +import com.abiquo.server.core.infrastructure.storage.StoragePoolDto; +import com.abiquo.server.core.infrastructure.storage.StoragePoolsDto; +import com.abiquo.server.core.infrastructure.storage.TiersDto; +import com.google.common.base.Predicate; +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; + +/** + * Adds high level functionality to {@link StorageDeviceDto}. The Storage Device + * Resource offers the functionality of managing the external storage. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + * @see API: + * http://community.abiquo.com/display/ABI20/StorageDeviceResource + */ +@EnterpriseEdition +public class StorageDevice extends DomainWrapper { + /** The datacenter where the storage device is. */ + private Datacenter datacenter; + + /** + * Constructor to be used only by the builder. + */ + protected StorageDevice(final RestContext context, final StorageDeviceDto target) { + super(context, target); + } + + /** + * Delete the storage device. + * + * @see API: http://community.abiquo.com/display/ABI20/StorageDeviceResource# + * StorageDeviceResource- Deleteastoragedevice + */ + public void delete() { + context.getApi().getInfrastructureApi().deleteStorageDevice(target); + target = null; + } + + /** + * Create a new storage device. + * + * @see API: http://community.abiquo.com/display/ABI20/StorageDeviceResource# + * StorageDeviceResource- Createastoragedevice + */ + public void save() { + target = context.getApi().getInfrastructureApi().createStorageDevice(datacenter.unwrap(), target); + } + + /** + * Update storage device information in the server with the data from this + * device. + * + * @see API: http://community.abiquo.com/display/ABI20/StorageDeviceResource# + * StorageDeviceResource- Updateastoragedevice + */ + public void update() { + target = context.getApi().getInfrastructureApi().updateStorageDevice(target); + } + + // Parent access + + /** + * Retrieve the datacenter where this storage device is. + * + * @see API: http://community.abiquo.com/display/ABI20/DatacenterResource# + * DatacenterResource- Retrieveadatacenter + */ + public Datacenter getDatacenter() { + Integer datacenterId = target.getIdFromLink(ParentLinkName.DATACENTER); + DatacenterDto dto = context.getApi().getInfrastructureApi().getDatacenter(datacenterId); + datacenter = wrap(context, Datacenter.class, dto); + return datacenter; + } + + // Children access + + /** + * Retrieve the list of storage pools in this device (synchronized with the + * device). + * + * @see API: http://community.abiquo.com/display/ABI20/StoragePoolResource# + * StoragePoolResource- Retrievestoragepools + * @return Synchronized list of storage pools in this device. + */ + public List listRemoteStoragePools() { + StoragePoolsDto storagePools = context.getApi().getInfrastructureApi() + .listStoragePools(target, StoragePoolOptions.builder().sync(true).build()); + + List storagePoolList = wrap(context, StoragePool.class, storagePools.getCollection()); + + for (StoragePool storagePool : storagePoolList) { + storagePool.storageDevice = this; + } + + return storagePoolList; + } + + /** + * Retrieve a filtered list of storage pools in this device (synchronized + * with the device). + * + * @param filter + * Filter to be applied to the list. + * @see API: http://community.abiquo.com/display/ABI20/StoragePoolResource# + * StoragePoolResource- Retrievestoragepools + * @return Filtered synchronized list of storage pools in this device. + */ + public List listRemoteStoragePools(final Predicate filter) { + return Lists.newLinkedList(filter(listRemoteStoragePools(), filter)); + } + + /** + * Retrieve the first storage pool matching the filter within the list of + * storage pools in this device (synchronized with the device). + * + * @param filter + * Filter to be applied to the list. + * @see API: http://community.abiquo.com/display/ABI20/StoragePoolResource# + * StoragePoolResource- Retrievestoragepools + * @return First storage pool (synchronized) matching the filter or + * null if there is none. + */ + public StoragePool findRemoteStoragePool(final Predicate filter) { + return Iterables.getFirst(filter(listRemoteStoragePools(), filter), null); + } + + /** + * Retrieve the list of storage pools in this device from Abiquo database + * (may not be synchronized with the device). + * + * @see API: http://community.abiquo.com/display/ABI20/StoragePoolResource# + * StoragePoolResource- Retrievestoragepools + * @return Unsynchronized list of storage pools in this device. + */ + public List listStoragePools() { + StoragePoolsDto storagePools = context.getApi().getInfrastructureApi() + .listStoragePools(target, StoragePoolOptions.builder().sync(false).build()); + return wrap(context, StoragePool.class, storagePools.getCollection()); + } + + /** + * Retrieve a filtered list of storage pools in this device from Abiquo + * database (may not be synchronized with the device). + * + * @param filter + * Filter to be applied to the list. + * @see API: http://community.abiquo.com/display/ABI20/StoragePoolResource# + * StoragePoolResource- Retrievestoragepools + * @return Filtered unsynchronized list of storage pools in this device. + */ + public List listStoragePools(final Predicate filter) { + return Lists.newLinkedList(filter(listStoragePools(), filter)); + } + + /** + * Retrieve the first storage pool matching the filter within the list of + * storage pools in this device (unsynchronized with the device). + * + * @param filter + * Filter to be applied to the list. + * @see API: http://community.abiquo.com/display/ABI20/StoragePoolResource# + * StoragePoolResource- Retrievestoragepools + * @return First storage pool (unsynchronized) matching the filter or + * null if there is none. + */ + public StoragePool findStoragePool(final Predicate filter) { + return Iterables.getFirst(filter(listStoragePools(), filter), null); + } + + /** + * Retrieve a single storage pool in this device from Abiquo database. + * + * @param id + * Unique ID of the storage device in this datacenter. + * @see API: http://community.abiquo.com/display/ABI20/StoragePoolResource# + * StoragePoolResource- Retrievearegisteredpool + * @return Storage pool with the given id or null if it does not + * exist. + */ + public StoragePool getStoragePool(final String id) { + StoragePoolDto storagePool = context.getApi().getInfrastructureApi().getStoragePool(target, id); + return wrap(context, StoragePool.class, storagePool); + } + + /** + * Retrieve the list of tiers in the datacenter using this device. + * + * @see API: + * http://community.abiquo.com/display/ABI20/TierResource#TierResource- + * Retrievethelistoftiers + * @return List of tiers in the datacenter using this device. + */ + public List listTiersFromDatacenter() { + DatacenterDto datacenter; + + if (this.datacenter == null) { + datacenter = new DatacenterDto(); + datacenter.setId(target.getIdFromLink(ParentLinkName.DATACENTER)); + } else { + datacenter = this.getDatacenter().unwrap(); + } + + TiersDto dto = context.getApi().getInfrastructureApi().listTiers(datacenter); + return DomainWrapper.wrap(context, Tier.class, dto.getCollection()); + } + + /** + * Retrieve a filtered list of tiers in the datacenter using this device. + * + * @param filter + * Filter to be applied to the list. + * @see API: + * http://community.abiquo.com/display/ABI20/TierResource#TierResource- + * Retrievethelistoftiers + * @return Filtered list of tiers in the datacenter using this device. + */ + public List listTiersFromDatacenter(final Predicate filter) { + return Lists.newLinkedList(filter(listTiersFromDatacenter(), filter)); + } + + /** + * Retrieve the first tier matching the filter within the list of tiers in + * the datacenter. + * + * @param filter + * Filter to be applied to the list. + * @see API: http://community.abiquo.com/display/ABI20/StorageDeviceResource# + * StorageDeviceResource- Retrievethelistofstoragedevices + * @return First tier matching the filter or null if there is + * none. + */ + public Tier findTierInDatacenter(final Predicate filter) { + return Iterables.getFirst(filter(listTiersFromDatacenter(), filter), null); + } + + public static Builder builder(final RestContext context, final Datacenter datacenter) { + return new Builder(context, datacenter); + } + + public static class Builder { + private RestContext context; + + private Datacenter datacenter; + + private String iscsiIp; + + private Integer iscsiPort; + + private String managementIp; + + private Integer managementPort; + + private String name; + + private String password; + + private String type; + + private String username; + + public Builder(final RestContext context, final Datacenter datacenter) { + super(); + checkNotNull(datacenter, ValidationErrors.NULL_RESOURCE + Datacenter.class); + this.datacenter = datacenter; + this.context = context; + } + + public Builder datacenter(final Datacenter datacenter) { + checkNotNull(datacenter, ValidationErrors.NULL_RESOURCE + Datacenter.class); + this.datacenter = datacenter; + return this; + } + + public Builder iscsiIp(final String iscsiIp) { + this.iscsiIp = iscsiIp; + return this; + } + + public Builder iscsiPort(final int iscsiPort) { + this.iscsiPort = iscsiPort; + return this; + } + + public Builder password(final String password) { + this.password = password; + return this; + } + + public Builder name(final String name) { + this.name = name; + return this; + } + + public Builder managementPort(final int managementPort) { + this.managementPort = managementPort; + return this; + } + + public Builder managementIp(final String managementIp) { + this.managementIp = managementIp; + return this; + } + + public Builder type(final String type) { + this.type = type; + return this; + } + + public Builder username(final String username) { + this.username = username; + return this; + } + + public StorageDevice build() { + StorageDeviceDto dto = new StorageDeviceDto(); + dto.setIscsiIp(iscsiIp); + dto.setIscsiPort(iscsiPort); + dto.setManagementIp(managementIp); + dto.setManagementPort(managementPort); + dto.setName(name); + dto.setPassword(password); + dto.setStorageTechnology(type); + dto.setUsername(username); + StorageDevice storageDevice = new StorageDevice(context, dto); + storageDevice.datacenter = datacenter; + return storageDevice; + } + + public static Builder fromStorageDevice(final StorageDevice in) { + Builder builder = StorageDevice.builder(in.context, in.getDatacenter()).iscsiIp(in.getIscsiIp()) + .iscsiPort(in.getIscsiPort()).managementIp(in.getManagementIp()).managementPort(in.getManagementPort()) + .name(in.getName()).password(in.getPassword()).type(in.getType()).username(in.getUsername()); + + return builder; + } + } + + // Delegate methods + + public Integer getId() { + return target.getId(); + } + + public String getIscsiIp() { + return target.getIscsiIp(); + } + + public int getIscsiPort() { + return target.getIscsiPort(); + } + + public String getManagementIp() { + return target.getManagementIp(); + } + + public int getManagementPort() { + return target.getManagementPort(); + } + + public String getName() { + return target.getName(); + } + + public String getPassword() { + return target.getPassword(); + } + + public String getType() { + return target.getStorageTechnology(); + } + + public String getUsername() { + return target.getUsername(); + } + + public void setIscsiIp(final String iscsiIp) { + target.setIscsiIp(iscsiIp); + } + + public void setIscsiPort(final int iscsiPort) { + target.setIscsiPort(iscsiPort); + } + + public void setManagementIp(final String managementIp) { + target.setManagementIp(managementIp); + } + + public void setManagementPort(final int managementPort) { + target.setManagementPort(managementPort); + } + + public void setName(final String name) { + target.setName(name); + } + + public void setPassword(final String password) { + target.setPassword(password); + } + + public void setType(final String type) { + target.setStorageTechnology(type); + } + + public void setUsername(final String username) { + target.setUsername(username); + } + + @Override + public String toString() { + return "StorageDevice [id=" + getId() + ", iscsiIp=" + getIscsiIp() + ", iscsiPort=" + getIscsiPort() + + ", managementIp=" + getManagementIp() + ", managementPort=" + getManagementPort() + ", name=" + getName() + + ", password=" + getPassword() + ", type=" + getType() + ", user=" + getUsername() + "]"; + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/StorageDeviceMetadata.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/StorageDeviceMetadata.java new file mode 100644 index 0000000000..2e4e436221 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/StorageDeviceMetadata.java @@ -0,0 +1,61 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.infrastructure; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.domain.DomainWrapper; +import org.jclouds.rest.RestContext; + +import com.abiquo.server.core.infrastructure.storage.StorageDeviceMetadataDto; + +/** + * metadata describing a Storage Device. + * + * @author Ignasi Barrera + */ +public class StorageDeviceMetadata extends DomainWrapper { + /** + * Constructor to be used only by the builder. + */ + protected StorageDeviceMetadata(final RestContext context, + final StorageDeviceMetadataDto target) { + super(context, target); + } + + // Delegate methods + + public String getType() { + return target.getType(); + } + + public int getDefaultManagementPort() { + return target.getDefaultManagementPort(); + } + + public int getDefaultIscsiPort() { + return target.getDefaultIscsiPort(); + } + + public boolean requiresAuthentication() { + return target.isRequiresAuthentication(); + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/StoragePool.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/StoragePool.java new file mode 100644 index 0000000000..5468bde79d --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/StoragePool.java @@ -0,0 +1,354 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.infrastructure; + +import static com.google.common.base.Preconditions.checkNotNull; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.domain.DomainWrapper; +import org.jclouds.abiquo.domain.config.Privilege; +import org.jclouds.abiquo.domain.infrastructure.options.StoragePoolOptions; +import org.jclouds.abiquo.reference.ValidationErrors; +import org.jclouds.abiquo.reference.annotations.EnterpriseEdition; +import org.jclouds.abiquo.reference.rest.ParentLinkName; +import org.jclouds.abiquo.rest.internal.ExtendedUtils; +import org.jclouds.http.HttpResponse; +import org.jclouds.http.functions.ParseXMLWithJAXB; +import org.jclouds.rest.RestContext; + +import com.abiquo.model.rest.RESTLink; +import com.abiquo.server.core.infrastructure.storage.StorageDeviceDto; +import com.abiquo.server.core.infrastructure.storage.StoragePoolDto; +import com.abiquo.server.core.infrastructure.storage.TierDto; +import com.google.inject.TypeLiteral; + +/** + * Adds high level functionality to {@link StoragePoolDto}. The Storage Pool + * Resource allows you to perform any administrative task for remote pools. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + * @see API: + * http://community.abiquo.com/display/ABI20/StoragePoolResource + */ +@EnterpriseEdition +public class StoragePool extends DomainWrapper { + /** The default value for the used space. */ + private static final long DEFAULT_USED_SIZE = 0; + + /** The datacenter where the storage device is. */ + // Package protected to allow the storage device to be set automatically when + // discovering the + // pools in a device. + StorageDevice storageDevice; + + /** + * Constructor to be used only by the builder. + */ + protected StoragePool(final RestContext context, final StoragePoolDto target) { + super(context, target); + } + + // Domain operations + + /** + * Delete the storage pool. + * + * @see API: http://community.abiquo.com/display/ABI20/StoragePoolResource# + * StoragePoolResource- Deleteastoragepool + */ + public void delete() { + context.getApi().getInfrastructureApi().deleteStoragePool(target); + target = null; + } + + /** + * Create a storage pool. Create a storage pool means registering an existing + * storage pool obtained from {@link StorageDevice#listRemoteStoragePools} + * method and saving it. The Storage Pools must be associated with a Tier + * using {@link #setTier}. + * + * @see API: http://community.abiquo.com/display/ABI20/StoragePoolResource# + * StoragePoolResource- Createastoragepoolwithatierlink + */ + public void save() { + target = context.getApi().getInfrastructureApi().createStoragePool(storageDevice.unwrap(), target); + } + + /** + * Update pool information in the server with the data from this pool. + * Storage pool parameters cannot be updated by a user, so the parameters are + * only a representation of the remote pool. Although the whole storage pool + * entity is sent to the API in the update call, the only thing a user can + * change is the tier that the pool belongs to by calling {@link #setTier}. + * + * @see API: http://community.abiquo.com/display/ABI20/Storage+Pool+Resource# + * StoragePoolResource- UpdateaStoragePool + */ + public void update() { + target = context.getApi().getInfrastructureApi().updateStoragePool(target); + } + + public void refresh() { + target = context.getApi().getInfrastructureApi() + .refreshStoragePool(target, StoragePoolOptions.builder().sync(true).build()); + } + + /** + * Define the tier in which the pool will be added. + * + * @see API: http://community.abiquo.com/display/ABI20/StoragePoolResource# + * StoragePoolResource- Createastoragepoolwithatierlink + */ + public void setTier(final Tier tier) { + checkNotNull(tier, ValidationErrors.NULL_RESOURCE + Privilege.class); + checkNotNull(tier.getId(), ValidationErrors.MISSING_REQUIRED_FIELD + " id in " + Tier.class); + + this.updateLink(target, ParentLinkName.TIER, tier.unwrap(), "edit"); + } + + // Parent access + + /** + * Get the device where the pool belongs. + * + * @see API: http://community.abiquo.com/display/ABI20/StorageDeviceResource# + * StorageDeviceResource- Retrieveastoragedevice + */ + public StorageDevice getStorageDevice() { + RESTLink link = checkNotNull(target.searchLink(ParentLinkName.STORAGE_DEVICE), + ValidationErrors.MISSING_REQUIRED_LINK + " " + ParentLinkName.STORAGE_DEVICE); + + ExtendedUtils utils = (ExtendedUtils) context.getUtils(); + HttpResponse response = utils.getAbiquoHttpClient().get(link); + + ParseXMLWithJAXB parser = new ParseXMLWithJAXB(utils.getXml(), + TypeLiteral.get(StorageDeviceDto.class)); + + return wrap(context, StorageDevice.class, parser.apply(response)); + } + + // Children access + + /** + * Get the tier assigned to the pool. The storage pool needs to be persisted + * in Abiquo first. + * + * @return The tier assinged to this storage pool. + */ + public Tier getTier() { + RESTLink link = checkNotNull(target.searchLink(ParentLinkName.TIER), ValidationErrors.MISSING_REQUIRED_LINK + " " + + ParentLinkName.TIER); + + ExtendedUtils utils = (ExtendedUtils) context.getUtils(); + HttpResponse response = utils.getAbiquoHttpClient().get(link); + + ParseXMLWithJAXB parser = new ParseXMLWithJAXB(utils.getXml(), TypeLiteral.get(TierDto.class)); + + return wrap(context, Tier.class, parser.apply(response)); + } + + // Builder + + public static Builder builder(final RestContext context, final StorageDevice storageDevice) { + return new Builder(context, storageDevice); + } + + public static class Builder { + private RestContext context; + + private StorageDevice storageDevice; + + private Long availableSizeInMb; + + // The enabled flag is still not used. It will be added when Abiquo + // includes anstorage + // allocator + + // private Boolean enabled; + + private String name; + + private Long totalSizeInMb; + + private Long usedSizeInMb = DEFAULT_USED_SIZE; + + public Builder(final RestContext context, final StorageDevice storageDevice) { + super(); + checkNotNull(storageDevice, ValidationErrors.NULL_RESOURCE + StorageDevice.class); + this.storageDevice = storageDevice; + this.context = context; + } + + public Builder storageDevice(final StorageDevice storageDevice) { + checkNotNull(storageDevice, ValidationErrors.NULL_RESOURCE + StorageDevice.class); + this.storageDevice = storageDevice; + return this; + } + + /** + * @deprecated This value is no longer used in Abiquo and will be removed + * in future versions. + */ + @Deprecated + public Builder availableSizeInMb(final long availableSizeInMb) { + this.availableSizeInMb = availableSizeInMb; + return this; + } + + public Builder name(final String name) { + this.name = name; + return this; + } + + // The enabled flag is still not used. It will be added when Abiquo + // includes anstorage + // allocator + + // public Builder enabled(final boolean enabled) + // { + // this.enabled = enabled; + // return this; + // } + + public Builder totalSizeInMb(final long totalSizeInMb) { + this.totalSizeInMb = totalSizeInMb; + if (availableSizeInMb == null) { + availableSizeInMb = totalSizeInMb; + } + return this; + } + + /** + * @deprecated This value is no longer used in Abiquo and will be removed + * in future versions. + */ + @Deprecated + public Builder usedSizeInMb(final long usedSizeInMb) { + this.usedSizeInMb = usedSizeInMb; + return this; + } + + public StoragePool build() { + StoragePoolDto dto = new StoragePoolDto(); + dto.setAvailableSizeInMb(availableSizeInMb); + + // The enabled flag is still not used. It will be added when Abiquo + // includes anstorage + // allocator + // dto.setEnabled(enabled); + + dto.setName(name); + dto.setTotalSizeInMb(totalSizeInMb); + dto.setUsedSizeInMb(usedSizeInMb); + StoragePool storagePool = new StoragePool(context, dto); + storagePool.storageDevice = storageDevice; + return storagePool; + } + + public static Builder fromStoragePool(final StoragePool in) { + Builder builder = StoragePool.builder(in.context, in.getStorageDevice()) + .availableSizeInMb(in.getAvailableSizeInMb())/* + * .enabled(in. + * getEnabled()) + */ + .totalSizeInMb(in.getTotalSizeInMb()).usedSizeInMb(in.getUsedSizeInMb()); + + return builder; + } + } + + // Delegate methods + + /** + * @deprecated This value is no longer used in Abiquo and will be removed in + * future versions. + */ + @Deprecated + public long getAvailableSizeInMb() { + return target.getAvailableSizeInMb(); + } + + // The enabled flag is still not used. It will be added when Abiquo includes + // anstorage + // allocator + + // public boolean getEnabled() + // { + // return target.getEnabled(); + // } + + public String getName() { + return target.getName(); + } + + public long getTotalSizeInMb() { + return target.getTotalSizeInMb(); + } + + /** + * @deprecated This value is no longer used in Abiquo and will be removed in + * future versions. + */ + @Deprecated + public long getUsedSizeInMb() { + return target.getUsedSizeInMb(); + } + + // The enabled flag is still not used. It will be added when Abiquo includes + // anstorage + // allocator + + // public void setEnabled(final boolean enabled) + // { + // target.setEnabled(enabled); + // } + + public void setName(final String name) { + target.setName(name); + } + + public void setTotalSizeInMb(final long totalSizeInMb) { + target.setTotalSizeInMb(totalSizeInMb); + } + + // Readonly property + public String getUUID() { + return target.getIdStorage(); + } + + @Override + public String toString() { + return "StoragePool [name=" + getName() + ", totalSizeInMb=" + getTotalSizeInMb() + ", uuid=" + getUUID() + "]"; + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/Tier.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/Tier.java new file mode 100644 index 0000000000..f8c8aa0e4d --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/Tier.java @@ -0,0 +1,177 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.infrastructure; + +import static com.google.common.collect.Iterables.filter; + +import java.util.List; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.domain.DomainWrapper; +import org.jclouds.abiquo.reference.annotations.EnterpriseEdition; +import org.jclouds.abiquo.reference.rest.ParentLinkName; +import org.jclouds.rest.RestContext; + +import com.abiquo.server.core.infrastructure.DatacenterDto; +import com.abiquo.server.core.infrastructure.storage.StoragePoolsDto; +import com.abiquo.server.core.infrastructure.storage.TierDto; +import com.google.common.base.Predicate; +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; + +/** + * Adds high level functionality to {@link TierDto}. The Tier Resource offers + * the functionality of managing the logic of QoS volume management. These are + * only logical levels of QoS and the real QoS (networking speed, volume + * replication, availability) must be configured manually in the infrastructure. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + * @see API: + * http://community.abiquo.com/display/ABI20/TierResource + */ +@EnterpriseEdition +public class Tier extends DomainWrapper { + /** The datacenter where the tier belongs. */ + private Datacenter datacenter; + + /** + * Constructor to be used only by the builder. + */ + protected Tier(final RestContext context, final TierDto target) { + super(context, target); + } + + // Domain operations + + /** + * Update tier information in the server with the data from this tier. + * + * @see API: + * http://community.abiquo.com/display/ABI20/TierResource#TierResource- + * Updateatier + */ + public void update() { + target = context.getApi().getInfrastructureApi().updateTier(target); + } + + /** + * Retrieve the list of storage pools in this tier. + * + * @see API: http://community.abiquo.com/display/ABI20/StoragePoolResource# + * StoragePoolResource- Retrievestoragepools + * @return List of storage pools in this tier. + */ + public List listStoragePools() { + StoragePoolsDto storagePools = context.getApi().getInfrastructureApi().listStoragePools(target); + return wrap(context, StoragePool.class, storagePools.getCollection()); + } + + /** + * Retrieve a filtered list of storage pools in this tier. + * + * @param filter + * Filter to be applied to the list. + * @see API: http://community.abiquo.com/display/ABI20/StoragePoolResource# + * StoragePoolResource- Retrievestoragepools + * @return Filtered list of storage pools in this tier. + */ + public List listStoragePools(final Predicate filter) { + return Lists.newLinkedList(filter(listStoragePools(), filter)); + } + + /** + * Retrieve the first storage pool matching the filter within the list of + * pools in this tier. + * + * @param filter + * Filter to be applied to the list. + * @see API: http://community.abiquo.com/display/ABI20/StoragePoolResource# + * StoragePoolResource- Retrievestoragepools + * @return First storage pool matching the filter or null if + * there is none. + */ + public StoragePool findStoragePool(final Predicate filter) { + return Iterables.getFirst(filter(listStoragePools(), filter), null); + } + + // Parent access + + /** + * Retrieve the datacenter where this tier is. + * + * @see API: http://community.abiquo.com/display/ABI20/DatacenterResource# + * DatacenterResource- Retrieveadatacenter + */ + public Datacenter getDatacenter() { + Integer datacenterId = target.getIdFromLink(ParentLinkName.DATACENTER); + DatacenterDto dto = context.getApi().getInfrastructureApi().getDatacenter(datacenterId); + datacenter = wrap(context, Datacenter.class, dto); + return datacenter; + } + + // Delegate methods + + public String getDescription() { + return target.getDescription(); + } + + public boolean getEnabled() { + return target.getEnabled(); + } + + public Integer getId() { + return target.getId(); + } + + public String getName() { + return target.getName(); + } + + public void setDescription(final String description) { + target.setDescription(description); + } + + public void setEnabled(final boolean enabled) { + target.setEnabled(enabled); + } + + public void setName(final String name) { + target.setName(name); + } + + @Override + public String toString() { + return "Tier [id=" + getId() + ", description=" + getDescription() + ", enabled=" + getEnabled() + ", name=" + + getName() + "]"; + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/options/DatacenterOptions.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/options/DatacenterOptions.java new file mode 100644 index 0000000000..d8d56358ee --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/options/DatacenterOptions.java @@ -0,0 +1,57 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.infrastructure.options; + +import org.jclouds.http.options.BaseHttpRequestOptions; + +/** + * Available options to query datacenters. + * + * @author Francesc Montserrat + */ +public class DatacenterOptions extends BaseHttpRequestOptions { + public static Builder builder() { + return new Builder(); + } + + @Override + protected Object clone() throws CloneNotSupportedException { + DatacenterOptions options = new DatacenterOptions(); + options.queryParameters.putAll(queryParameters); + return options; + } + + public static class Builder { + private String ip; + + public Builder ip(final String ip) { + this.ip = ip; + return this; + } + + public DatacenterOptions build() { + DatacenterOptions options = new DatacenterOptions(); + if (ip != null) { + options.queryParameters.put("ip", ip); + } + return options; + } + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/options/IpmiOptions.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/options/IpmiOptions.java new file mode 100644 index 0000000000..4d691e1060 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/options/IpmiOptions.java @@ -0,0 +1,61 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.infrastructure.options; + +import org.jclouds.http.options.BaseHttpRequestOptions; + +/** + * Available options to query ipmi config. + * + * @author scastro + */ +public class IpmiOptions extends BaseHttpRequestOptions { + public static Builder builder() { + return new Builder(); + } + + @Override + protected Object clone() throws CloneNotSupportedException { + IpmiOptions options = new IpmiOptions(); + options.queryParameters.putAll(queryParameters); + return options; + } + + public static class Builder { + private Integer port; + + /** + * Set the optional hypervisor port. + */ + public Builder port(final int port) { + this.port = port; + return this; + } + + public IpmiOptions build() { + IpmiOptions options = new IpmiOptions(); + if (port != null) { + options.queryParameters.put("port", port.toString()); + } + + return options; + } + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/options/MachineOptions.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/options/MachineOptions.java new file mode 100644 index 0000000000..bd37a73ba8 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/options/MachineOptions.java @@ -0,0 +1,75 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.infrastructure.options; + +import org.jclouds.http.options.BaseHttpRequestOptions; + +/** + * Available options to query machines. + * + * @author Francesc Montserrat + */ +public class MachineOptions extends BaseHttpRequestOptions { + public static Builder builder() { + return new Builder(); + } + + @Override + protected Object clone() throws CloneNotSupportedException { + MachineOptions options = new MachineOptions(); + options.queryParameters.putAll(queryParameters); + return options; + } + + public static class Builder { + private Integer port; + + private Boolean sync; + + /** + * Set the optional hypervisor port. + */ + public Builder port(final int port) { + this.port = port; + return this; + } + + /** + * Set the optional sync param. + */ + public Builder sync(final boolean sync) { + this.sync = sync; + return this; + } + + public MachineOptions build() { + MachineOptions options = new MachineOptions(); + if (port != null) { + options.queryParameters.put("port", port.toString()); + } + + if (sync != null) { + options.queryParameters.put("sync", sync.toString()); + } + + return options; + } + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/options/StoragePoolOptions.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/options/StoragePoolOptions.java new file mode 100644 index 0000000000..77b73fe3b5 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/infrastructure/options/StoragePoolOptions.java @@ -0,0 +1,64 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.infrastructure.options; + +import org.jclouds.abiquo.reference.annotations.EnterpriseEdition; +import org.jclouds.http.options.BaseHttpRequestOptions; + +/** + * Available options to query storage pools. + * + * @author Francesc Montserrat + */ + +@EnterpriseEdition +public class StoragePoolOptions extends BaseHttpRequestOptions { + public static Builder builder() { + return new Builder(); + } + + @Override + protected Object clone() throws CloneNotSupportedException { + StoragePoolOptions options = new StoragePoolOptions(); + options.queryParameters.putAll(queryParameters); + return options; + } + + public static class Builder { + private Boolean sync; + + /** + * Set the optional sync param. + */ + public Builder sync(final boolean sync) { + this.sync = sync; + return this; + } + + public StoragePoolOptions build() { + StoragePoolOptions options = new StoragePoolOptions(); + if (sync != null) { + options.queryParameters.put("sync", sync.toString()); + } + + return options; + } + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/network/AbstractPublicIp.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/network/AbstractPublicIp.java new file mode 100644 index 0000000000..bda42fbbb9 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/network/AbstractPublicIp.java @@ -0,0 +1,60 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.network; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.rest.RestContext; + +import com.abiquo.server.core.infrastructure.network.AbstractInfrastructureIpDto; + +/** + * Adds generic high level functionality to {@link AbstractInfrastructureIpDto}. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +public abstract class AbstractPublicIp> extends Ip { + /** + * Constructor to be used only by the builder. + */ + protected AbstractPublicIp(final RestContext context, final T target) { + super(context, target); + } + + // Delegate methods + + public boolean isAvailable() { + return target.isAvailable(); + } + + public boolean isQuarantine() { + return target.isQuarantine(); + } + + public void setAvailable(final boolean available) { + target.setAvailable(available); + } + + public void setQuarantine(final boolean quarantine) { + target.setQuarantine(quarantine); + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/network/ExternalIp.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/network/ExternalIp.java new file mode 100644 index 0000000000..1c546f4cab --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/network/ExternalIp.java @@ -0,0 +1,81 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.network; + +import static com.google.common.base.Preconditions.checkNotNull; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.reference.ValidationErrors; +import org.jclouds.abiquo.reference.rest.ParentLinkName; +import org.jclouds.abiquo.rest.internal.ExtendedUtils; +import org.jclouds.http.HttpResponse; +import org.jclouds.http.functions.ParseXMLWithJAXB; +import org.jclouds.rest.RestContext; + +import com.abiquo.model.enumerator.NetworkType; +import com.abiquo.model.rest.RESTLink; +import com.abiquo.server.core.infrastructure.network.ExternalIpDto; +import com.abiquo.server.core.infrastructure.network.VLANNetworkDto; +import com.google.inject.TypeLiteral; + +/** + * Adds generic high level functionality to {@link ExternalIpDto}. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +public class ExternalIp extends AbstractPublicIp { + /** + * Constructor to be used only by the builder. + */ + protected ExternalIp(final RestContext context, final ExternalIpDto target) { + super(context, target); + } + + // Domain operations + + @Override + public ExternalNetwork getNetwork() { + RESTLink link = checkNotNull(target.searchLink(ParentLinkName.EXTERNAL_NETWORK), + ValidationErrors.MISSING_REQUIRED_LINK + " " + ParentLinkName.EXTERNAL_NETWORK); + + ExtendedUtils utils = (ExtendedUtils) context.getUtils(); + HttpResponse response = utils.getAbiquoHttpClient().get(link); + + ParseXMLWithJAXB parser = new ParseXMLWithJAXB(utils.getXml(), + TypeLiteral.get(VLANNetworkDto.class)); + + return wrap(context, ExternalNetwork.class, parser.apply(response)); + } + + @Override + public NetworkType getNetworkType() { + return NetworkType.EXTERNAL; + } + + @Override + public String toString() { + return "ExternalIp [networkType=" + getNetworkType() + ", available=" + isAvailable() + ", quarantine=" + + isQuarantine() + ", id=" + getId() + ", ip=" + getIp() + ", mac=" + getMac() + ", name=" + getName() + + ", networkName=" + getNetworkName() + "]"; + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/network/ExternalNetwork.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/network/ExternalNetwork.java new file mode 100644 index 0000000000..a005666289 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/network/ExternalNetwork.java @@ -0,0 +1,229 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.network; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.List; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.domain.enterprise.Enterprise; +import org.jclouds.abiquo.domain.infrastructure.Datacenter; +import org.jclouds.abiquo.domain.network.options.IpOptions; +import org.jclouds.abiquo.reference.ValidationErrors; +import org.jclouds.abiquo.reference.annotations.EnterpriseEdition; +import org.jclouds.abiquo.reference.rest.ParentLinkName; +import org.jclouds.abiquo.rest.internal.ExtendedUtils; +import org.jclouds.http.HttpResponse; +import org.jclouds.http.functions.ParseXMLWithJAXB; +import org.jclouds.rest.RestContext; + +import com.abiquo.model.enumerator.NetworkType; +import com.abiquo.model.rest.RESTLink; +import com.abiquo.server.core.enterprise.EnterpriseDto; +import com.abiquo.server.core.infrastructure.DatacenterDto; +import com.abiquo.server.core.infrastructure.network.ExternalIpDto; +import com.abiquo.server.core.infrastructure.network.ExternalIpsDto; +import com.abiquo.server.core.infrastructure.network.VLANNetworkDto; +import com.google.inject.TypeLiteral; + +/** + * Adds high level functionality to external {@link VLANNetworkDto}. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + * @see API: http://community.abiquo.com/display/ABI20/Public+Network+Resource + */ +@EnterpriseEdition +public class ExternalNetwork extends Network { + /** The datacenter where the network belongs. */ + private Datacenter datacenter; + + /** The enterprise where the network belongs. */ + private Enterprise enterprise; + + /** + * Constructor to be used only by the builder. + */ + protected ExternalNetwork(final RestContext context, final VLANNetworkDto target) { + super(context, target); + } + + /** + * @see API: http://community.abiquo.com/display/ABI20/Public+Network+Resource# + * PublicNetworkResource -DeleteanExternalNetwork + */ + @Override + public void delete() { + context.getApi().getInfrastructureApi().deleteNetwork(target); + target = null; + } + + /** + * @see API: http://community.abiquo.com/display/ABI20/Public+Network+Resource# + * PublicNetworkResource -CreateanewExternalNetwork + */ + @Override + public void save() { + this.addEnterpriseLink(); + target = context.getApi().getInfrastructureApi().createNetwork(datacenter.unwrap(), target); + } + + /** + * @see API: http://community.abiquo.com/display/ABI20/Public+Network+Resource# + * PublicNetworkResource -UpdateanExternalNetwork + */ + @Override + public void update() { + target = context.getApi().getInfrastructureApi().updateNetwork(target); + } + + /** + * @see API: http://community.abiquo.com/display/ABI20/Public+IPs+Resource# + * PublicIPsResource- ReturnthelistofIPsforaPublicNetwork + */ + @Override + public List listIps(final IpOptions options) { + ExternalIpsDto ips = context.getApi().getInfrastructureApi().listExternalIps(target, options); + return wrap(context, ExternalIp.class, ips.getCollection()); + } + + @Override + public ExternalIp getIp(final Integer id) { + ExternalIpDto ip = context.getApi().getInfrastructureApi().getExternalIp(target, id); + return wrap(context, ExternalIp.class, ip); + } + + // Parent access + + public Enterprise getEnterprise() { + RESTLink link = checkNotNull(target.searchLink(ParentLinkName.ENTERPRISE), ValidationErrors.MISSING_REQUIRED_LINK + + " " + ParentLinkName.ENTERPRISE); + + ExtendedUtils utils = (ExtendedUtils) context.getUtils(); + HttpResponse response = utils.getAbiquoHttpClient().get(link); + + ParseXMLWithJAXB parser = new ParseXMLWithJAXB(utils.getXml(), + TypeLiteral.get(EnterpriseDto.class)); + + enterprise = wrap(context, Enterprise.class, parser.apply(response)); + return enterprise; + } + + public Datacenter getDatacenter() { + RESTLink link = checkNotNull(target.searchLink(ParentLinkName.DATACENTER), ValidationErrors.MISSING_REQUIRED_LINK + + " " + ParentLinkName.DATACENTER); + + ExtendedUtils utils = (ExtendedUtils) context.getUtils(); + HttpResponse response = utils.getAbiquoHttpClient().get(link); + + ParseXMLWithJAXB parser = new ParseXMLWithJAXB(utils.getXml(), + TypeLiteral.get(DatacenterDto.class)); + + datacenter = wrap(context, Datacenter.class, parser.apply(response)); + return datacenter; + } + + private void addEnterpriseLink() { + checkNotNull(enterprise, ValidationErrors.NULL_RESOURCE + Enterprise.class); + checkNotNull(enterprise.getId(), ValidationErrors.MISSING_REQUIRED_FIELD + " id in " + Enterprise.class); + + RESTLink link = enterprise.unwrap().getEditLink(); + checkNotNull(link, ValidationErrors.MISSING_REQUIRED_LINK); + + target.addLink(new RESTLink("enterprise", link.getHref())); + } + + // Builder + + public static Builder builder(final RestContext context, final Datacenter datacenter, + final Enterprise enterprise) { + return new Builder(context, datacenter, enterprise); + } + + public static class Builder extends NetworkBuilder { + private Datacenter datacenter; + + private Enterprise enterprise; + + public Builder(final RestContext context, final Datacenter datacenter, + final Enterprise enterprise) { + super(context); + checkNotNull(datacenter, ValidationErrors.NULL_RESOURCE + Datacenter.class); + checkNotNull(datacenter, ValidationErrors.NULL_RESOURCE + Enterprise.class); + this.datacenter = datacenter; + this.enterprise = enterprise; + this.context = context; + } + + public Builder datacenter(final Datacenter datacenter) { + this.datacenter = datacenter; + return this; + } + + public Builder enterprise(final Enterprise enterprise) { + this.enterprise = enterprise; + return this; + } + + public ExternalNetwork build() { + VLANNetworkDto dto = new VLANNetworkDto(); + dto.setName(name); + dto.setTag(tag); + dto.setGateway(gateway); + dto.setAddress(address); + dto.setMask(mask); + dto.setPrimaryDNS(primaryDNS); + dto.setSecondaryDNS(secondaryDNS); + dto.setSufixDNS(sufixDNS); + dto.setDefaultNetwork(defaultNetwork == null ? Boolean.FALSE : defaultNetwork); + dto.setUnmanaged(Boolean.FALSE); + dto.setType(NetworkType.EXTERNAL); + + ExternalNetwork network = new ExternalNetwork(context, dto); + network.datacenter = datacenter; + network.enterprise = enterprise; + + return network; + } + + public static Builder fromExternalNetwork(final ExternalNetwork in) { + return ExternalNetwork.builder(in.context, in.datacenter, in.enterprise).name(in.getName()).tag(in.getTag()) + .gateway(in.getGateway()).address(in.getAddress()).mask(in.getMask()).primaryDNS(in.getPrimaryDNS()) + .secondaryDNS(in.getSecondaryDNS()).sufixDNS(in.getSufixDNS()).defaultNetwork(in.getDefaultNetwork()); + } + } + + @Override + public String toString() { + return "External " + super.toString(); + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/network/Ip.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/network/Ip.java new file mode 100644 index 0000000000..c4d683eb35 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/network/Ip.java @@ -0,0 +1,77 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.network; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.domain.DomainWrapper; +import org.jclouds.rest.RestContext; + +import com.abiquo.model.enumerator.NetworkType; +import com.abiquo.server.core.infrastructure.network.AbstractIpDto; + +/** + * Adds generic high level functionality to {@link AbstractIpDto}. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +public abstract class Ip> extends DomainWrapper { + /** + * Constructor to be used only by the builder. + */ + protected Ip(final RestContext context, final T target) { + super(context, target); + } + + // Domain operations + + public abstract N getNetwork(); + + public abstract NetworkType getNetworkType(); + + // Delegate methods + + public Integer getId() { + return target.getId(); + } + + public String getIp() { + return target.getIp(); + } + + public String getMac() { + return target.getMac(); + } + + public String getName() { + return target.getName(); + } + + public String getNetworkName() { + return target.getNetworkName(); + } + + @Override + public String toString() { + return "Ip [id=" + getId() + ", ip=" + getIp() + ", mac=" + getMac() + ", name=" + getName() + ", networkName=" + + getNetworkName() + "]"; + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/network/Network.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/network/Network.java new file mode 100644 index 0000000000..b4d373e806 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/network/Network.java @@ -0,0 +1,329 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.network; + +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.collect.Iterables.filter; + +import java.util.List; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.domain.DomainWrapper; +import org.jclouds.abiquo.domain.network.options.IpOptions; +import org.jclouds.abiquo.predicates.network.IpPredicates; +import org.jclouds.abiquo.reference.ValidationErrors; +import org.jclouds.rest.RestContext; + +import com.abiquo.model.enumerator.NetworkType; +import com.abiquo.server.core.infrastructure.network.VLANNetworkDto; +import com.google.common.base.Predicate; +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; + +/** + * Adds generic high level functionality to {@link VLANNetworkDto}. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +public abstract class Network> extends DomainWrapper { + /** + * Constructor to be used only by the builder. + */ + protected Network(final RestContext context, final VLANNetworkDto target) { + super(context, target); + } + + // Domain operations + + public abstract void save(); + + public abstract void update(); + + public abstract void delete(); + + public abstract List listIps(IpOptions options); + + public abstract T getIp(Integer id); + + public List listIps() { + // Disable pagination by default + return listIps(IpOptions.builder().disablePagination().build()); + } + + public List listIps(final Predicate filter) { + return Lists.newLinkedList(filter(listIps(), filter)); + } + + public T findIp(final Predicate filter) { + return Iterables.getFirst(filter(listIps(), filter), null); + } + + public List listUnusedIps() { + return listIps(IpPredicates. notUsed()); + } + + public T findUnusedIp(final Predicate filter) { + return Iterables.getFirst(filter(listUnusedIps(), filter), null); + } + + // Builder + + public static class NetworkBuilder> { + protected RestContext context; + + protected String name; + + protected Integer tag; + + protected String gateway; + + protected String address; + + protected Integer mask; + + protected String primaryDNS; + + protected String secondaryDNS; + + protected String sufixDNS; + + protected Boolean defaultNetwork; + + public NetworkBuilder(final RestContext context) { + super(); + this.context = context; + } + + @SuppressWarnings("unchecked") + public T name(final String name) { + this.name = name; + return (T) this; + } + + @SuppressWarnings("unchecked") + public T tag(final Integer tag) { + this.tag = tag; + return (T) this; + } + + @SuppressWarnings("unchecked") + public T gateway(final String gateway) { + this.gateway = gateway; + return (T) this; + } + + @SuppressWarnings("unchecked") + public T address(final String address) { + this.address = address; + return (T) this; + } + + @SuppressWarnings("unchecked") + public T mask(final int mask) { + this.mask = mask; + return (T) this; + } + + @SuppressWarnings("unchecked") + public T primaryDNS(final String primaryDNS) { + this.primaryDNS = primaryDNS; + return (T) this; + } + + @SuppressWarnings("unchecked") + public T secondaryDNS(final String secondaryDNS) { + this.secondaryDNS = secondaryDNS; + return (T) this; + } + + @SuppressWarnings("unchecked") + public T sufixDNS(final String sufixDNS) { + this.sufixDNS = sufixDNS; + return (T) this; + } + + @SuppressWarnings("unchecked") + public T defaultNetwork(final Boolean defaultNetwork) { + this.defaultNetwork = defaultNetwork; + return (T) this; + } + } + + public PrivateNetwork toPrivateNetwork() { + checkArgument(target.getType().equals(NetworkType.INTERNAL), + ValidationErrors.INVALID_NETWORK_TYPE + target.getType()); + + return wrap(context, PrivateNetwork.class, target); + + } + + public ExternalNetwork toExternalNetwork() { + checkArgument(target.getType().equals(NetworkType.EXTERNAL), + ValidationErrors.INVALID_NETWORK_TYPE + target.getType()); + + return wrap(context, ExternalNetwork.class, target); + + } + + public PublicNetwork toPublicNetwork() { + checkArgument(target.getType().equals(NetworkType.PUBLIC), + ValidationErrors.INVALID_NETWORK_TYPE + target.getType()); + + return wrap(context, PublicNetwork.class, target); + + } + + public UnmanagedNetwork toUnmanagedNetwork() { + checkArgument(target.getType().equals(NetworkType.UNMANAGED), + ValidationErrors.INVALID_NETWORK_TYPE + target.getType()); + + return wrap(context, UnmanagedNetwork.class, target); + + } + + // Delegate methods + + public String getAddress() { + return target.getAddress(); + } + + public Boolean getDefaultNetwork() { + return target.getDefaultNetwork(); + } + + public String getGateway() { + return target.getGateway(); + } + + public Integer getId() { + return target.getId(); + } + + public Integer getMask() { + return target.getMask(); + } + + public String getName() { + return target.getName(); + } + + public String getPrimaryDNS() { + return target.getPrimaryDNS(); + } + + public String getSecondaryDNS() { + return target.getSecondaryDNS(); + } + + public String getSufixDNS() { + return target.getSufixDNS(); + } + + public Integer getTag() { + return target.getTag(); + } + + public NetworkType getType() { + return target.getType(); + } + + public void setAddress(final String address) { + target.setAddress(address); + } + + public void setDefaultNetwork(final Boolean defaultNetwork) { + target.setDefaultNetwork(defaultNetwork); + } + + public void setGateway(final String gateway) { + target.setGateway(gateway); + } + + public void setMask(final Integer mask) { + target.setMask(mask); + } + + public void setName(final String name) { + target.setName(name); + } + + public void setPrimaryDNS(final String primaryDNS) { + target.setPrimaryDNS(primaryDNS); + } + + public void setSecondaryDNS(final String secondaryDNS) { + target.setSecondaryDNS(secondaryDNS); + } + + public void setSufixDNS(final String sufixDNS) { + target.setSufixDNS(sufixDNS); + } + + public void setTag(final Integer tag) { + target.setTag(tag); + } + + @Override + public String toString() { + return "Network [id=" + getId() + ", address=" + getAddress() + ", defaultNetwork=" + getDefaultNetwork() + + ", gateway=" + getGateway() + ", mask=" + getMask() + ", name=" + getName() + ", primaryDNS=" + + getPrimaryDNS() + ", secondaryDNS=" + getSecondaryDNS() + ", suffixDNS=" + getSufixDNS() + ", tag=" + + getTag() + ", type=" + getType() + "]"; + } + + public static Network wrapNetwork(final RestContext context, final VLANNetworkDto dto) { + if (dto == null) { + return null; + } + + Network network = null; + + switch (dto.getType()) { + case EXTERNAL: + network = wrap(context, ExternalNetwork.class, dto); + break; + case EXTERNAL_UNMANAGED: + // TODO: How do we manage External && unmanaged networks ? + throw new UnsupportedOperationException("EXTERNAL_UNMANAGED networks not supported yet"); + case INTERNAL: + network = wrap(context, PrivateNetwork.class, dto); + break; + case PUBLIC: + network = wrap(context, PublicNetwork.class, dto); + break; + case UNMANAGED: + network = wrap(context, UnmanagedNetwork.class, dto); + break; + } + + return network; + } + + public static List> wrapNetworks(final RestContext context, + final List dtos) { + List> networks = Lists.newLinkedList(); + for (VLANNetworkDto dto : dtos) { + networks.add(wrapNetwork(context, dto)); + } + return networks; + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/network/Nic.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/network/Nic.java new file mode 100644 index 0000000000..91bfba17da --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/network/Nic.java @@ -0,0 +1,62 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.network; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.domain.DomainWrapper; +import org.jclouds.rest.RestContext; + +import com.abiquo.server.core.infrastructure.network.NicDto; + +/** + * Adds high level functionality to {@link NicDto}. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + * @see API: http://community.abiquo.com/display/ABI20/ + * VirtualMachineNetworkConfiguration + */ +public class Nic extends DomainWrapper { + /** + * Constructor to be used only by the builder (if any). + */ + protected Nic(final RestContext context, final NicDto target) { + super(context, target); + } + + // Parent access + + // Delegate methods + + public Integer getId() { + return target.getId(); + } + + public String getIp() { + return target.getIp(); + } + + public String getMac() { + return target.getMac(); + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/network/PrivateIp.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/network/PrivateIp.java new file mode 100644 index 0000000000..afbd320f32 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/network/PrivateIp.java @@ -0,0 +1,80 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.network; + +import static com.google.common.base.Preconditions.checkNotNull; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.reference.ValidationErrors; +import org.jclouds.abiquo.reference.rest.ParentLinkName; +import org.jclouds.abiquo.rest.internal.ExtendedUtils; +import org.jclouds.http.HttpResponse; +import org.jclouds.http.functions.ParseXMLWithJAXB; +import org.jclouds.rest.RestContext; + +import com.abiquo.model.enumerator.NetworkType; +import com.abiquo.model.rest.RESTLink; +import com.abiquo.server.core.infrastructure.network.PrivateIpDto; +import com.abiquo.server.core.infrastructure.network.VLANNetworkDto; +import com.google.inject.TypeLiteral; + +/** + * Adds generic high level functionality to {@link PrivateIpDto}. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +public class PrivateIp extends Ip { + /** + * Constructor to be used only by the builder. + */ + protected PrivateIp(final RestContext context, final PrivateIpDto target) { + super(context, target); + } + + // Domain operations + + @Override + public PrivateNetwork getNetwork() { + RESTLink link = checkNotNull(target.searchLink(ParentLinkName.PRIVATE_NETWORK), + ValidationErrors.MISSING_REQUIRED_LINK + " " + ParentLinkName.PRIVATE_NETWORK); + + ExtendedUtils utils = (ExtendedUtils) context.getUtils(); + HttpResponse response = utils.getAbiquoHttpClient().get(link); + + ParseXMLWithJAXB parser = new ParseXMLWithJAXB(utils.getXml(), + TypeLiteral.get(VLANNetworkDto.class)); + + return wrap(context, PrivateNetwork.class, parser.apply(response)); + } + + @Override + public NetworkType getNetworkType() { + return NetworkType.INTERNAL; + } + + @Override + public String toString() { + return "PrivateIp [networkType=" + getNetworkType() + ", id=" + getId() + ", ip=" + getIp() + ", mac=" + getMac() + + ", name=" + getName() + ", networkName=" + getNetworkName() + "]"; + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/network/PrivateNetwork.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/network/PrivateNetwork.java new file mode 100644 index 0000000000..55d900b93f --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/network/PrivateNetwork.java @@ -0,0 +1,169 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.network; + +import java.util.List; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.domain.cloud.VirtualDatacenter; +import org.jclouds.abiquo.domain.network.options.IpOptions; +import org.jclouds.rest.RestContext; + +import com.abiquo.model.enumerator.NetworkType; +import com.abiquo.server.core.infrastructure.network.PrivateIpDto; +import com.abiquo.server.core.infrastructure.network.PrivateIpsDto; +import com.abiquo.server.core.infrastructure.network.VLANNetworkDto; + +/** + * Adds high level functionality to private {@link VLANNetworkDto}. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + * @see API: http://community.abiquo.com/display/ABI20/Private+Network+Resource + */ +public class PrivateNetwork extends Network { + /** The virtual datacenter where the network belongs. */ + private VirtualDatacenter virtualDatacenter; + + /** + * Constructor to be used only by the builder. + */ + protected PrivateNetwork(final RestContext context, final VLANNetworkDto target) { + super(context, target); + } + + // Domain operations + + /** + * @see API: http://community.abiquo.com/display/ABI20/Private+Network+Resource# + * PrivateNetworkResource -DeleteaPrivateNetwork + */ + @Override + public void delete() { + context.getApi().getCloudApi().deletePrivateNetwork(target); + target = null; + } + + /** + * @see API: http://community.abiquo.com/display/ABI20/Private+Network+Resource# + * PrivateNetworkResource -CreateaPrivateNetwork + */ + @Override + public void save() { + target = context.getApi().getCloudApi().createPrivateNetwork(virtualDatacenter.unwrap(), target); + } + + /** + * @see API: http://community.abiquo.com/display/ABI20/Private+Network+Resource# + * PrivateNetworkResource -UpdateaPrivateNetwork + */ + @Override + public void update() { + target = context.getApi().getCloudApi().updatePrivateNetwork(target); + } + + /** + * @see API: http://community.abiquo.com/display/ABI20/Private+Network+Resource# + * PrivateNetworkResource -RetrievethelistofIPSofthePrivateNetwork + */ + @Override + public List listIps(final IpOptions options) { + PrivateIpsDto ips = context.getApi().getCloudApi().listPrivateNetworkIps(target, options); + return wrap(context, PrivateIp.class, ips.getCollection()); + } + + // Override to apply the filter in the server side + @Override + public List listUnusedIps() { + IpOptions options = IpOptions.builder().disablePagination().free(true).build(); + PrivateIpsDto ips = context.getApi().getCloudApi().listPrivateNetworkIps(target, options); + return wrap(context, PrivateIp.class, ips.getCollection()); + } + + @Override + public PrivateIp getIp(final Integer id) { + PrivateIpDto ip = context.getApi().getCloudApi().getPrivateNetworkIp(target, id); + return wrap(context, PrivateIp.class, ip); + } + + // Builder + + public static Builder builder(final RestContext context) { + return new Builder(context); + } + + public static class Builder extends NetworkBuilder { + private VirtualDatacenter virtualDatacenter; + + public Builder(final RestContext context) { + super(context); + this.context = context; + } + + public Builder virtualDatacenter(final VirtualDatacenter virtualDatacenter) { + this.virtualDatacenter = virtualDatacenter; + return this; + } + + public PrivateNetwork build() { + VLANNetworkDto dto = new VLANNetworkDto(); + dto.setName(name); + dto.setTag(tag); + dto.setGateway(gateway); + dto.setAddress(address); + dto.setMask(mask); + dto.setPrimaryDNS(primaryDNS); + dto.setSecondaryDNS(secondaryDNS); + dto.setSufixDNS(sufixDNS); + dto.setDefaultNetwork(defaultNetwork); + dto.setUnmanaged(false); + dto.setType(NetworkType.INTERNAL); + + PrivateNetwork network = new PrivateNetwork(context, dto); + network.virtualDatacenter = virtualDatacenter; + + return network; + } + + public static Builder fromPrivateNetwork(final PrivateNetwork in) { + return PrivateNetwork.builder(in.context).name(in.getName()).tag(in.getTag()).gateway(in.getGateway()) + .address(in.getAddress()).mask(in.getMask()).primaryDNS(in.getPrimaryDNS()) + .secondaryDNS(in.getSecondaryDNS()).sufixDNS(in.getSufixDNS()).defaultNetwork(in.getDefaultNetwork()) + .virtualDatacenter(in.virtualDatacenter); + } + } + + @Override + public String toString() { + return "Private " + super.toString(); + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/network/PublicIp.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/network/PublicIp.java new file mode 100644 index 0000000000..c02418624d --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/network/PublicIp.java @@ -0,0 +1,79 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.network; + +import static com.google.common.base.Preconditions.checkNotNull; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.reference.ValidationErrors; +import org.jclouds.abiquo.reference.rest.ParentLinkName; +import org.jclouds.abiquo.rest.internal.ExtendedUtils; +import org.jclouds.http.HttpResponse; +import org.jclouds.http.functions.ParseXMLWithJAXB; +import org.jclouds.rest.RestContext; + +import com.abiquo.model.enumerator.NetworkType; +import com.abiquo.model.rest.RESTLink; +import com.abiquo.server.core.infrastructure.network.PublicIpDto; +import com.abiquo.server.core.infrastructure.network.VLANNetworkDto; +import com.google.inject.TypeLiteral; + +/** + * Adds generic high level functionality to {@link PublicIpDto}. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +public class PublicIp extends AbstractPublicIp { + /** + * Constructor to be used only by the builder. + */ + protected PublicIp(final RestContext context, final PublicIpDto target) { + super(context, target); + } + + @Override + public PublicNetwork getNetwork() { + RESTLink link = checkNotNull(target.searchLink(ParentLinkName.PUBLIC_NETWORK), + ValidationErrors.MISSING_REQUIRED_LINK + ParentLinkName.PUBLIC_NETWORK); + + ExtendedUtils utils = (ExtendedUtils) context.getUtils(); + HttpResponse response = utils.getAbiquoHttpClient().get(link); + + ParseXMLWithJAXB parser = new ParseXMLWithJAXB(utils.getXml(), + TypeLiteral.get(VLANNetworkDto.class)); + + return wrap(context, PublicNetwork.class, parser.apply(response)); + } + + @Override + public NetworkType getNetworkType() { + return NetworkType.PUBLIC; + } + + @Override + public String toString() { + return "PublicIp [networkType=" + getNetworkType() + ", available=" + isAvailable() + ", quarantine=" + + isQuarantine() + ", id=" + getId() + ", ip=" + getIp() + ", mac=" + getMac() + ", name=" + getName() + + ", networkName=" + getNetworkName() + "]"; + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/network/PublicNetwork.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/network/PublicNetwork.java new file mode 100644 index 0000000000..15a9d48d6d --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/network/PublicNetwork.java @@ -0,0 +1,189 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.network; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.List; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.domain.enterprise.Enterprise; +import org.jclouds.abiquo.domain.infrastructure.Datacenter; +import org.jclouds.abiquo.domain.network.options.IpOptions; +import org.jclouds.abiquo.reference.ValidationErrors; +import org.jclouds.abiquo.reference.annotations.EnterpriseEdition; +import org.jclouds.abiquo.reference.rest.ParentLinkName; +import org.jclouds.abiquo.rest.internal.ExtendedUtils; +import org.jclouds.http.HttpResponse; +import org.jclouds.http.functions.ParseXMLWithJAXB; +import org.jclouds.rest.RestContext; + +import com.abiquo.model.enumerator.NetworkType; +import com.abiquo.model.rest.RESTLink; +import com.abiquo.server.core.infrastructure.DatacenterDto; +import com.abiquo.server.core.infrastructure.network.PublicIpDto; +import com.abiquo.server.core.infrastructure.network.PublicIpsDto; +import com.abiquo.server.core.infrastructure.network.VLANNetworkDto; +import com.google.inject.TypeLiteral; + +/** + * Adds high level functionality to public {@link VLANNetworkDto}. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + * @see API: http://community.abiquo.com/display/ABI20/Public+Network+Resource + */ +@EnterpriseEdition +public class PublicNetwork extends Network { + /** The datacenter where the network belongs. */ + private Datacenter datacenter; + + /** + * Constructor to be used only by the builder. + */ + protected PublicNetwork(final RestContext context, final VLANNetworkDto target) { + super(context, target); + } + + /** + * @see API: http://community.abiquo.com/display/ABI20/Public+Network+Resource# + * PublicNetworkResource -DeleteaPublicNetwork + */ + @Override + public void delete() { + context.getApi().getInfrastructureApi().deleteNetwork(target); + target = null; + } + + /** + * @see API: http://community.abiquo.com/display/ABI20/Public+Network+Resource# + * PublicNetworkResource -CreateanewPublicNetwork + */ + @Override + public void save() { + target = context.getApi().getInfrastructureApi().createNetwork(datacenter.unwrap(), target); + } + + /** + * @see API: http://community.abiquo.com/display/ABI20/Public+Network+Resource# + * PublicNetworkResource -UpdateaPublicNetwork + */ + @Override + public void update() { + target = context.getApi().getInfrastructureApi().updateNetwork(target); + } + + /** + * @see API: http://community.abiquo.com/display/ABI20/Public+IPs+Resource# + * PublicIPsResource- ReturnthelistofIPsforaPublicNetwork + */ + @Override + public List listIps(final IpOptions options) { + PublicIpsDto ips = context.getApi().getInfrastructureApi().listPublicIps(target, options); + return wrap(context, PublicIp.class, ips.getCollection()); + } + + @Override + public PublicIp getIp(final Integer id) { + PublicIpDto ip = context.getApi().getInfrastructureApi().getPublicIp(target, id); + return wrap(context, PublicIp.class, ip); + } + + // Parent access + + public Datacenter getDatacenter() { + RESTLink link = checkNotNull(target.searchLink(ParentLinkName.DATACENTER), ValidationErrors.MISSING_REQUIRED_LINK + + " " + ParentLinkName.DATACENTER); + + ExtendedUtils utils = (ExtendedUtils) context.getUtils(); + HttpResponse response = utils.getAbiquoHttpClient().get(link); + + ParseXMLWithJAXB parser = new ParseXMLWithJAXB(utils.getXml(), + TypeLiteral.get(DatacenterDto.class)); + + datacenter = wrap(context, Datacenter.class, parser.apply(response)); + return datacenter; + } + + // Builder + + public static Builder builder(final RestContext context, final Datacenter datacenter) { + return new Builder(context, datacenter); + } + + public static class Builder extends NetworkBuilder { + private Datacenter datacenter; + + public Builder(final RestContext context, final Datacenter datacenter) { + super(context); + checkNotNull(datacenter, ValidationErrors.NULL_RESOURCE + Datacenter.class); + checkNotNull(datacenter, ValidationErrors.NULL_RESOURCE + Enterprise.class); + this.datacenter = datacenter; + this.context = context; + } + + public Builder datacenter(final Datacenter datacenter) { + this.datacenter = datacenter; + return this; + } + + public PublicNetwork build() { + VLANNetworkDto dto = new VLANNetworkDto(); + dto.setName(name); + dto.setTag(tag); + dto.setGateway(gateway); + dto.setAddress(address); + dto.setMask(mask); + dto.setPrimaryDNS(primaryDNS); + dto.setSecondaryDNS(secondaryDNS); + dto.setSufixDNS(sufixDNS); + dto.setDefaultNetwork(defaultNetwork); + dto.setUnmanaged(false); + dto.setType(NetworkType.PUBLIC); + + PublicNetwork network = new PublicNetwork(context, dto); + network.datacenter = datacenter; + + return network; + } + + public static Builder fromPublicNetwork(final PublicNetwork in) { + return PublicNetwork.builder(in.context, in.datacenter).name(in.getName()).tag(in.getTag()) + .gateway(in.getGateway()).address(in.getAddress()).mask(in.getMask()).primaryDNS(in.getPrimaryDNS()) + .secondaryDNS(in.getSecondaryDNS()).sufixDNS(in.getSufixDNS()).defaultNetwork(in.getDefaultNetwork()); + } + } + + @Override + public String toString() { + return "Public " + super.toString(); + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/network/UnmanagedIp.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/network/UnmanagedIp.java new file mode 100644 index 0000000000..9c4d0c66ad --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/network/UnmanagedIp.java @@ -0,0 +1,81 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.network; + +import static com.google.common.base.Preconditions.checkNotNull; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.reference.ValidationErrors; +import org.jclouds.abiquo.reference.rest.ParentLinkName; +import org.jclouds.abiquo.rest.internal.ExtendedUtils; +import org.jclouds.http.HttpResponse; +import org.jclouds.http.functions.ParseXMLWithJAXB; +import org.jclouds.rest.RestContext; + +import com.abiquo.model.enumerator.NetworkType; +import com.abiquo.model.rest.RESTLink; +import com.abiquo.server.core.infrastructure.network.UnmanagedIpDto; +import com.abiquo.server.core.infrastructure.network.VLANNetworkDto; +import com.google.inject.TypeLiteral; + +/** + * Adds generic high level functionality to {@link UnmanagedIpDto}. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +public class UnmanagedIp extends AbstractPublicIp { + /** + * Constructor to be used only by the builder. + */ + protected UnmanagedIp(final RestContext context, final UnmanagedIpDto target) { + super(context, target); + } + + // Domain operations + + @Override + public UnmanagedNetwork getNetwork() { + RESTLink link = checkNotNull(target.searchLink(ParentLinkName.UNMANAGED_NETWORK), + ValidationErrors.MISSING_REQUIRED_LINK + " " + ParentLinkName.UNMANAGED_NETWORK); + + ExtendedUtils utils = (ExtendedUtils) context.getUtils(); + HttpResponse response = utils.getAbiquoHttpClient().get(link); + + ParseXMLWithJAXB parser = new ParseXMLWithJAXB(utils.getXml(), + TypeLiteral.get(VLANNetworkDto.class)); + + return wrap(context, UnmanagedNetwork.class, parser.apply(response)); + } + + @Override + public NetworkType getNetworkType() { + return NetworkType.UNMANAGED; + } + + @Override + public String toString() { + return "UnmanagedIp [networkType=" + getNetworkType() + ", available=" + isAvailable() + ", quarantine=" + + isQuarantine() + ", id=" + getId() + ", ip=" + getIp() + ", mac=" + getMac() + ", name=" + getName() + + ", networkName=" + getNetworkName() + "]"; + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/network/UnmanagedNetwork.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/network/UnmanagedNetwork.java new file mode 100644 index 0000000000..9b8e73ecbf --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/network/UnmanagedNetwork.java @@ -0,0 +1,230 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.network; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.List; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.domain.enterprise.Enterprise; +import org.jclouds.abiquo.domain.infrastructure.Datacenter; +import org.jclouds.abiquo.domain.network.options.IpOptions; +import org.jclouds.abiquo.reference.ValidationErrors; +import org.jclouds.abiquo.reference.annotations.EnterpriseEdition; +import org.jclouds.abiquo.reference.rest.ParentLinkName; +import org.jclouds.abiquo.rest.internal.ExtendedUtils; +import org.jclouds.http.HttpResponse; +import org.jclouds.http.functions.ParseXMLWithJAXB; +import org.jclouds.rest.RestContext; + +import com.abiquo.model.enumerator.NetworkType; +import com.abiquo.model.rest.RESTLink; +import com.abiquo.server.core.enterprise.EnterpriseDto; +import com.abiquo.server.core.infrastructure.DatacenterDto; +import com.abiquo.server.core.infrastructure.network.UnmanagedIpDto; +import com.abiquo.server.core.infrastructure.network.UnmanagedIpsDto; +import com.abiquo.server.core.infrastructure.network.VLANNetworkDto; +import com.google.inject.TypeLiteral; + +/** + * Adds high level functionality to external {@link VLANNetworkDto}. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + * @see API: http://community.abiquo.com/display/ABI20/Public+Network+Resource + */ +@EnterpriseEdition +public class UnmanagedNetwork extends Network { + /** The datacenter where the network belongs. */ + private Datacenter datacenter; + + /** The enterprise where the network belongs. */ + private Enterprise enterprise; + + /** + * Constructor to be used only by the builder. + */ + protected UnmanagedNetwork(final RestContext context, final VLANNetworkDto target) { + super(context, target); + } + + /** + * @see API: http://community.abiquo.com/display/ABI20/Public+Network+Resource# + * PublicNetworkResource -DeleteanUnmanagedNetwork + */ + @Override + public void delete() { + context.getApi().getInfrastructureApi().deleteNetwork(target); + target = null; + } + + /** + * @see API: http://community.abiquo.com/display/ABI20/Public+Network+Resource# + * PublicNetworkResource -CreateanewUnmanagedNetwork + */ + @Override + public void save() { + this.addEnterpriseLink(); + target = context.getApi().getInfrastructureApi().createNetwork(datacenter.unwrap(), target); + } + + /** + * @see API: http://community.abiquo.com/display/ABI20/Public+Network+Resource# + * PublicNetworkResource -UpdateanUnmanagedNetwork + */ + @Override + public void update() { + target = context.getApi().getInfrastructureApi().updateNetwork(target); + } + + /** + * @see API: http://community.abiquo.com/display/ABI20/Public+IPs+Resource# + * PublicIPsResource- ReturnthelistofIPsforaPublicNetwork + */ + @Override + public List listIps(final IpOptions options) { + UnmanagedIpsDto ips = context.getApi().getInfrastructureApi().listUnmanagedIps(target, options); + return wrap(context, UnmanagedIp.class, ips.getCollection()); + } + + @Override + public UnmanagedIp getIp(final Integer id) { + UnmanagedIpDto ip = context.getApi().getInfrastructureApi().getUnmanagedIp(target, id); + return wrap(context, UnmanagedIp.class, ip); + } + + // Parent access + + public Enterprise getEnterprise() { + RESTLink link = checkNotNull(target.searchLink(ParentLinkName.ENTERPRISE), ValidationErrors.MISSING_REQUIRED_LINK + + " " + ParentLinkName.ENTERPRISE); + + ExtendedUtils utils = (ExtendedUtils) context.getUtils(); + HttpResponse response = utils.getAbiquoHttpClient().get(link); + + ParseXMLWithJAXB parser = new ParseXMLWithJAXB(utils.getXml(), + TypeLiteral.get(EnterpriseDto.class)); + + enterprise = wrap(context, Enterprise.class, parser.apply(response)); + return enterprise; + } + + public Datacenter getDatacenter() { + RESTLink link = checkNotNull(target.searchLink(ParentLinkName.DATACENTER), ValidationErrors.MISSING_REQUIRED_LINK + + " " + ParentLinkName.DATACENTER); + + ExtendedUtils utils = (ExtendedUtils) context.getUtils(); + HttpResponse response = utils.getAbiquoHttpClient().get(link); + + ParseXMLWithJAXB parser = new ParseXMLWithJAXB(utils.getXml(), + TypeLiteral.get(DatacenterDto.class)); + + datacenter = wrap(context, Datacenter.class, parser.apply(response)); + return datacenter; + } + + private void addEnterpriseLink() { + checkNotNull(enterprise, ValidationErrors.NULL_RESOURCE + Enterprise.class); + checkNotNull(enterprise.getId(), ValidationErrors.MISSING_REQUIRED_FIELD + " id in " + Enterprise.class); + + RESTLink link = enterprise.unwrap().searchLink("edit"); + + checkNotNull(link, ValidationErrors.MISSING_REQUIRED_LINK); + + target.addLink(new RESTLink("enterprise", link.getHref())); + } + + // Builder + + public static Builder builder(final RestContext context, final Datacenter datacenter, + final Enterprise enterprise) { + return new Builder(context, datacenter, enterprise); + } + + public static class Builder extends NetworkBuilder { + private Datacenter datacenter; + + private Enterprise enterprise; + + public Builder(final RestContext context, final Datacenter datacenter, + final Enterprise enterprise) { + super(context); + checkNotNull(datacenter, ValidationErrors.NULL_RESOURCE + Datacenter.class); + checkNotNull(datacenter, ValidationErrors.NULL_RESOURCE + Enterprise.class); + this.datacenter = datacenter; + this.enterprise = enterprise; + this.context = context; + } + + public Builder datacenter(final Datacenter datacenter) { + this.datacenter = datacenter; + return this; + } + + public Builder enterprise(final Enterprise enterprise) { + this.enterprise = enterprise; + return this; + } + + public UnmanagedNetwork build() { + VLANNetworkDto dto = new VLANNetworkDto(); + dto.setName(name); + dto.setTag(tag); + dto.setGateway(gateway); + dto.setAddress(address); + dto.setMask(mask); + dto.setPrimaryDNS(primaryDNS); + dto.setSecondaryDNS(secondaryDNS); + dto.setSufixDNS(sufixDNS); + dto.setDefaultNetwork(defaultNetwork); + dto.setUnmanaged(true); + dto.setType(NetworkType.UNMANAGED); + + UnmanagedNetwork network = new UnmanagedNetwork(context, dto); + network.datacenter = datacenter; + network.enterprise = enterprise; + + return network; + } + + public static Builder fromUnmanagedNetwork(final UnmanagedNetwork in) { + return UnmanagedNetwork.builder(in.context, in.datacenter, in.enterprise).name(in.getName()).tag(in.getTag()) + .gateway(in.getGateway()).address(in.getAddress()).mask(in.getMask()).primaryDNS(in.getPrimaryDNS()) + .secondaryDNS(in.getSecondaryDNS()).sufixDNS(in.getSufixDNS()).defaultNetwork(in.getDefaultNetwork()); + } + } + + @Override + public String toString() { + return "Unmanaged " + super.toString(); + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/network/options/IpOptions.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/network/options/IpOptions.java new file mode 100644 index 0000000000..dfcbdc5bac --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/network/options/IpOptions.java @@ -0,0 +1,60 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.network.options; + +import org.jclouds.abiquo.domain.options.search.FilterOptions.BaseFilterOptionsBuilder; +import org.jclouds.http.options.BaseHttpRequestOptions; + +/** + * Available options to query ips. + * + * @author Francesc Montserrat + */ +public class IpOptions extends BaseHttpRequestOptions { + public static Builder builder() { + return new Builder(); + } + + @Override + protected Object clone() throws CloneNotSupportedException { + IpOptions options = new IpOptions(); + options.queryParameters.putAll(queryParameters); + return options; + } + + public static class Builder extends BaseFilterOptionsBuilder { + private Boolean free; + + public Builder free(final boolean free) { + this.free = free; + return this; + } + + public IpOptions build() { + IpOptions options = new IpOptions(); + + if (free != null) { + options.queryParameters.put("free", String.valueOf(free)); + } + + return addFilterOptions(options); + } + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/network/options/NetworkOptions.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/network/options/NetworkOptions.java new file mode 100644 index 0000000000..304d6b9356 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/network/options/NetworkOptions.java @@ -0,0 +1,72 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.network.options; + +import org.jclouds.http.options.BaseHttpRequestOptions; + +import com.abiquo.model.enumerator.NetworkType; + +/** + * Available options to query networks. + * + * @author Francesc Montserrat + */ +public class NetworkOptions extends BaseHttpRequestOptions { + public static Builder builder() { + return new Builder(); + } + + @Override + protected Object clone() throws CloneNotSupportedException { + NetworkOptions options = new NetworkOptions(); + options.queryParameters.putAll(queryParameters); + return options; + } + + public static class Builder { + private NetworkType type; + + private Boolean all; + + public Builder type(final NetworkType type) { + this.type = type; + return this; + } + + public Builder all(final boolean all) { + this.all = all; + return this; + } + + public NetworkOptions build() { + NetworkOptions options = new NetworkOptions(); + + if (type != null) { + options.queryParameters.put("type", String.valueOf(type)); + } + + if (all != null) { + options.queryParameters.put("all", String.valueOf(all)); + } + + return options; + } + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/options/search/FilterOptions.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/options/search/FilterOptions.java new file mode 100644 index 0000000000..8364f65885 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/options/search/FilterOptions.java @@ -0,0 +1,124 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.options.search; + +import org.jclouds.abiquo.domain.options.search.reference.OrderBy; +import org.jclouds.http.options.BaseHttpRequestOptions; + +import com.google.common.collect.Multimap; + +/** + * Available options to filter and pagination methods. + * + * @author Francesc Montserrat + */ +public class FilterOptions extends BaseHttpRequestOptions { + @Override + protected Object clone() throws CloneNotSupportedException { + FilterOptions options = new FilterOptions(); + options.queryParameters.putAll(queryParameters); + return options; + } + + public static FilterOptionsBuilder builder() { + return new FilterOptionsBuilder(); + } + + public static class FilterOptionsBuilder extends BaseFilterOptionsBuilder { + public FilterOptions build() { + FilterOptions options = new FilterOptions(); + return super.addFilterOptions(options); + } + } + + @SuppressWarnings("unchecked") + public static class BaseFilterOptionsBuilder> { + protected Integer startWith; + + protected Integer limit; + + protected OrderBy by; + + protected String has; + + protected Boolean asc; + + public T startWith(final int startWith) { + this.startWith = startWith; + return (T) this; + } + + public T has(final String has) { + this.has = has; + return (T) this; + } + + public T limit(final int limit) { + this.limit = limit; + return (T) this; + } + + public T orderBy(final OrderBy by) { + this.by = by; + return (T) this; + } + + public T ascendant(final boolean asc) { + this.asc = asc; + return (T) this; + } + + public T descendant(final boolean desc) { + this.asc = !desc; + return (T) this; + } + + public T disablePagination() { + this.limit = 0; + return (T) this; + } + + protected O addFilterOptions(final O options) { + Multimap queryParameters = options.buildQueryParameters(); + + if (startWith != null) { + queryParameters.put("startwith", startWith.toString()); + } + + if (limit != null) { + queryParameters.put("limit", limit.toString()); + } + + if (has != null) { + queryParameters.put("has", has); + } + + if (by != null) { + queryParameters.put("by", by.getValue()); + } + + if (asc != null) { + queryParameters.put("asc", asc.toString()); + } + + return options; + } + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/options/search/reference/OrderBy.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/options/search/reference/OrderBy.java new file mode 100644 index 0000000000..65db94df61 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/options/search/reference/OrderBy.java @@ -0,0 +1,41 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.options.search.reference; + +/** + * Available fields to order search results. + * + * @author Francesc Montserrat + * @author Ignasi Barrera + */ +public enum OrderBy { + NAME("name"), ID("id"), VIRTUALDATACENTER("virtualdatacenter"), VIRTUALMACHINE("virtualmachine"), VIRTUALAPPLIANCE( + "virtualappliance"), TIER("tier"), TOTALSIZE("totalsize"), STATE("state"); + + public String value; + + public String getValue() { + return value; + } + + private OrderBy(final String value) { + this.value = value; + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/task/AsyncJob.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/task/AsyncJob.java new file mode 100644 index 0000000000..f1283b801e --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/task/AsyncJob.java @@ -0,0 +1,76 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.task; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.domain.DomainWrapper; +import org.jclouds.rest.RestContext; + +import com.abiquo.server.core.task.Job.JobState; +import com.abiquo.server.core.task.Job.JobType; +import com.abiquo.server.core.task.JobDto; + +/** + * Adds generic high level functionality to {JobDto}. + * + * @author Francesc Montserrat + */ +public class AsyncJob extends DomainWrapper { + /** + * Constructor to be used only by the builder. + */ + protected AsyncJob(final RestContext context, final JobDto target) { + super(context, target); + } + + // Delegate methods + + public String getDescription() { + return target.getDescription(); + } + + public String getId() { + return target.getId(); + } + + public JobState getRollbackState() { + return target.getRollbackState(); + } + + public JobState getState() { + return target.getState(); + } + + public long getTimestamp() { + return target.getTimestamp(); + } + + public JobType getType() { + return target.getType(); + } + + @Override + public String toString() { + return "AsyncJob [id=" + getId() + ", description=" + getDescription() + ", rollbackState=" + getRollbackState() + + ", state=" + getState() + ", timestamp=" + getTimestamp() + ", type=" + getType() + "]"; + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/task/AsyncTask.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/task/AsyncTask.java new file mode 100644 index 0000000000..7cf5d999a1 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/task/AsyncTask.java @@ -0,0 +1,101 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.task; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.List; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.domain.DomainWrapper; +import org.jclouds.abiquo.reference.ValidationErrors; +import org.jclouds.rest.RestContext; + +import com.abiquo.model.rest.RESTLink; +import com.abiquo.server.core.task.TaskDto; +import com.abiquo.server.core.task.enums.TaskState; +import com.abiquo.server.core.task.enums.TaskType; + +/** + * Adds generic high level functionality to {TaskDto}. + * + * @author Francesc Montserrat + */ +public class AsyncTask extends DomainWrapper { + /** + * Constructor to be used only by the builder. + */ + protected AsyncTask(final RestContext context, final TaskDto target) { + super(context, target); + } + + // Domain operations + + /** + * Refresh the state of the task. + */ + public void refresh() { + RESTLink self = checkNotNull(target.searchLink("self"), ValidationErrors.MISSING_REQUIRED_LINK + "self"); + + target = context.getApi().getTaskApi().getTask(self); + } + + // Children access + + /** + * Get the individual jobs that compose the current task. + */ + public List getJobs() { + return wrap(context, AsyncJob.class, target.getJobs().getCollection()); + } + + // Delegate methods + + public String getOwnerId() { + return target.getOwnerId(); + } + + public TaskState getState() { + return target.getState(); + } + + public String getTaskId() { + return target.getTaskId(); + } + + public long getTimestamp() { + return target.getTimestamp(); + } + + public TaskType getType() { + return target.getType(); + } + + public String getUserId() { + return target.getUserId(); + } + + @Override + public String toString() { + return "AsyncTask [taskId=" + getTaskId() + ", ownerId=" + getOwnerId() + ", timestamp=" + getTimestamp() + + ", userId=" + getUserId() + ", state=" + getState() + ", type=" + getType() + "]"; + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/util/LinkUtils.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/util/LinkUtils.java new file mode 100644 index 0000000000..d8626de5c3 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/domain/util/LinkUtils.java @@ -0,0 +1,60 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.util; + +import static com.google.common.collect.Iterables.filter; + +import java.util.List; + +import org.jclouds.abiquo.predicates.LinkPredicates; + +import com.abiquo.model.rest.RESTLink; +import com.abiquo.model.transport.SingleResourceTransportDto; +import com.google.common.collect.Lists; + +/** + * Utility method to work with {@link RESTLink} objects. + * + * @author Ignasi Barrera + */ +public class LinkUtils { + /** + * Get the link that points to the current resource. + * + * @param dto + * The target dto. + * @return The link to the current resource. + */ + public static RESTLink getSelfLink(final SingleResourceTransportDto dto) { + RESTLink link = dto.searchLink("edit"); + return link == null ? dto.searchLink("self") : link; + } + + /** + * Filter the given link list and return only the links that point to a NIC. + * + * @param links + * The list with the links to filter. + * @return A lsit with all links taht point to a NIC. + */ + public static List filterNicLinks(final List links) { + return Lists.newLinkedList(filter(links, LinkPredicates.isNic())); + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/events/handlers/AbstractEventHandler.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/events/handlers/AbstractEventHandler.java new file mode 100644 index 0000000000..d5a022f6a7 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/events/handlers/AbstractEventHandler.java @@ -0,0 +1,57 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.events.handlers; + +import javax.annotation.Resource; + +import org.jclouds.abiquo.events.monitor.MonitorEvent; +import org.jclouds.logging.Logger; + +/** + * Base class for all {@link MonitorEvent} handlers. + * + * @author Ignasi Barrera + */ +public abstract class AbstractEventHandler { + @Resource + protected Logger logger = Logger.NULL; + + /** + * Checks if the current handler must handle the dispatched event. + * + * @param event + * The event being dispatched. + * @return Boolean indicating if the event must be handled by the current + * handler. + */ + protected abstract boolean handles(MonitorEvent event); + + // Public getters and setters to allow non-guice code to set the appropriate + // logger + + public Logger getLogger() { + return logger; + } + + public void setLogger(final Logger logger) { + this.logger = logger; + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/events/handlers/BlockingEventHandler.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/events/handlers/BlockingEventHandler.java new file mode 100644 index 0000000000..45c14994ea --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/events/handlers/BlockingEventHandler.java @@ -0,0 +1,149 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.events.handlers; + +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.List; +import java.util.concurrent.CountDownLatch; + +import org.jclouds.abiquo.events.monitor.MonitorEvent; +import org.jclouds.logging.Logger; + +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Throwables; +import com.google.common.collect.Lists; +import com.google.common.eventbus.Subscribe; + +/** + * An event handler that blocks the thread until all monitored objects have been + * finished being watched. + *

+ * Due to Guava + * Issue 786 {@link #handle(MonitorEvent)} is marked finalto + * avoid having duplicate events. + * + * @author Ignasi Barrera + * @param + * The monitored object. + */ +public class BlockingEventHandler extends AbstractEventHandler { + /** The signal used to lock the thread. */ + @VisibleForTesting + CountDownLatch completeSignal; + + /** + * The objects being locked. + *

+ * This class handles events in a thread safe way. Otherwise this collections + * should be synchronised. + */ + protected List lockedObjects; + + public BlockingEventHandler(final T... lockedObjects) { + this(Logger.NULL, lockedObjects); + } + + public BlockingEventHandler(final Logger logger, final T... lockedObjects) { + super(); + checkArgument(checkNotNull(lockedObjects, "lockedObjects").length > 0, "must provide at least one object"); + this.logger = checkNotNull(logger, "logger"); + this.lockedObjects = Lists.newArrayList(lockedObjects); + this.logger.debug("created BlockingEventHandler locking %s objects", lockedObjects.length); + } + + @Override + protected boolean handles(final MonitorEvent event) { + logger.debug("checking if %s event on %s must be handled by %s", event.getType(), event.getTarget(), this); + boolean handles = lockedObjects.contains(event.getTarget()); + logger.debug("%s event on %s must %sbe handled", event.getType(), event.getTarget(), handles ? "" : "not "); + return handles; + } + + /** + * Handles the dispatched event in a thread safe way. + *

+ * Due to Guava + * Issue 786 {@link #handle(MonitorEvent)} is marked finalto + * avoid having duplicate events. + * + * @see {@link #doBeforeRelease(MonitorEvent)} + */ + @Subscribe + public final void handle(final MonitorEvent event) { + if (handles(event)) { + logger.debug("handling %s", event); + + try { + doBeforeRelease(event); + } finally { + // Always release the lock, even if the handler code fails + release(event.getTarget()); + } + } + } + + /** + * Blocks the thread until all locked objects have been released. + */ + public void lock() { + // When invoking the lock, it is possible that all events have + // already been consumed. If there are no objects to monitor, + // just ignore the lock. + if (!lockedObjects.isEmpty()) { + try { + completeSignal = new CountDownLatch(lockedObjects.size()); + logger.debug("creating lock for %s object(s)", lockedObjects.size()); + completeSignal.await(); + } catch (InterruptedException ex) { + Throwables.propagate(ex); + } + } else { + logger.debug("there is nothing to watch. Ignoring lock."); + } + } + + /** + * Releases the lock on the given object. + */ + protected void release(final T target) { + logger.debug("releasing %s", target); + lockedObjects.remove(target); + + // The completeSignal might be null if the events have been consumed + // before acquiring the lock + if (completeSignal != null) { + completeSignal.countDown(); + logger.debug("releasing lock for %s. %s remaining objects", target, completeSignal.getCount()); + } + } + + /** + * Convenience method to bypass the Guava + * Issue 786 that forces the subscriber method to be final. + */ + protected void doBeforeRelease(final MonitorEvent event) { + // Let subclasses may override it to customize behavior + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/events/monitor/CompletedEvent.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/events/monitor/CompletedEvent.java new file mode 100644 index 0000000000..cac8e36d45 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/events/monitor/CompletedEvent.java @@ -0,0 +1,32 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.events.monitor; + +/** + * Event dispatched when a monitoring job completes without error. + * + * @author Ignasi Barrera + */ +public class CompletedEvent extends MonitorEvent { + public CompletedEvent(final T target) { + super(MonitorEvent.Type.COMPLETED, target); + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/events/monitor/FailedEvent.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/events/monitor/FailedEvent.java new file mode 100644 index 0000000000..7d185c2260 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/events/monitor/FailedEvent.java @@ -0,0 +1,32 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.events.monitor; + +/** + * Event dispatched when a monitoring job completes with errors. + * + * @author Ignasi Barrera + */ +public class FailedEvent extends MonitorEvent { + public FailedEvent(final T target) { + super(MonitorEvent.Type.FAILED, target); + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/events/monitor/MonitorEvent.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/events/monitor/MonitorEvent.java new file mode 100644 index 0000000000..7a263dd247 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/events/monitor/MonitorEvent.java @@ -0,0 +1,70 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.events.monitor; + +import static com.google.common.base.Preconditions.checkNotNull; + +/** + * base class for all monitor events. + * + * @author Ignasi Barrera + */ +public class MonitorEvent { + /** + * The type of the event. + */ + public static enum Type { + COMPLETED, FAILED, TIMEOUT; + } + + /** The type of the event. */ + private Type type; + + /** The target object being monitored. */ + private T target; + + public MonitorEvent(final Type type, final T target) { + super(); + this.type = checkNotNull(type, "type"); + this.target = checkNotNull(target, "target"); + } + + public Type getType() { + return type; + } + + public void setType(final Type type) { + this.type = type; + } + + public T getTarget() { + return target; + } + + public void setTarget(final T target) { + this.target = target; + } + + @Override + public String toString() { + return "MonitorEvent [type=" + type + ", target=" + target + "]"; + } + +} diff --git a/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/paas/reference/PaasConstants.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/events/monitor/TimeoutEvent.java similarity index 70% rename from demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/paas/reference/PaasConstants.java rename to labs/abiquo/src/main/java/org/jclouds/abiquo/events/monitor/TimeoutEvent.java index 8af7021bd2..b98c38f5cd 100644 --- a/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/paas/reference/PaasConstants.java +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/events/monitor/TimeoutEvent.java @@ -7,7 +7,7 @@ * "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 + * 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 @@ -16,13 +16,17 @@ * specific language governing permissions and limitations * under the License. */ -package org.jclouds.demo.paas.reference; + +package org.jclouds.abiquo.events.monitor; /** - * Configuration properties and constants used in PaaS applications. + * Event dispatched when a monitoring job times out. * - * @author Andrew Phillips + * @author Ignasi Barrera */ -public interface PaasConstants { - static final String PROPERTY_PLATFORM_BASE_URL = "jclouds.paas.baseurl"; +public class TimeoutEvent extends MonitorEvent { + public TimeoutEvent(final T target) { + super(MonitorEvent.Type.TIMEOUT, target); + } + } diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/features/AdminApi.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/features/AdminApi.java new file mode 100644 index 0000000000..228854225a --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/features/AdminApi.java @@ -0,0 +1,120 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.features; + +import java.util.concurrent.TimeUnit; + +import org.jclouds.concurrent.Timeout; + +import com.abiquo.server.core.enterprise.EnterpriseDto; +import com.abiquo.server.core.enterprise.PrivilegesDto; +import com.abiquo.server.core.enterprise.RoleDto; +import com.abiquo.server.core.enterprise.RolesDto; +import com.abiquo.server.core.enterprise.UserDto; + +/** + * Provides synchronous access to Abiquo Admin API. + * + * @see API: + * http://community.abiquo.com/display/ABI20/API+Reference + * @see AdminAsyncApi + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +@Timeout(duration = 30, timeUnit = TimeUnit.SECONDS) +public interface AdminApi { + /* ********************** User ********************** */ + + /** + * Get the information of the current user. + * + * @return The information of the current user. + */ + UserDto getCurrentUser(); + + /* ********************** Role ********************** */ + + /** + * List global roles. + * + * @return The list of global Roles. + */ + RolesDto listRoles(); + + /** + * List enterprise roles. + * + * @return The list of Roles for the given enterprise. + */ + RolesDto listRoles(EnterpriseDto enterprise); + + /** + * Retrieves the role of the given user. + * + * @param user + * The user. + * @return The role of the user. + */ + RoleDto getRole(UserDto user); + + /** + * Get the given role. + * + * @param roleId + * The id of the role. + * @return The role or null if it does not exist. + */ + RoleDto getRole(Integer roleId); + + /** + * Deletes an existing role. + * + * @param role + * The role to delete. + */ + void deleteRole(final RoleDto role); + + /** + * Updates an existing role. + * + * @param role + * The new attributes for the role. + * @return The updated role. + */ + RoleDto updateRole(RoleDto role); + + /** + * Create a new role. + * + * @param role + * The role to be created. + * @return The created role. + */ + RoleDto createRole(RoleDto role); + + /** + * Get privileges of the given role. + * + * @param role + * The role. + * @return The list of privileges. + */ + PrivilegesDto listPrivileges(RoleDto role); +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/features/AdminAsyncApi.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/features/AdminAsyncApi.java new file mode 100644 index 0000000000..d795614304 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/features/AdminAsyncApi.java @@ -0,0 +1,149 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.features; + +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 javax.ws.rs.QueryParam; + +import org.jclouds.abiquo.binders.BindToPath; +import org.jclouds.abiquo.binders.BindToXMLPayloadAndPath; +import org.jclouds.abiquo.domain.enterprise.Enterprise; +import org.jclouds.abiquo.functions.enterprise.ParseEnterpriseId; +import org.jclouds.abiquo.http.filters.AbiquoAuthentication; +import org.jclouds.abiquo.http.filters.AppendApiVersionToMediaType; +import org.jclouds.abiquo.rest.annotations.EndpointLink; +import org.jclouds.rest.annotations.BinderParam; +import org.jclouds.rest.annotations.ExceptionParser; +import org.jclouds.rest.annotations.JAXBResponseParser; +import org.jclouds.rest.annotations.ParamParser; +import org.jclouds.rest.annotations.RequestFilters; +import org.jclouds.rest.binders.BindToXMLPayload; +import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; + +import com.abiquo.server.core.enterprise.EnterpriseDto; +import com.abiquo.server.core.enterprise.PrivilegesDto; +import com.abiquo.server.core.enterprise.RoleDto; +import com.abiquo.server.core.enterprise.RolesDto; +import com.abiquo.server.core.enterprise.UserDto; +import com.google.common.util.concurrent.ListenableFuture; + +/** + * Provides asynchronous access to Abiquo Admin API. + * + * @see API: + * http://community.abiquo.com/display/ABI20/API+Reference + * @see AdminApi + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +@RequestFilters({ AbiquoAuthentication.class, AppendApiVersionToMediaType.class }) +public interface AdminAsyncApi { + /*********************** Login ***********************/ + + /** + * @see AdminApi#getCurrentUser() + */ + @GET + @Path("/login") + @Consumes(UserDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture getCurrentUser(); + + /*********************** Role ***********************/ + + /** + * @see AdminApi#listRoles() + */ + @GET + @Path("/admin/roles") + @Consumes(RolesDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listRoles(); + + /** + * @see AdminApi#listRoles(Enterprise enterprise) + */ + @GET + @Path("/admin/roles") + @Consumes(RolesDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listRoles( + @QueryParam("identerprise") @ParamParser(ParseEnterpriseId.class) final EnterpriseDto enterprise); + + /** + * @see AdminApi#getRole(UserDto) + */ + @GET + @Consumes(RoleDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + ListenableFuture getRole(@EndpointLink("role") @BinderParam(BindToPath.class) UserDto user); + + /** + * @see AdminApi#getRole(Integer) + */ + @GET + @Path("/admin/roles/{role}") + @Consumes(RoleDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + ListenableFuture getRole(@PathParam("role") Integer roleId); + + /** + * @see AdminApi#deleteRole(RoleDto) + */ + @DELETE + ListenableFuture deleteRole(@EndpointLink("edit") @BinderParam(BindToPath.class) RoleDto role); + + /** + * @see AdminApi#updateRole(RoleDto) + */ + @PUT + @Produces(RoleDto.BASE_MEDIA_TYPE) + @Consumes(RoleDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture updateRole(@EndpointLink("edit") @BinderParam(BindToXMLPayloadAndPath.class) RoleDto role); + + /** + * @see AdminApi#createRole(RoleDto) + */ + @POST + @Path("/admin/roles") + @Produces(RoleDto.BASE_MEDIA_TYPE) + @Consumes(RoleDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture createRole(@BinderParam(BindToXMLPayload.class) RoleDto role); + + /** + * @see AdminApi#listPrivileges(RoleDto) + */ + @GET + @Consumes(PrivilegesDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listPrivileges( + @EndpointLink("privileges") @BinderParam(BindToPath.class) RoleDto role); +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/features/CloudApi.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/features/CloudApi.java new file mode 100644 index 0000000000..2ddb1cd6a6 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/features/CloudApi.java @@ -0,0 +1,787 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.features; + +import java.util.concurrent.TimeUnit; + +import org.jclouds.abiquo.domain.cloud.options.VirtualApplianceOptions; +import org.jclouds.abiquo.domain.cloud.options.VirtualDatacenterOptions; +import org.jclouds.abiquo.domain.cloud.options.VirtualMachineOptions; +import org.jclouds.abiquo.domain.cloud.options.VirtualMachineTemplateOptions; +import org.jclouds.abiquo.domain.cloud.options.VolumeOptions; +import org.jclouds.abiquo.domain.network.options.IpOptions; +import org.jclouds.abiquo.reference.annotations.EnterpriseEdition; +import org.jclouds.concurrent.Timeout; + +import com.abiquo.model.transport.AcceptedRequestDto; +import com.abiquo.server.core.appslibrary.VirtualMachineTemplateDto; +import com.abiquo.server.core.appslibrary.VirtualMachineTemplatesDto; +import com.abiquo.server.core.cloud.VirtualApplianceDto; +import com.abiquo.server.core.cloud.VirtualApplianceStateDto; +import com.abiquo.server.core.cloud.VirtualAppliancesDto; +import com.abiquo.server.core.cloud.VirtualDatacenterDto; +import com.abiquo.server.core.cloud.VirtualDatacentersDto; +import com.abiquo.server.core.cloud.VirtualMachineDto; +import com.abiquo.server.core.cloud.VirtualMachineStateDto; +import com.abiquo.server.core.cloud.VirtualMachineTaskDto; +import com.abiquo.server.core.cloud.VirtualMachineWithNodeExtendedDto; +import com.abiquo.server.core.cloud.VirtualMachinesWithNodeExtendedDto; +import com.abiquo.server.core.enterprise.EnterpriseDto; +import com.abiquo.server.core.infrastructure.DatacenterDto; +import com.abiquo.server.core.infrastructure.network.PrivateIpDto; +import com.abiquo.server.core.infrastructure.network.PrivateIpsDto; +import com.abiquo.server.core.infrastructure.network.PublicIpDto; +import com.abiquo.server.core.infrastructure.network.PublicIpsDto; +import com.abiquo.server.core.infrastructure.network.VLANNetworkDto; +import com.abiquo.server.core.infrastructure.network.VLANNetworksDto; +import com.abiquo.server.core.infrastructure.network.VMNetworkConfigurationsDto; +import com.abiquo.server.core.infrastructure.storage.DiskManagementDto; +import com.abiquo.server.core.infrastructure.storage.DisksManagementDto; +import com.abiquo.server.core.infrastructure.storage.TierDto; +import com.abiquo.server.core.infrastructure.storage.TiersDto; +import com.abiquo.server.core.infrastructure.storage.VolumeManagementDto; +import com.abiquo.server.core.infrastructure.storage.VolumesManagementDto; + +/** + * Provides synchronous access to Abiquo Cloud API. + * + * @see API: + * http://community.abiquo.com/display/ABI20/API+Reference + * @see CloudAsyncApi + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +@Timeout(duration = 30, timeUnit = TimeUnit.SECONDS) +public interface CloudApi { + /*********************** Virtual Datacenter ***********************/ + + /** + * List all virtual datacenters. + * + * @param options + * Optional query params. + * @return The list of Datacenters. + */ + VirtualDatacentersDto listVirtualDatacenters(VirtualDatacenterOptions options); + + /** + * Get the given virtual datacenter. + * + * @param virtualDatacenterId + * The id of the virtual datacenter. + * @return The virtual datacenter or null if it does not exist. + */ + VirtualDatacenterDto getVirtualDatacenter(Integer virtualDatacenterId); + + /** + * Create a new virtual datacenter. + * + * @param virtualDatacenter + * The virtual datacenter to be created. + * @param datacenter + * Datacenter where the virtualdatacenter will be deployed. + * @param enterprise + * Enterprise of the virtual datacenter. + * @return The created virtual datacenter. + */ + VirtualDatacenterDto createVirtualDatacenter(VirtualDatacenterDto virtualDatacenter, DatacenterDto datacenter, + EnterpriseDto enterprise); + + /** + * Updates an existing virtual datacenter. + * + * @param virtualDatacenter + * The new attributes for the virtual datacenter. + * @return The updated virtual datacenter. + */ + VirtualDatacenterDto updateVirtualDatacenter(VirtualDatacenterDto virtualDatacenter); + + /** + * Deletes an existing virtual datacenter. + * + * @param virtualDatacenter + * The virtual datacenter to delete. + */ + void deleteVirtualDatacenter(VirtualDatacenterDto virtualDatacenter); + + /** + * List all available templates for the given virtual datacenter. + * + * @param virtualDatacenter + * The virtual datacenter. + * @return The list of available templates. + */ + VirtualMachineTemplatesDto listAvailableTemplates(VirtualDatacenterDto virtualDatacenter); + + /** + * List all available templates for the given virtual datacenter. + * + * @param virtualDatacenter + * The virtual datacenter. + * @param options + * Filtering options. + * @return The list of available templates. + */ + VirtualMachineTemplatesDto listAvailableTemplates(VirtualDatacenterDto virtualDatacenter, + VirtualMachineTemplateOptions options); + + /** + * List all available ips to purchase in the datacenter by the virtual + * datacenter. + * + * @param virtualDatacenter + * The virtual datacenter. + * @param options + * Filtering options. + * @return The list of available ips. + */ + PublicIpsDto listAvailablePublicIps(VirtualDatacenterDto virtualDatacenter, IpOptions options); + + /** + * List all purchased public ip addresses in the virtual datacenter. + * + * @param virtualDatacenter + * The virtual datacenter. + * @param options + * Filtering options. + * @return The list of purchased ips. + */ + PublicIpsDto listPurchasedPublicIps(VirtualDatacenterDto virtualDatacenter, IpOptions options); + + /** + * Purchase a public IP. + * + * @param ip + * The public ip address to purchase. + * @return The purchased public ip. + */ + PublicIpDto purchasePublicIp(PublicIpDto publicIp); + + /** + * Release a public IP. + * + * @param ip + * The public ip address to purchase. + * @return The release public ip. + */ + PublicIpDto releasePublicIp(PublicIpDto publicIp); + + /** + * List the storage tiers available for the given virtual datacenter. + * + * @param virtualDatacenter + * The virtual datacenter. + * @return The storage tiers available to the given virtual datacenter. + */ + @EnterpriseEdition + TiersDto listStorageTiers(VirtualDatacenterDto virtualDatacenter); + + /** + * Get the storage tier from the given virtual datacenter. + * + * @param virtualDatacenter + * The virtual datacenter. + * @param The + * id of the storage tier. + * @return The storage tiers available to the given virtual datacenter. + */ + @EnterpriseEdition + TierDto getStorageTier(VirtualDatacenterDto virtualDatacenter, Integer tierId); + + /*********************** Private Network ***********************/ + + /** + * Get the default network of the virtual datacenter. + * + * @param virtualDatacenter + * The virtual datacenter. + * @return The default network of the virtual datacenter. + */ + VLANNetworkDto getDefaultNetwork(VirtualDatacenterDto virtualDatacenter); + + /** + * Set the default network of the virtual datacenter. + * + * @param virtualDatacenter + * The virtual datacenter. + * @param network + * The default network. + */ + void setDefaultNetwork(VirtualDatacenterDto virtualDatacenter, VLANNetworkDto network); + + /** + * List all private networks for a virtual datacenter. + * + * @param virtualDatacenter + * The virtual datacenter. + * @return The list of private networks for the virtual datacenter. + */ + VLANNetworksDto listPrivateNetworks(VirtualDatacenterDto virtualDatacenter); + + /** + * Get the given private network from the given virtual datacenter. + * + * @param virtualDatacenter + * The virtual datacenter. + * @param virtualApplianceId + * The id of the private network. + * @return The private network or null if it does not exist. + */ + VLANNetworkDto getPrivateNetwork(VirtualDatacenterDto virtualDatacenter, Integer privateNetworkId); + + /** + * Create a new private network in a virtual datacenter. + * + * @param virtualDatacenter + * The virtual datacenter. + * @param privateNetwork + * The private network to be created. + * @return The created private network. + */ + VLANNetworkDto createPrivateNetwork(final VirtualDatacenterDto virtualDatacenter, final VLANNetworkDto privateNetwork); + + /** + * Updates an existing private network from the given virtual datacenter. + * + * @param privateNetwork + * The new attributes for the private network. + * @return The updated private network. + */ + VLANNetworkDto updatePrivateNetwork(VLANNetworkDto privateNetwork); + + /** + * Deletes an existing private network. + * + * @param privateNetwork + * The private network to delete. + */ + void deletePrivateNetwork(VLANNetworkDto privateNetwork); + + /*********************** Private Network IPs ***********************/ + + /** + * List all ips for a private network. + * + * @param network + * The private network. + * @return The list of ips for the private network. + */ + PrivateIpsDto listPrivateNetworkIps(VLANNetworkDto network); + + /** + * List all ips for a private network with options. + * + * @param network + * The private network. + * @param options + * Filtering options. + * @return The list of ips for the private network. + */ + PrivateIpsDto listPrivateNetworkIps(VLANNetworkDto network, IpOptions options); + + /** + * Get the requested ip from the given private network. + * + * @param network + * The private network. + * @param ipId + * The id of the ip to get. + * @return The requested ip. + */ + PrivateIpDto getPrivateNetworkIp(VLANNetworkDto network, Integer ipId); + + /*********************** Virtual Appliance ***********************/ + + /** + * List all virtual appliance for a virtual datacenter. + * + * @param virtualDatacenter + * The virtual datacenter. + * @return The list of virtual appliances for the virtual datacenter. + */ + VirtualAppliancesDto listVirtualAppliances(VirtualDatacenterDto virtualDatacenter); + + /** + * Get the given virtual appliance from the given virtual datacenter. + * + * @param virtualDatacenter + * The virtual datacenter. + * @param virtualApplianceId + * The id of the virtual appliance. + * @return The virtual appliance or null if it does not exist. + */ + VirtualApplianceDto getVirtualAppliance(VirtualDatacenterDto virtualDatacenter, Integer virtualApplianceId); + + /** + * Create a new virtual appliance in a virtual datacenter. + * + * @param virtualDatacenter + * The virtual datacenter. + * @param virtualAppliance + * The virtual appliance to be created. + * @return The created virtual appliance. + */ + VirtualApplianceDto createVirtualAppliance(VirtualDatacenterDto virtualDatacenter, + VirtualApplianceDto virtualAppliance); + + /** + * Updates an existing virtual appliance from the given virtual datacenter. + * + * @param virtualAppliance + * The new attributes for the virtual appliance. + * @return The updated virtual appliance. + */ + VirtualApplianceDto updateVirtualAppliance(VirtualApplianceDto virtualAppliance); + + /** + * Deletes an existing virtual appliance. + * + * @param virtualAppliance + * The virtual appliance to delete. + */ + void deleteVirtualAppliance(VirtualApplianceDto virtualAppliance); + + /** + * Deletes an existing virtual appliance. + * + * @param virtualAppliance + * The virtual appliance to delete. + * @param options + * The options to customize the delete operation (e.g. Force + * delete). + */ + void deleteVirtualAppliance(VirtualApplianceDto virtualAppliance, VirtualApplianceOptions options); + + /** + * Deploy a virtual appliance. + * + * @param virtualAppliance + * The virtual appliance to deploy + * @param options + * the extra options for the deploy process. + * @return Response message to the deploy request. + */ + @Timeout(duration = 90, timeUnit = TimeUnit.SECONDS) + AcceptedRequestDto deployVirtualAppliance(VirtualApplianceDto virtualAppliance, VirtualMachineTaskDto options); + + /** + * Undeploy a virtual appliance. + * + * @param virtualAppliance + * The virtual appliance to undeploy + * @param options + * the extra options for the undeploy process. + * @return Response message to the undeploy request. + */ + @Timeout(duration = 90, timeUnit = TimeUnit.SECONDS) + AcceptedRequestDto undeployVirtualAppliance(VirtualApplianceDto virtualAppliance, + VirtualMachineTaskDto options); + + /** + * Get the state of the given virtual appliance. + * + * @param virtualAppliance + * The given virtual appliance. + * @return The state of the given virtual appliance. + */ + VirtualApplianceStateDto getVirtualApplianceState(VirtualApplianceDto virtualAppliance); + + /** + * Gets the price of the given virtual appliance. + * + * @param virtualAppliance + * The virtual appliance to get the price of. + * @return A String representation of the price of the virtual + * appliance. + */ + String getVirtualAppliancePrice(VirtualApplianceDto virtualAppliance); + + /*********************** Virtual Machine ***********************/ + + /** + * List all virtual machines for a virtual appliance. + * + * @param virtualAppliance + * The virtual appliance. + * @return The list of virtual machines for the virtual appliance. + */ + VirtualMachinesWithNodeExtendedDto listVirtualMachines(VirtualApplianceDto virtualAppliance); + + /** + * List all virtual machines for a virtual appliance. + * + * @param virtualAppliance + * The virtual appliance. + * @param options + * The options to filter the list of virtual machines. + * @return The list of virtual machines for the virtual appliance. + */ + VirtualMachinesWithNodeExtendedDto listVirtualMachines(VirtualApplianceDto virtualAppliance, + VirtualMachineOptions options); + + /** + * Get the given virtual machine from the given virtual machine. + * + * @param virtualAppliance + * The virtual appliance. + * @param virtualMachineId + * The id of the virtual machine. + * @return The virtual machine or null if it does not exist. + */ + VirtualMachineWithNodeExtendedDto getVirtualMachine(VirtualApplianceDto virtualAppliance, Integer virtualMachineId); + + /** + * Create a new virtual machine in a virtual appliance. + * + * @param virtualAppliance + * The virtual appliance. + * @param virtualMachine + * The virtual machine to be created. + * @return The created virtual machine. + */ + VirtualMachineWithNodeExtendedDto createVirtualMachine(VirtualApplianceDto virtualAppliance, + VirtualMachineWithNodeExtendedDto virtualMachine); + + /** + * Deletes an existing virtual machine. + * + * @param virtualMachine + * The virtual machine to delete. + */ + void deleteVirtualMachine(VirtualMachineDto virtualMachine); + + /** + * Updates an existing virtual machine from the given virtual appliance. + * + * @param virtualMachine + * The new attributes for the virtual machine. + * @return The task reference or null if the operation completed + * synchronously. + */ + AcceptedRequestDto updateVirtualMachine(VirtualMachineWithNodeExtendedDto virtualMachine); + + /** + * Updates an existing virtual machine from the given virtual appliance. + * + * @param virtualMachine + * The new attributes for the virtual machine. + * @param options + * The update options. + * @return The task reference or null if the operation completed + * synchronously. + */ + AcceptedRequestDto updateVirtualMachine(VirtualMachineWithNodeExtendedDto virtualMachine, + VirtualMachineOptions options); + + /** + * Changes the state an existing virtual machine. + * + * @param virtualMachine + * The given virtual machine. + * @param state + * The new state. + * @return The task reference. + */ + AcceptedRequestDto changeVirtualMachineState(VirtualMachineDto virtualMachine, VirtualMachineStateDto state); + + /** + * Get the state of the given virtual machine. + * + * @param virtualMachine + * The given virtual machine. + * @return The state of the given virtual machine. + */ + VirtualMachineStateDto getVirtualMachineState(VirtualMachineDto virtualMachine); + + /** + * Deploy a virtual machine with task options. + * + * @param virtualMachine + * The virtual machine to deploy. + * @param options + * extra deploy options. + * @return Response message to the deploy request. + */ + @Timeout(duration = 90, timeUnit = TimeUnit.SECONDS) + AcceptedRequestDto deployVirtualMachine(VirtualMachineDto virtualMachine, VirtualMachineTaskDto options); + + /** + * Uneploy a virtual machine with task options. + * + * @param virtualMachine + * The virtual machine to undeploy. + * @param options + * extra deploy unoptions. + * @return Response message to the undeploy request. + */ + @Timeout(duration = 90, timeUnit = TimeUnit.SECONDS) + AcceptedRequestDto undeployVirtualMachine(VirtualMachineDto virtualMachine, VirtualMachineTaskDto options); + + /** + * List all available network configurations for a virtual machine. + * + * @param virtualMachine + * The virtual machine. + * @return The list of network configurations. + */ + VMNetworkConfigurationsDto listNetworkConfigurations(VirtualMachineDto virtualMachine); + + /** + * Sets the gateway network to be used by this virtual machine. + * + * @param virtualMachine + * The virtual machine. + * @param network + * The gateway network to use. + */ + void setGatewayNetwork(final VirtualMachineDto virtualMachine, final VLANNetworkDto network); + + /** + * Reboot a virtual machine. + * + * @param virtualMachine + * The virtual machine to reboot. + * @return Response message to the reset request. + */ + AcceptedRequestDto rebootVirtualMachine(VirtualMachineDto virtualMachine); + + /******************* Virtual Machine Template ***********************/ + + /** + * Get the template of a virtual machine. + * + * @param virtualMachine + * The given virtual machine. + * @return The template of the given virtual machine. + */ + VirtualMachineTemplateDto getVirtualMachineTemplate(VirtualMachineDto virtualMachine); + + /** + * Get the volumes attached to the given virtual machine. + * + * @param virtualMachine + * The virtual machine. + * @return The volumes attached to the given virtual machine. + */ + VolumesManagementDto listAttachedVolumes(VirtualMachineDto virtualMachine); + + /** + * Detach all volumes from the given virtual machine. + *

+ * If the virtual machine is deployed, the operation will be executed + * asynchronously. + * + * @param virtualMachine + * The virtual machine. + * @return The task reference or null if the operation completed + * synchronously. + */ + AcceptedRequestDto detachAllVolumes(VirtualMachineDto virtualMachine); + + /** + * Replaces the current volumes attached to the virtual machine with the + * given ones. + *

+ * If the virtual machine is deployed, the operation will be executed + * asynchronously. + * + * @param virtualMachine + * The virtual machine. + * @param options + * virtual machine parameters + * @param volumes + * The new volumes for the virtual machine. + * @return The task reference or null if the operation completed + * synchronously. + */ + @Timeout(duration = 90, timeUnit = TimeUnit.SECONDS) + AcceptedRequestDto replaceVolumes(VirtualMachineDto virtualMachine, VirtualMachineOptions options, + VolumeManagementDto... volumes); + + /** + * List all hard disks attached to the given virtual machine. + * + * @param virtualMachine + * The virtual machine. + * @return The hard disks attached to the virtual machine. + */ + DisksManagementDto listAttachedHardDisks(VirtualMachineDto virtualMachine); + + /** + * Detach all hard disks from the given virtual machine. + *

+ * If the virtual machine is deployed, the operation will be executed + * asynchronously. + * + * @param virtualMachine + * The virtual machine. + * @return The task reference or null if the operation completed + * synchronously. + */ + AcceptedRequestDto detachAllHardDisks(VirtualMachineDto virtualMachine); + + /** + * Replaces the current hard disks attached to the virtual machine with the + * given ones. + *

+ * If the virtual machine is deployed, the operation will be executed + * asynchronously. + * + * @param virtualMachine + * The virtual machine. + * @param hardDisks + * The new hard disks for the virtual machine. + * @return The task reference or null if the operation completed + * synchronously. + */ + AcceptedRequestDto replaceHardDisks(VirtualMachineDto virtualMachine, DiskManagementDto... hardDisks); + + /*********************** Hard disks ***********************/ + + /** + * List all hard disks in the given virtual datacenter. + * + * @param virtualDatacenter + * The virtual datacenter. + * @return The hard disks in the virtual datacenter. + */ + DisksManagementDto listHardDisks(VirtualDatacenterDto virtualDatacenter); + + /** + * Get the hard disk with the given id in the given virtual datacenter. + * + * @param virtualDatacenter + * The virtual datacenter. + * @param diskId + * The id of the hard disk to get. + * @return The requested hard disk or null if it does not exist. + */ + DiskManagementDto getHardDisk(VirtualDatacenterDto virtualDatacenter, Integer diskId); + + /** + * Creates a new hard disk in the given virtual datacenter. + * + * @param virtualDatacenter + * The virtual datacenter where the hard disk will be created. + * @param hardDisk + * The hard disk to create. + * @return The created hard disk. + */ + DiskManagementDto createHardDisk(VirtualDatacenterDto virtualDatacenter, DiskManagementDto hardDisk); + + /** + * Deletes the given hard disk. + * + * @param hardDisk + * The hard disk to delete. + */ + void deleteHardDisk(DiskManagementDto hardDisk); + + /*********************** Volumes ***********************/ + + /** + * List all volumes in the given virtual datacenter. + * + * @param virtualDatacenter + * The virtual datacenter. + * @return The volumes in the virtual datacenter. + */ + @EnterpriseEdition + VolumesManagementDto listVolumes(VirtualDatacenterDto virtualDatacenter); + + /** + * List all volumes in the given virtual datacenter. + * + * @param virtualDatacenter + * The virtual datacenter. + * @param options + * Optional parameters to filter the volume list. + * @return The volumes in the virtual datacenter. + */ + @EnterpriseEdition + VolumesManagementDto listVolumes(VirtualDatacenterDto virtualDatacenter, VolumeOptions options); + + /** + * Get a volume from the given virtual datacenter. + * + * @param virtualDatacenter + * The virtual datacenter. + * @param volumeId + * The id of the volume to get. + * @return The volume or null if it does not exist. + */ + @EnterpriseEdition + VolumeManagementDto getVolume(VirtualDatacenterDto virtualDatacenter, Integer volumeId); + + /** + * Creates a volume in the given virtual datacenter. + * + * @param virtualDatacenter + * The virtual datacenter where the volume will be created. + * @param volume + * The volume to create. This volume dto must contain a link to the + * tier where the volume should be created. + * @return The created volume. + */ + @EnterpriseEdition + @Timeout(duration = 90, timeUnit = TimeUnit.SECONDS) + VolumeManagementDto createVolume(VirtualDatacenterDto virtualDatacenter, VolumeManagementDto volume); + + /** + * Modifies the given volume. + *

+ * If the virtual machine is deployed and the size of the volume is changed, + * then an asynchronous task will be generated to refresh the resources of + * the virtual machine in the hypervisor. + * + * @param volume + * The volume to modify. + * @return The task reference or null if no task was generated. + */ + @EnterpriseEdition + @Timeout(duration = 90, timeUnit = TimeUnit.SECONDS) + AcceptedRequestDto updateVolume(VolumeManagementDto volume); + + /** + * Delete the given volume. + * + * @param volume + * The volume to delete. + */ + @EnterpriseEdition + @Timeout(duration = 90, timeUnit = TimeUnit.SECONDS) + void deleteVolume(VolumeManagementDto volume); + + /** + * Moves the given volume to a new virtual datacenter. + *

+ * The Abiquo API will return a 301 (Moved Permanently), so redirects must be + * enabled to make this method succeed. + * + * @param volume + * The volume to move. + * @param newVirtualDatacenter + * The destination virtual datacenter. + * @return The reference to the volume in the new virtual datacenter. + */ + @EnterpriseEdition + VolumeManagementDto moveVolume(VolumeManagementDto volume, VirtualDatacenterDto newVirtualDatacenter); + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/features/CloudAsyncApi.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/features/CloudAsyncApi.java new file mode 100644 index 0000000000..d79839bb2b --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/features/CloudAsyncApi.java @@ -0,0 +1,783 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.features; + +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 javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; + +import org.jclouds.abiquo.binders.AppendToPath; +import org.jclouds.abiquo.binders.BindToPath; +import org.jclouds.abiquo.binders.BindToXMLPayloadAndPath; +import org.jclouds.abiquo.binders.cloud.BindHardDiskRefsToPayload; +import org.jclouds.abiquo.binders.cloud.BindMoveVolumeToPath; +import org.jclouds.abiquo.binders.cloud.BindNetworkConfigurationRefToPayload; +import org.jclouds.abiquo.binders.cloud.BindNetworkRefToPayload; +import org.jclouds.abiquo.binders.cloud.BindVirtualDatacenterRefToPayload; +import org.jclouds.abiquo.binders.cloud.BindVolumeRefsToPayload; +import org.jclouds.abiquo.domain.cloud.VirtualDatacenter; +import org.jclouds.abiquo.domain.cloud.options.VirtualApplianceOptions; +import org.jclouds.abiquo.domain.cloud.options.VirtualDatacenterOptions; +import org.jclouds.abiquo.domain.cloud.options.VirtualMachineOptions; +import org.jclouds.abiquo.domain.cloud.options.VirtualMachineTemplateOptions; +import org.jclouds.abiquo.domain.cloud.options.VolumeOptions; +import org.jclouds.abiquo.domain.enterprise.Enterprise; +import org.jclouds.abiquo.domain.infrastructure.Datacenter; +import org.jclouds.abiquo.domain.network.options.IpOptions; +import org.jclouds.abiquo.functions.ReturnTaskReferenceOrNull; +import org.jclouds.abiquo.functions.cloud.ReturnMovedVolume; +import org.jclouds.abiquo.functions.enterprise.ParseEnterpriseId; +import org.jclouds.abiquo.functions.infrastructure.ParseDatacenterId; +import org.jclouds.abiquo.http.filters.AbiquoAuthentication; +import org.jclouds.abiquo.http.filters.AppendApiVersionToMediaType; +import org.jclouds.abiquo.reference.annotations.EnterpriseEdition; +import org.jclouds.abiquo.rest.annotations.EndpointLink; +import org.jclouds.http.functions.ReturnStringIf2xx; +import org.jclouds.rest.annotations.BinderParam; +import org.jclouds.rest.annotations.ExceptionParser; +import org.jclouds.rest.annotations.JAXBResponseParser; +import org.jclouds.rest.annotations.ParamParser; +import org.jclouds.rest.annotations.RequestFilters; +import org.jclouds.rest.annotations.ResponseParser; +import org.jclouds.rest.binders.BindToXMLPayload; +import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; + +import com.abiquo.model.transport.AcceptedRequestDto; +import com.abiquo.model.transport.LinksDto; +import com.abiquo.server.core.appslibrary.VirtualMachineTemplateDto; +import com.abiquo.server.core.appslibrary.VirtualMachineTemplatesDto; +import com.abiquo.server.core.cloud.VirtualApplianceDto; +import com.abiquo.server.core.cloud.VirtualApplianceStateDto; +import com.abiquo.server.core.cloud.VirtualAppliancesDto; +import com.abiquo.server.core.cloud.VirtualDatacenterDto; +import com.abiquo.server.core.cloud.VirtualDatacentersDto; +import com.abiquo.server.core.cloud.VirtualMachineDto; +import com.abiquo.server.core.cloud.VirtualMachineStateDto; +import com.abiquo.server.core.cloud.VirtualMachineTaskDto; +import com.abiquo.server.core.cloud.VirtualMachineWithNodeExtendedDto; +import com.abiquo.server.core.cloud.VirtualMachinesWithNodeExtendedDto; +import com.abiquo.server.core.enterprise.EnterpriseDto; +import com.abiquo.server.core.infrastructure.DatacenterDto; +import com.abiquo.server.core.infrastructure.network.PrivateIpDto; +import com.abiquo.server.core.infrastructure.network.PrivateIpsDto; +import com.abiquo.server.core.infrastructure.network.PublicIpDto; +import com.abiquo.server.core.infrastructure.network.PublicIpsDto; +import com.abiquo.server.core.infrastructure.network.VLANNetworkDto; +import com.abiquo.server.core.infrastructure.network.VLANNetworksDto; +import com.abiquo.server.core.infrastructure.network.VMNetworkConfigurationDto; +import com.abiquo.server.core.infrastructure.network.VMNetworkConfigurationsDto; +import com.abiquo.server.core.infrastructure.storage.DiskManagementDto; +import com.abiquo.server.core.infrastructure.storage.DisksManagementDto; +import com.abiquo.server.core.infrastructure.storage.MovedVolumeDto; +import com.abiquo.server.core.infrastructure.storage.TierDto; +import com.abiquo.server.core.infrastructure.storage.TiersDto; +import com.abiquo.server.core.infrastructure.storage.VolumeManagementDto; +import com.abiquo.server.core.infrastructure.storage.VolumesManagementDto; +import com.google.common.util.concurrent.ListenableFuture; + +/** + * Provides asynchronous access to Abiquo Cloud API. + * + * @see API: + * http://community.abiquo.com/display/ABI20/API+Reference + * @see CloudApi + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +@RequestFilters({ AbiquoAuthentication.class, AppendApiVersionToMediaType.class }) +@Path("/cloud") +public interface CloudAsyncApi { + /*********************** Virtual Datacenter ***********************/ + + /** + * @see CloudApi#listVirtualDatacenters(VirtualDatacenterOptions) + */ + @GET + @Path("/virtualdatacenters") + @Consumes(VirtualDatacentersDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listVirtualDatacenters(VirtualDatacenterOptions options); + + /** + * @see CloudApi#getVirtualDatacenter(Integer) + */ + @GET + @Path("/virtualdatacenters/{virtualdatacenter}") + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + @Consumes(VirtualDatacenterDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture getVirtualDatacenter( + @PathParam("virtualdatacenter") Integer virtualDatacenterId); + + /** + * @see CloudApi#createVirtualDatacenter(VirtualDatacenterDto, Datacenter, + * Enterprise) + */ + @POST + @Path("/virtualdatacenters") + @Consumes(VirtualDatacenterDto.BASE_MEDIA_TYPE) + @Produces(VirtualDatacenterDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture createVirtualDatacenter( + @BinderParam(BindToXMLPayload.class) final VirtualDatacenterDto virtualDatacenter, + @QueryParam("datacenter") @ParamParser(ParseDatacenterId.class) final DatacenterDto datacenter, + @QueryParam("enterprise") @ParamParser(ParseEnterpriseId.class) final EnterpriseDto enterprise); + + /** + * @see CloudApi#updateVirtualDatacenter(VirtualDatacenterDto) + */ + @PUT + @Consumes(VirtualDatacenterDto.BASE_MEDIA_TYPE) + @Produces(VirtualDatacenterDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture updateVirtualDatacenter( + @EndpointLink("edit") @BinderParam(BindToXMLPayloadAndPath.class) VirtualDatacenterDto virtualDatacenter); + + /** + * @see CloudApi#deleteVirtualDatacenter(VirtualDatacenterDto) + */ + @DELETE + ListenableFuture deleteVirtualDatacenter( + @EndpointLink("edit") @BinderParam(BindToPath.class) VirtualDatacenterDto virtualDatacenter); + + /** + * @see CloudApi#listAvailableTemplates(VirtualDatacenterDto) + */ + @GET + @Consumes(VirtualMachineTemplatesDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listAvailableTemplates( + @EndpointLink("templates") @BinderParam(BindToPath.class) VirtualDatacenterDto virtualDatacenter); + + /** + * @see CloudApi#listAvailableTemplates(VirtualDatacenterDto, + * VirtualMachineTemplateOptions) + */ + @GET + @Consumes(VirtualMachineTemplatesDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listAvailableTemplates( + @EndpointLink("templates") @BinderParam(BindToPath.class) VirtualDatacenterDto virtualDatacenter, + VirtualMachineTemplateOptions options); + + /** + * @see CloudApi#listStorageTiers(VirtualDatacenterDto) + */ + @EnterpriseEdition + @GET + @Consumes(TiersDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listStorageTiers( + @EndpointLink("tiers") @BinderParam(BindToPath.class) VirtualDatacenterDto virtualDatacenter); + + /** + * @see CloudApi#getStorageTier(VirtualDatacenterDto, Integer) + */ + @EnterpriseEdition + @GET + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + @Consumes(TierDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture getStorageTier( + @EndpointLink("tiers") @BinderParam(BindToPath.class) VirtualDatacenterDto virtualDatacenter, + @BinderParam(AppendToPath.class) Integer tierId); + + /*********************** Public IP ***********************/ + + /** + * @see CloudApi#listAvailablePublicIps(VirtualDatacenterDto, IpOptions) + */ + @GET + @Consumes(PublicIpsDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listAvailablePublicIps( + @EndpointLink("topurchase") @BinderParam(BindToPath.class) VirtualDatacenterDto virtualDatacenter, + IpOptions options); + + /** + * @see CloudApi#listPurchasedPublicIps(VirtualDatacenterDto, IpOptions) + */ + @GET + @Consumes(PublicIpsDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listPurchasedPublicIps( + @EndpointLink("purchased") @BinderParam(BindToPath.class) VirtualDatacenterDto virtualDatacenter, + IpOptions options); + + /** + * @see CloudApi#purchasePublicIp(PublicIpDto) + */ + @PUT + @Consumes(PublicIpDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture purchasePublicIp( + @EndpointLink("purchase") @BinderParam(BindToPath.class) PublicIpDto publicIp); + + /** + * @see CloudApi#releasePublicIp(PublicIpDto) + */ + @PUT + @Consumes(PublicIpDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture releasePublicIp( + @EndpointLink("release") @BinderParam(BindToPath.class) PublicIpDto publicIp); + + /*********************** Private Network ***********************/ + + /** + * @see CloudApi#listPrivateNetworks(VirtualDatacenter) + */ + @GET + @Consumes(VLANNetworksDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listPrivateNetworks( + @EndpointLink("privatenetworks") @BinderParam(BindToPath.class) VirtualDatacenterDto virtualDatacenter); + + /** + * @see CloudApi#getPrivateNetwork(VirtualDatacenterDto, Integer) + */ + @GET + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + @Consumes(VLANNetworkDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture getPrivateNetwork( + @EndpointLink("privatenetworks") @BinderParam(BindToPath.class) VirtualDatacenterDto virtualDatacenter, + @BinderParam(AppendToPath.class) Integer privateNetworkId); + + /** + * @see CloudApi#createPrivateNetwork(VirtualDatacenterDto, VLANNetworkDto) + */ + @POST + @Consumes(VLANNetworkDto.BASE_MEDIA_TYPE) + @Produces(VLANNetworkDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture createPrivateNetwork( + @EndpointLink("privatenetworks") @BinderParam(BindToPath.class) VirtualDatacenterDto virtualDatacenter, + @BinderParam(BindToXMLPayload.class) VLANNetworkDto privateNetwork); + + /** + * @see CloudApi#updatePrivateNetwork(VLANNetworkDto) + */ + @PUT + @Consumes(VLANNetworkDto.BASE_MEDIA_TYPE) + @Produces(VLANNetworkDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture updatePrivateNetwork( + @EndpointLink("edit") @BinderParam(BindToXMLPayloadAndPath.class) VLANNetworkDto privateNetwork); + + /** + * @see CloudApi#deletePrivateNetwork(VLANNetworkDto) + */ + @DELETE + ListenableFuture deletePrivateNetwork( + @EndpointLink("edit") @BinderParam(BindToPath.class) VLANNetworkDto privateNetwork); + + /** + * @see CloudApi#getDefaultNetwork(VirtualDatacenterDto) + */ + @GET + @Consumes(VLANNetworkDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture getDefaultNetwork( + @EndpointLink("defaultnetwork") @BinderParam(BindToPath.class) VirtualDatacenterDto virtualDatacenter); + + /** + * @see CloudApi#setDefaultNetwork(VirtualDatacenterDto, VLANNetworkDto) + */ + @PUT + @Produces(LinksDto.BASE_MEDIA_TYPE) + ListenableFuture setDefaultNetwork( + @EndpointLink("defaultvlan") @BinderParam(BindToPath.class) VirtualDatacenterDto virtualDatacenter, + @BinderParam(BindNetworkRefToPayload.class) VLANNetworkDto network); + + /*********************** Private Network IPs ***********************/ + + /** + * @see CloudApi#listPrivateNetworkIps(VLANNetworkDto) + */ + @GET + @Consumes(PrivateIpsDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listPrivateNetworkIps( + @EndpointLink("ips") @BinderParam(BindToPath.class) VLANNetworkDto network); + + /** + * @see CloudApi#listPrivateNetworkIps(VLANNetworkDto, IpOptions) + */ + @GET + @Consumes(PrivateIpsDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listPrivateNetworkIps( + @EndpointLink("ips") @BinderParam(BindToPath.class) VLANNetworkDto network, IpOptions options); + + /** + * @see CloudApi#getPrivateNetworkIp(VLANNetworkDto, Integer) + */ + @GET + @Consumes(PrivateIpDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture getPrivateNetworkIp( + @EndpointLink("ips") @BinderParam(BindToPath.class) VLANNetworkDto network, + @BinderParam(AppendToPath.class) Integer ipId); + + /*********************** Virtual Appliance ***********************/ + + /** + * @see CloudApi#listVirtualAppliances(VirtualDatacenterDto) + */ + @GET + @Consumes(VirtualAppliancesDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listVirtualAppliances( + @EndpointLink("virtualappliances") @BinderParam(BindToPath.class) VirtualDatacenterDto virtualDatacenter); + + /** + * @see CloudApi#getVirtualAppliance(VirtualDatacenterDto, Integer) + */ + @GET + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + @Consumes(VirtualApplianceDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture getVirtualAppliance( + @EndpointLink("virtualappliances") @BinderParam(BindToPath.class) VirtualDatacenterDto virtualDatacenter, + @BinderParam(AppendToPath.class) Integer virtualApplianceId); + + /** + * @see CloudApi#getVirtualApplianceState(VirtualApplianceDto) + */ + @GET + @Consumes(VirtualApplianceStateDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture getVirtualApplianceState( + @EndpointLink("state") @BinderParam(BindToPath.class) VirtualApplianceDto virtualAppliance); + + /** + * @see CloudApi#createVirtualAppliance(VirtualDatacenterDto, + * VirtualApplianceDto) + */ + @POST + @Consumes(VirtualApplianceDto.BASE_MEDIA_TYPE) + @Produces(VirtualApplianceDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture createVirtualAppliance( + @EndpointLink("virtualappliances") @BinderParam(BindToPath.class) VirtualDatacenterDto virtualDatacenter, + @BinderParam(BindToXMLPayload.class) VirtualApplianceDto virtualAppliance); + + /** + * @see CloudApi#updateVirtualAppliance(VirtualApplianceDto) + */ + @PUT + @Consumes(VirtualApplianceDto.BASE_MEDIA_TYPE) + @Produces(VirtualApplianceDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture updateVirtualAppliance( + @EndpointLink("edit") @BinderParam(BindToXMLPayloadAndPath.class) VirtualApplianceDto virtualAppliance); + + /** + * @see CloudApi#deleteVirtualAppliance(VirtualApplianceDto) + */ + @DELETE + ListenableFuture deleteVirtualAppliance( + @EndpointLink("edit") @BinderParam(BindToPath.class) VirtualApplianceDto virtualAppliance); + + /** + * @see CloudApi#deleteVirtualAppliance(VirtualApplianceDto, + * VirtualApplianceOptions) + */ + @DELETE + ListenableFuture deleteVirtualAppliance( + @EndpointLink("edit") @BinderParam(BindToPath.class) VirtualApplianceDto virtualAppliance, + VirtualApplianceOptions options); + + /** + * @see CloudApi#deployVirtualAppliance(VirtualApplianceDto, + * VirtualMachineTaskDto) + */ + @POST + @Consumes(AcceptedRequestDto.BASE_MEDIA_TYPE) + @Produces(VirtualMachineTaskDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture> deployVirtualAppliance( + @EndpointLink("deploy") @BinderParam(BindToPath.class) VirtualApplianceDto virtualAppliance, + @BinderParam(BindToXMLPayload.class) VirtualMachineTaskDto task); + + /** + * @see CloudApi#undeployVirtualAppliance(VirtualApplianceDto, + * VirtualMachineTaskDto) + */ + @POST + @Consumes(AcceptedRequestDto.BASE_MEDIA_TYPE) + @Produces(VirtualMachineTaskDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture> undeployVirtualAppliance( + @EndpointLink("undeploy") @BinderParam(BindToPath.class) VirtualApplianceDto virtualAppliance, + @BinderParam(BindToXMLPayload.class) VirtualMachineTaskDto task); + + /** + * @see CloudApi#getVirtualAppliancePrice(VirtualApplianceDto) + */ + @GET + @Consumes(MediaType.TEXT_PLAIN) + @ResponseParser(ReturnStringIf2xx.class) + ListenableFuture getVirtualAppliancePrice( + @EndpointLink("price") @BinderParam(BindToPath.class) VirtualApplianceDto virtualAppliance); + + /*********************** Virtual Machine ***********************/ + + /** + * @see CloudApi#listVirtualMachines(VirtualApplianceDto) + */ + @GET + @Consumes(VirtualMachinesWithNodeExtendedDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listVirtualMachines( + @EndpointLink("virtualmachines") @BinderParam(BindToPath.class) VirtualApplianceDto virtualAppliance); + + /** + * @see CloudApi#listVirtualMachines(VirtualApplianceDto, + * VirtualMachineOptions) + */ + @GET + @Consumes(VirtualMachinesWithNodeExtendedDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listVirtualMachines( + @EndpointLink("virtualmachines") @BinderParam(BindToPath.class) VirtualApplianceDto virtualAppliance, + VirtualMachineOptions options); + + /** + * @see CloudApi#getVirtualMachine(VirtualApplianceDto, Integer) + */ + @GET + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + @Consumes(VirtualMachineWithNodeExtendedDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture getVirtualMachine( + @EndpointLink("virtualmachines") @BinderParam(BindToPath.class) VirtualApplianceDto virtualAppliance, + @BinderParam(AppendToPath.class) Integer virtualMachineId); + + /** + * @see CloudApi#createVirtualMachine(VirtualApplianceDto, + * VirtualMachineWithNodeExtendedDto) + */ + @POST + @Consumes(VirtualMachineWithNodeExtendedDto.BASE_MEDIA_TYPE) + @Produces(VirtualMachineWithNodeExtendedDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture createVirtualMachine( + @EndpointLink("virtualmachines") @BinderParam(BindToPath.class) VirtualApplianceDto virtualAppliance, + @BinderParam(BindToXMLPayload.class) VirtualMachineWithNodeExtendedDto virtualMachine); + + /** + * @see CloudApi#deleteVirtualMachine(VirtualMachineDto) + */ + @DELETE + ListenableFuture deleteVirtualMachine( + @EndpointLink("edit") @BinderParam(BindToPath.class) VirtualMachineDto virtualMachine); + + /** + * @see CloudApi#updateVirtualMachine(VirtualMachineWithNodeExtendedDto) + */ + @PUT + @ResponseParser(ReturnTaskReferenceOrNull.class) + @Consumes(AcceptedRequestDto.BASE_MEDIA_TYPE) + @Produces(VirtualMachineWithNodeExtendedDto.BASE_MEDIA_TYPE) + ListenableFuture> updateVirtualMachine( + @EndpointLink("edit") @BinderParam(BindToXMLPayloadAndPath.class) VirtualMachineWithNodeExtendedDto virtualMachine); + + /** + * @see CloudApi#updateVirtualMachine(VirtualMachineDto, + * VirtualMachineOptions) + */ + @PUT + @ResponseParser(ReturnTaskReferenceOrNull.class) + @Consumes(AcceptedRequestDto.BASE_MEDIA_TYPE) + @Produces(VirtualMachineWithNodeExtendedDto.BASE_MEDIA_TYPE) + ListenableFuture> updateVirtualMachine( + @EndpointLink("edit") @BinderParam(BindToXMLPayloadAndPath.class) VirtualMachineWithNodeExtendedDto virtualMachine, + VirtualMachineOptions options); + + /** + * @see CloudApi#changeVirtualMachineState(VirtualMachineDto, + * VirtualMachineStateDto) + */ + @PUT + @Consumes(AcceptedRequestDto.BASE_MEDIA_TYPE) + @Produces(VirtualMachineStateDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture> changeVirtualMachineState( + @EndpointLink("state") @BinderParam(BindToPath.class) VirtualMachineDto virtualMachine, + @BinderParam(BindToXMLPayload.class) VirtualMachineStateDto state); + + /** + * @see CloudApi#getVirtualMachineState(VirtualMachineDto) + */ + @GET + @Consumes(VirtualMachineStateDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture getVirtualMachineState( + @EndpointLink("state") @BinderParam(BindToPath.class) VirtualMachineDto virtualMachine); + + /** + * @see CloudApi#listNetworkConfigurations(VirtualMachineDto) + */ + @GET + @Consumes(VMNetworkConfigurationsDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listNetworkConfigurations( + @EndpointLink("configurations") @BinderParam(BindToPath.class) VirtualMachineDto virtualMachine); + + /** + * @see CloudApi#setGatewayNetwork(VirtualMachineDto, + * VMNetworkConfigurationDto) + */ + @PUT + @Produces(LinksDto.BASE_MEDIA_TYPE) + ListenableFuture setGatewayNetwork( + @EndpointLink("configurations") @BinderParam(BindToPath.class) VirtualMachineDto virtualMachine, + @BinderParam(BindNetworkConfigurationRefToPayload.class) VLANNetworkDto network); + + /** + * @see CloudApi#rebootVirtualMachine(VirtualMachineDto) + */ + @POST + @Consumes(AcceptedRequestDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture> rebootVirtualMachine( + @EndpointLink("reset") @BinderParam(BindToPath.class) VirtualMachineDto virtualMachine); + + /*********************** Virtual Machine Template ***********************/ + + /** + * @see CloudApi#getVirtualMachineTemplate(VirtualMachineTemplateDto) + */ + @GET + @Consumes(VirtualMachineTemplateDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture getVirtualMachineTemplate( + @EndpointLink("virtualmachinetemplate") @BinderParam(BindToPath.class) VirtualMachineDto virtualMachine); + + /** + * @see CloudApi#listAttachedVolumes(VirtualMachineDto) + */ + @GET + @Consumes(VolumesManagementDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listAttachedVolumes( + @EndpointLink("volumes") @BinderParam(BindToPath.class) VirtualMachineDto virtualMachine); + + /** + * @see CloudApi#detachAllVolumes(VirtualMachineDto) + */ + @DELETE + @ResponseParser(ReturnTaskReferenceOrNull.class) + @Consumes(AcceptedRequestDto.BASE_MEDIA_TYPE) + ListenableFuture> detachAllVolumes( + @EndpointLink("volumes") @BinderParam(BindToPath.class) VirtualMachineDto virtualMachine); + + /** + * @see CloudApi#replaceVolumes(VirtualMachineDto, VirtualMachineOptions, + * VolumeManagementDto...) + */ + @PUT + @ResponseParser(ReturnTaskReferenceOrNull.class) + @Consumes(AcceptedRequestDto.BASE_MEDIA_TYPE) + @Produces(LinksDto.BASE_MEDIA_TYPE) + ListenableFuture> replaceVolumes( + @EndpointLink("volumes") @BinderParam(BindToPath.class) VirtualMachineDto virtualMachine, + VirtualMachineOptions options, @BinderParam(BindVolumeRefsToPayload.class) VolumeManagementDto... volumes); + + /** + * @see CloudApi#listAttachedHardDisks(VirtualMachineDto) + */ + @GET + @Consumes(DisksManagementDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listAttachedHardDisks( + @EndpointLink("disks") @BinderParam(BindToPath.class) VirtualMachineDto virtualMachine); + + /** + * @see CloudApi#detachAllHardDisks(VirtualMachineDto) + */ + @DELETE + @ResponseParser(ReturnTaskReferenceOrNull.class) + @Consumes(AcceptedRequestDto.BASE_MEDIA_TYPE) + ListenableFuture> detachAllHardDisks( + @EndpointLink("disks") @BinderParam(BindToPath.class) VirtualMachineDto virtualMachine); + + /** + * @see CloudApi#replaceHardDisks(VirtualMachineDto, DiskManagementDto...) + */ + @PUT + @ResponseParser(ReturnTaskReferenceOrNull.class) + @Consumes(AcceptedRequestDto.BASE_MEDIA_TYPE) + @Produces(LinksDto.BASE_MEDIA_TYPE) + ListenableFuture> replaceHardDisks( + @EndpointLink("disks") @BinderParam(BindToPath.class) VirtualMachineDto virtualMachine, + @BinderParam(BindHardDiskRefsToPayload.class) DiskManagementDto... hardDisks); + + /** + * @see CloudApi#deployVirtualMachine(VirtualMachineDto, + * VirtualMachineTaskDto) + */ + @POST + @Consumes(AcceptedRequestDto.BASE_MEDIA_TYPE) + @Produces(VirtualMachineTaskDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture> deployVirtualMachine( + @EndpointLink("deploy") @BinderParam(BindToPath.class) VirtualMachineDto virtualMachine, + @BinderParam(BindToXMLPayload.class) VirtualMachineTaskDto task); + + /** + * @see CloudApi#undeployVirtualMachine(VirtualMachineDto, + * VirtualMachineTaskDto) + */ + @POST + @Consumes(AcceptedRequestDto.BASE_MEDIA_TYPE) + @Produces(VirtualMachineTaskDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture> undeployVirtualMachine( + @EndpointLink("undeploy") @BinderParam(BindToPath.class) VirtualMachineDto virtualMachine, + @BinderParam(BindToXMLPayload.class) VirtualMachineTaskDto task); + + /*********************** Hard disks ***********************/ + + /** + * @see CloudApi#listHardDisks(VirtualDatacenterDto) + */ + @GET + @Consumes(DisksManagementDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listHardDisks( + @EndpointLink("disks") @BinderParam(BindToPath.class) VirtualDatacenterDto virtualDatacenter); + + /** + * @see CloudApi#getHardDisk(VirtualDatacenterDto, Integer) + */ + @GET + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + @Consumes(DiskManagementDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture getHardDisk( + @EndpointLink("disks") @BinderParam(BindToPath.class) VirtualDatacenterDto virtualDatacenter, + @BinderParam(AppendToPath.class) Integer diskId); + + /** + * @see CloudApi#createHardDisk(VirtualDatacenterDto, DiskManagementDto) + */ + @POST + @Consumes(DiskManagementDto.BASE_MEDIA_TYPE) + @Produces(DiskManagementDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture createHardDisk( + @EndpointLink("disks") @BinderParam(BindToPath.class) VirtualDatacenterDto virtualDatacenter, + @BinderParam(BindToXMLPayload.class) DiskManagementDto hardDisk); + + /** + * @see CloudApi#deleteHardDisk(DiskManagementDto) + */ + @DELETE + ListenableFuture deleteHardDisk(@EndpointLink("edit") @BinderParam(BindToPath.class) DiskManagementDto hardDisk); + + /*********************** Volumes ***********************/ + + /** + * @see CloudApi#listVolumes(VirtualDatacenterDto) + */ + @EnterpriseEdition + @GET + @Consumes(VolumesManagementDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listVolumes( + @EndpointLink("volumes") @BinderParam(BindToPath.class) VirtualDatacenterDto virtualDatacenter); + + /** + * @see CloudApi#listVolumes(VirtualDatacenterDto, VolumeOptions) + */ + @EnterpriseEdition + @GET + @Consumes(VolumesManagementDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listVolumes( + @EndpointLink("volumes") @BinderParam(BindToPath.class) VirtualDatacenterDto virtualDatacenter, + VolumeOptions options); + + /** + * @see CloudApi#getVolume(VirtualDatacenterDto, Integer) + */ + @EnterpriseEdition + @GET + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + @Consumes(VolumeManagementDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture getVolume( + @EndpointLink("volumes") @BinderParam(BindToPath.class) VirtualDatacenterDto virtualDatacenter, + @BinderParam(AppendToPath.class) Integer volumeId); + + /** + * @see CloudApi#createVolume(VirtualDatacenterDto, VolumeManagementDto) + */ + @EnterpriseEdition + @POST + @Consumes(VolumeManagementDto.BASE_MEDIA_TYPE) + @Produces(VolumeManagementDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture createVolume( + @EndpointLink("volumes") @BinderParam(BindToPath.class) VirtualDatacenterDto virtualDatacenter, + @BinderParam(BindToXMLPayload.class) VolumeManagementDto volume); + + /** + * @see CloudApi#updateVolume(VolumeManagementDto) + */ + @EnterpriseEdition + @PUT + @ResponseParser(ReturnTaskReferenceOrNull.class) + @Consumes(AcceptedRequestDto.BASE_MEDIA_TYPE) + @Produces(VolumeManagementDto.BASE_MEDIA_TYPE) + ListenableFuture> updateVolume( + @EndpointLink("edit") @BinderParam(BindToXMLPayloadAndPath.class) VolumeManagementDto volume); + + /** + * @see CloudApi#updateVolume(VolumeManagementDto) + */ + @EnterpriseEdition + @DELETE + ListenableFuture deleteVolume(@EndpointLink("edit") @BinderParam(BindToPath.class) VolumeManagementDto volume); + + /** + * @see CloudApi#moveVolume(VolumeManagementDto, VirtualDatacenterDto) + */ + @EnterpriseEdition + @POST + @ExceptionParser(ReturnMovedVolume.class) + @Consumes(MovedVolumeDto.BASE_MEDIA_TYPE) + @Produces(LinksDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture moveVolume( + @BinderParam(BindMoveVolumeToPath.class) VolumeManagementDto volume, + @BinderParam(BindVirtualDatacenterRefToPayload.class) VirtualDatacenterDto newVirtualDatacenter); + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/features/ConfigApi.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/features/ConfigApi.java new file mode 100644 index 0000000000..fee541be01 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/features/ConfigApi.java @@ -0,0 +1,176 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.features; + +import java.util.concurrent.TimeUnit; + +import org.jclouds.abiquo.domain.config.options.LicenseOptions; +import org.jclouds.abiquo.domain.config.options.PropertyOptions; +import org.jclouds.abiquo.reference.annotations.EnterpriseEdition; +import org.jclouds.concurrent.Timeout; + +import com.abiquo.server.core.appslibrary.CategoriesDto; +import com.abiquo.server.core.appslibrary.CategoryDto; +import com.abiquo.server.core.config.LicenseDto; +import com.abiquo.server.core.config.LicensesDto; +import com.abiquo.server.core.config.SystemPropertiesDto; +import com.abiquo.server.core.config.SystemPropertyDto; +import com.abiquo.server.core.enterprise.PrivilegeDto; +import com.abiquo.server.core.enterprise.PrivilegesDto; + +/** + * Provides synchronous access to Abiquo Admin API. + * + * @see API: + * http://community.abiquo.com/display/ABI20/API+Reference + * @see ConfigAsyncApi + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +@Timeout(duration = 30, timeUnit = TimeUnit.SECONDS) +public interface ConfigApi { + /*********************** License ***********************/ + + /** + * List all licenses. + * + * @return The list of licenses. + */ + @EnterpriseEdition + LicensesDto listLicenses(); + + /** + * List all active/inactive licenses. + * + * @param options + * Optional query params. + * @return The list of licenses. + */ + @EnterpriseEdition + LicensesDto listLicenses(LicenseOptions options); + + /** + * Add a new license. + * + * @param license + * The license to add. + * @return The added license. + */ + @EnterpriseEdition + LicenseDto addLicense(LicenseDto license); + + /** + * Removes an existing license. + * + * @param license + * The license to delete. + */ + @EnterpriseEdition + void removeLicense(LicenseDto license); + + /*********************** Privilege ***********************/ + + /** + * List all privileges in the system. + * + * @return The list of privileges. + */ + PrivilegesDto listPrivileges(); + + /** + * Get the given privilege. + * + * @param privilegeId + * The id of the privilege. + * @return The privilege or null if it does not exist. + */ + PrivilegeDto getPrivilege(Integer privilegeId); + + /*********************** System Properties ***********************/ + + /** + * List all system properties. + * + * @return The list of properties. + */ + SystemPropertiesDto listSystemProperties(); + + /** + * List properties with options. + * + * @param options + * Optional query params. + * @return The list of system properties. + */ + SystemPropertiesDto listSystemProperties(PropertyOptions options); + + /** + * Updates a system property. + * + * @param property + * The new attributes for the system property. + * @return The updated system property. + */ + SystemPropertyDto updateSystemProperty(SystemPropertyDto property); + + /*********************** Category ***********************/ + + /** + * List all categories. + * + * @return The list of categories. + */ + CategoriesDto listCategories(); + + /** + * Get the given category. + * + * @param categoryId + * The id of the category. + * @return The category or null if it does not exist. + */ + CategoryDto getCategory(Integer categoryId); + + /** + * Create a new category. + * + * @param icon + * The category to be created. + * @return The created category. + */ + CategoryDto createCategory(CategoryDto category); + + /** + * Updates an existing category. + * + * @param category + * The new attributes for the category. + * @return The updated category. + */ + CategoryDto updateCategory(CategoryDto category); + + /** + * Deletes an existing category. + * + * @param icon + * The category to delete. + */ + void deleteCategory(CategoryDto category); +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/features/ConfigAsyncApi.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/features/ConfigAsyncApi.java new file mode 100644 index 0000000000..eeacd4a3a9 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/features/ConfigAsyncApi.java @@ -0,0 +1,207 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.features; + +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.abiquo.binders.BindToPath; +import org.jclouds.abiquo.binders.BindToXMLPayloadAndPath; +import org.jclouds.abiquo.domain.config.options.LicenseOptions; +import org.jclouds.abiquo.domain.config.options.PropertyOptions; +import org.jclouds.abiquo.http.filters.AbiquoAuthentication; +import org.jclouds.abiquo.http.filters.AppendApiVersionToMediaType; +import org.jclouds.abiquo.reference.annotations.EnterpriseEdition; +import org.jclouds.abiquo.rest.annotations.EndpointLink; +import org.jclouds.rest.annotations.BinderParam; +import org.jclouds.rest.annotations.ExceptionParser; +import org.jclouds.rest.annotations.JAXBResponseParser; +import org.jclouds.rest.annotations.RequestFilters; +import org.jclouds.rest.binders.BindToXMLPayload; +import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; + +import com.abiquo.server.core.appslibrary.CategoriesDto; +import com.abiquo.server.core.appslibrary.CategoryDto; +import com.abiquo.server.core.cloud.VirtualDatacenterDto; +import com.abiquo.server.core.config.LicenseDto; +import com.abiquo.server.core.config.LicensesDto; +import com.abiquo.server.core.config.SystemPropertiesDto; +import com.abiquo.server.core.config.SystemPropertyDto; +import com.abiquo.server.core.enterprise.PrivilegeDto; +import com.abiquo.server.core.enterprise.PrivilegesDto; +import com.google.common.util.concurrent.ListenableFuture; + +/** + * Provides asynchronous access to Abiquo Config API. + * + * @see API: + * http://community.abiquo.com/display/ABI20/API+Reference + * @see AdminApi + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +@RequestFilters({ AbiquoAuthentication.class, AppendApiVersionToMediaType.class }) +@Path("/config") +public interface ConfigAsyncApi { + /*********************** License ***********************/ + + /** + * @see ConfigApi#listLicenses() + */ + + @EnterpriseEdition + @GET + @Path("/licenses") + @Consumes(LicensesDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listLicenses(); + + /** + * @see ConfigApi#listLicenses(LicenseOptions) + */ + @EnterpriseEdition + @GET + @Path("/licenses") + @Consumes(LicensesDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listLicenses(LicenseOptions options); + + /** + * @see ConfigApi#addLicense(LicenseDto) + */ + @EnterpriseEdition + @POST + @Produces(LicenseDto.BASE_MEDIA_TYPE) + @Consumes(LicenseDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + @Path("/licenses") + ListenableFuture addLicense(@BinderParam(BindToXMLPayload.class) LicenseDto license); + + /** + * @see ConfigApi#removeLicense(LicenseDto) + */ + @DELETE + @EnterpriseEdition + ListenableFuture removeLicense(@EndpointLink("edit") @BinderParam(BindToPath.class) LicenseDto license); + + /*********************** Privilege ***********************/ + + /** + * @see ConfigApi#listPrivileges() + */ + @GET + @Path("/privileges") + @Consumes(PrivilegesDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listPrivileges(); + + /** + * @see ConfigApi#getPrivilege(Integer) + */ + @GET + @Path("/privileges/{privilege}") + @Consumes(PrivilegeDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + ListenableFuture getPrivilege(@PathParam("privilege") Integer privilegeId); + + /*********************** System Properties ***********************/ + + /** + * @see ConfigApi#listSystemProperties() + */ + @GET + @Path("/properties") + @Consumes(SystemPropertiesDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listSystemProperties(); + + /** + * @see ConfigApi#listSystemProperties(PropertyOptions) + */ + @GET + @Path("/properties") + @Consumes(SystemPropertiesDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listSystemProperties(PropertyOptions options); + + /** + * @see ConfigApi#updateSystemProperty(VirtualDatacenterDto) + */ + @PUT + @Produces(SystemPropertyDto.BASE_MEDIA_TYPE) + @Consumes(SystemPropertyDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture updateSystemProperty( + @EndpointLink("edit") @BinderParam(BindToXMLPayloadAndPath.class) SystemPropertyDto property); + + /*********************** Category ***********************/ + + /** + * @see ConfigApi#listCategories() + */ + @GET + @Path("/categories") + @Consumes(CategoriesDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listCategories(); + + /** + * @see ConfigApi#getCategory(Integer) + */ + @GET + @Path("/categories/{category}") + @Consumes(CategoryDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + ListenableFuture getCategory(@PathParam("category") Integer categoryId); + + /** + * @see ConfigApi#createCategory(CategoryDto) + */ + @POST + @Path("/categories") + @Produces(CategoryDto.BASE_MEDIA_TYPE) + @Consumes(CategoryDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture createCategory(@BinderParam(BindToXMLPayload.class) CategoryDto category); + + /** + * @see ConfigApi#updateCategory(CategoryDto) + */ + @PUT + @Produces(CategoryDto.BASE_MEDIA_TYPE) + @Consumes(CategoryDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture updateCategory( + @EndpointLink("edit") @BinderParam(BindToXMLPayloadAndPath.class) CategoryDto category); + + /** + * @see ConfigApi#deleteCategory(CategoryDto) + */ + @DELETE + ListenableFuture deleteCategory(@EndpointLink("edit") @BinderParam(BindToPath.class) CategoryDto category); +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/features/EnterpriseApi.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/features/EnterpriseApi.java new file mode 100644 index 0000000000..2cd716bd53 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/features/EnterpriseApi.java @@ -0,0 +1,403 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.features; + +import java.util.concurrent.TimeUnit; + +import org.jclouds.abiquo.domain.enterprise.options.EnterpriseOptions; +import org.jclouds.abiquo.reference.annotations.EnterpriseEdition; +import org.jclouds.concurrent.Timeout; + +import com.abiquo.am.model.TemplatesStateDto; +import com.abiquo.server.core.appslibrary.DatacenterRepositoryDto; +import com.abiquo.server.core.appslibrary.TemplateDefinitionListDto; +import com.abiquo.server.core.appslibrary.TemplateDefinitionListsDto; +import com.abiquo.server.core.cloud.VirtualAppliancesDto; +import com.abiquo.server.core.cloud.VirtualDatacentersDto; +import com.abiquo.server.core.cloud.VirtualMachinesWithNodeExtendedDto; +import com.abiquo.server.core.enterprise.DatacenterLimitsDto; +import com.abiquo.server.core.enterprise.DatacentersLimitsDto; +import com.abiquo.server.core.enterprise.EnterpriseDto; +import com.abiquo.server.core.enterprise.EnterprisePropertiesDto; +import com.abiquo.server.core.enterprise.EnterprisesDto; +import com.abiquo.server.core.enterprise.UserDto; +import com.abiquo.server.core.enterprise.UsersDto; +import com.abiquo.server.core.infrastructure.DatacenterDto; +import com.abiquo.server.core.infrastructure.DatacentersDto; +import com.abiquo.server.core.infrastructure.MachinesDto; +import com.abiquo.server.core.infrastructure.network.VLANNetworksDto; + +/** + * Provides synchronous access to Abiquo Enterprise API. + * + * @see API: + * http://community.abiquo.com/display/ABI20/API+Reference + * @see EnterpriseAsyncApi + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +@Timeout(duration = 30, timeUnit = TimeUnit.SECONDS) +public interface EnterpriseApi { + + /*********************** Enterprise ********************** */ + + /** + * List all enterprises. + * + * @return The list of Enterprises. + */ + EnterprisesDto listEnterprises(); + + /** + * List enterprises with options. + * + * @param options + * Filtering options. + * @return The list of Enterprises. + */ + EnterprisesDto listEnterprises(EnterpriseOptions options); + + /** + * List filtered enterprises by datacenter. + * + * @param datacenter + * The given datacenter. + * @param options + * Filtering options. + * @return The list of Enterprises. + */ + EnterprisesDto listEnterprises(DatacenterDto datacenter, EnterpriseOptions options); + + /** + * Create a new enterprise. + * + * @param enterprise + * The enterprise to be created. + * @return The created enterprise. + */ + EnterpriseDto createEnterprise(EnterpriseDto enterprise); + + /** + * Get the given enterprise. + * + * @param enterpriseId + * The id of the enterprise. + * @return The enterprise or null if it does not exist. + */ + EnterpriseDto getEnterprise(Integer enterpriseId); + + /** + * Updates an existing enterprise. + * + * @param enterprise + * The new attributes for the enterprise. + * @return The updated enterprise. + */ + EnterpriseDto updateEnterprise(EnterpriseDto enterprise); + + /** + * Deletes an existing enterprise. + * + * @param enterprise + * The enterprise to delete. + */ + void deleteEnterprise(EnterpriseDto enterprise); + + /** + * List the allowed datacenters to the given enterprise. + * + * @param enterpriseId + * The id of the enterprise. + * @return The allowed datacenters to the given enterprise. + */ + DatacentersDto listAllowedDatacenters(Integer enterpriseId); + + /** + * List all virtual datacenters of an enterprise. + * + * @param enterprise + * The given enterprise. + * @return The list of Datacenters. + */ + VirtualDatacentersDto listVirtualDatacenters(EnterpriseDto enterprise); + + /*********************** Enterprise Properties ***********************/ + + /** + * Get defined properties of the given enterprise. + * + * @param enterpriseId + * The enterprise id. + * @return Set of enterprise properties. + */ + @EnterpriseEdition + EnterprisePropertiesDto getEnterpriseProperties(EnterpriseDto enterprise); + + /** + * Updates the given enterprise properties set. + * + * @param properties + * The properties set. + * @return The updated properties. + */ + @EnterpriseEdition + EnterprisePropertiesDto updateEnterpriseProperties(EnterprisePropertiesDto properties); + + /*********************** Enterprise Limits ***********************/ + + /** + * Allows the given enterprise to use the given datacenter with the given + * limits. + * + * @param enterprise + * The enterprise. + * @param datacenter + * The datacenter to allow to the given enterprise. + * @param limits + * The usage limits for the enterprise in the given datacenter. + * @return The usage limits for the enterprise in the given datacenter. + */ + DatacenterLimitsDto createLimits(final EnterpriseDto enterprise, final DatacenterDto datacenter, + final DatacenterLimitsDto limits); + + /** + * Retreives the limits for the given enterprise and datacenter. + * + * @param enterprise + * The enterprise. + * @param datacenter + * The datacenter. + * @return The usage limits for the enterprise in the given datacenter. + */ + DatacentersLimitsDto getLimits(EnterpriseDto enterprise, DatacenterDto datacenter); + + /** + * Retreives limits for the given enterprise and any datacenter. + * + * @param enterprise + * The enterprise. + * @return The usage limits for the enterprise on any datacenter. + */ + DatacentersLimitsDto listLimits(EnterpriseDto enterprise); + + /** + * Updates an existing enterprise-datacenter limits. + * + * @param limits + * The new set of limits. + * @return The updated limits. + */ + DatacenterLimitsDto updateLimits(DatacenterLimitsDto limits); + + /** + * Deletes existing limits for a pair enterprise-datacenter. + * + * @param limits + * The limits to delete. + */ + void deleteLimits(DatacenterLimitsDto limits); + + /*********************** User ********************** */ + + /** + * Retreives users of the given enterprise. + * + * @param enterprise + * The enterprise. + * @return The users of the enterprise. + */ + UsersDto listUsers(final EnterpriseDto enterprise); + + /** + * Create a new user in the given enterprise. + * + * @param enterprise + * The enterprise. + * @param user + * The user to be created. + * @return The created user. + */ + UserDto createUser(EnterpriseDto enterprise, UserDto user); + + /** + * Get the given user from the given enterprise. + * + * @param enterprise + * The enterprise. + * @param userId + * The id of the user. + * @return The user or null if it does not exist. + */ + UserDto getUser(final EnterpriseDto enterprise, final Integer idUser); + + /** + * Updates an existing user. + * + * @param enterprise + * The new attributes for the user. + * @return The updated user. + */ + UserDto updateUser(UserDto user); + + /** + * Deletes existing user. + * + * @param user + * The user to delete. + */ + void deleteUser(UserDto user); + + /** + * Retrieves list of virtual machines by user. + * + * @param user + * The user. + * @return The list of virtual machines of the user. + */ + VirtualMachinesWithNodeExtendedDto listVirtualMachines(final UserDto user); + + /*********************** Datacenter Repository ***********************/ + + /** + * Get the given datacenter repository from the given enterprise. + * + * @param enterprise + * The enterprise. + * @param datacenterRepositoryId + * The id of the datacenter repository. + * @return The datacenter repository or null if it does not + * exist. + */ + DatacenterRepositoryDto getDatacenterRepository(final EnterpriseDto enterprise, final Integer datacenterRepositoryId); + + /** + * Refreshes database with virtual machine templates existing in the + * repository filesystem. + * + * @param enterpriseId + * Id of the enterprise which information will be refreshed. + * @param datacenterRepositoryId + * Id of the datacenter repository contaning the templates. + */ + @Timeout(duration = 60, timeUnit = TimeUnit.SECONDS) + void refreshTemplateRepository(Integer enterpriseId, Integer datacenterRepositoryId); + + /*********************** Network ***********************/ + + /** + * List external networks of the enterprise + * + * @param enterprise + * The enterprise. + * @return The list of external networks created and assigned. + */ + @EnterpriseEdition + VLANNetworksDto listExternalNetworks(EnterpriseDto enterprise); + + /*********************** Cloud ***********************/ + + /** + * Retrieves list of virtual appliances by the given enterprise. + * + * @param enterprise + * The enterprise. + * @return The list of virtual appliances of the enterprise. + */ + VirtualAppliancesDto listVirtualAppliances(EnterpriseDto enterprise); + + /** + * List virtual machines for the enterprise + * + * @param enterprise + * The enterprise. + * @return The list of virtual machines by the enterprise. + */ + VirtualMachinesWithNodeExtendedDto listVirtualMachines(EnterpriseDto enterprise); + + /** + * List reserved machines for the enterprise + * + * @param enterprise + * The enterprise. + * @return The list of reserverd machines by the enterprise. + */ + MachinesDto listReservedMachines(EnterpriseDto enterprise); + + /** + * List all template definitions in apps library. + * + * @param enterprise + * The enterprise. + * @return The list of template definitions by the enterprise. + */ + TemplateDefinitionListsDto listTemplateDefinitionLists(EnterpriseDto enterprise); + + /** + * Create a new template definition list in apps library in the given + * enterprise. + * + * @param enterprise + * The enterprise. + * @param template + * The template to be created. + * @return The created template. + */ + TemplateDefinitionListDto createTemplateDefinitionList(EnterpriseDto enterprise, + TemplateDefinitionListDto templateList); + + /** + * Update an existing template definition list in apps library. + * + * @param template + * The template to be update. + * @return The updated template. + */ + TemplateDefinitionListDto updateTemplateDefinitionList(TemplateDefinitionListDto templateList); + + /** + * Deletes existing user. + * + * @param user + * The user to delete. + */ + void deleteTemplateDefinitionList(TemplateDefinitionListDto templateList); + + /** + * Get the given template definition list from the given enterprise. + * + * @param enterprise + * The enterprise. + * @param templateListId + * The id of the template definition list. + * @return The list or null if it does not exist. + */ + TemplateDefinitionListDto getTemplateDefinitionList(final EnterpriseDto enterprise, final Integer templateListId); + + /** + * Get the list of status of a template definition list in a datacenter. + * + * @param templateList + * The template definition list. + * @param datacenter + * The given datacenter. + * @return The list of states. + */ + TemplatesStateDto listTemplateListStatus(TemplateDefinitionListDto templateList, DatacenterDto datacenter); +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/features/EnterpriseAsyncApi.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/features/EnterpriseAsyncApi.java new file mode 100644 index 0000000000..c77af99c0a --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/features/EnterpriseAsyncApi.java @@ -0,0 +1,416 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.features; + +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 javax.ws.rs.QueryParam; + +import org.jclouds.abiquo.binders.AppendToPath; +import org.jclouds.abiquo.binders.BindToPath; +import org.jclouds.abiquo.binders.BindToXMLPayloadAndPath; +import org.jclouds.abiquo.domain.enterprise.options.EnterpriseOptions; +import org.jclouds.abiquo.functions.infrastructure.ParseDatacenterId; +import org.jclouds.abiquo.http.filters.AbiquoAuthentication; +import org.jclouds.abiquo.http.filters.AppendApiVersionToMediaType; +import org.jclouds.abiquo.reference.annotations.EnterpriseEdition; +import org.jclouds.abiquo.rest.annotations.EndpointLink; +import org.jclouds.rest.annotations.BinderParam; +import org.jclouds.rest.annotations.ExceptionParser; +import org.jclouds.rest.annotations.JAXBResponseParser; +import org.jclouds.rest.annotations.ParamParser; +import org.jclouds.rest.annotations.RequestFilters; +import org.jclouds.rest.binders.BindToXMLPayload; +import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; + +import com.abiquo.am.model.TemplatesStateDto; +import com.abiquo.server.core.appslibrary.DatacenterRepositoryDto; +import com.abiquo.server.core.appslibrary.TemplateDefinitionListDto; +import com.abiquo.server.core.appslibrary.TemplateDefinitionListsDto; +import com.abiquo.server.core.cloud.VirtualAppliancesDto; +import com.abiquo.server.core.cloud.VirtualDatacentersDto; +import com.abiquo.server.core.cloud.VirtualMachinesWithNodeExtendedDto; +import com.abiquo.server.core.enterprise.DatacenterLimitsDto; +import com.abiquo.server.core.enterprise.DatacentersLimitsDto; +import com.abiquo.server.core.enterprise.EnterpriseDto; +import com.abiquo.server.core.enterprise.EnterprisePropertiesDto; +import com.abiquo.server.core.enterprise.EnterprisesDto; +import com.abiquo.server.core.enterprise.UserDto; +import com.abiquo.server.core.enterprise.UsersDto; +import com.abiquo.server.core.infrastructure.DatacenterDto; +import com.abiquo.server.core.infrastructure.DatacentersDto; +import com.abiquo.server.core.infrastructure.MachinesDto; +import com.abiquo.server.core.infrastructure.network.VLANNetworksDto; +import com.google.common.util.concurrent.ListenableFuture; + +/** + * Provides asynchronous access to Abiquo Enterprise API. + * + * @see API: + * http://community.abiquo.com/display/ABI20/API+Reference + * @see EnterpriseApi + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +@RequestFilters({ AbiquoAuthentication.class, AppendApiVersionToMediaType.class }) +@Path("/admin") +public interface EnterpriseAsyncApi { + /*********************** Enterprise ***********************/ + + /** + * @see EnterpriseApi#listEnterprises() + */ + @GET + @Path("/enterprises") + @Consumes(EnterprisesDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listEnterprises(); + + /** + * @see EnterpriseApi#listEnterprises(EnterpriseOptions) + */ + @GET + @Path("/enterprises") + @Consumes(EnterprisesDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listEnterprises(EnterpriseOptions options); + + /** + * @see EnterpriseApi#listEnterprises(DatacenterDto, EnterpriseOptions) + */ + @GET + @Consumes(EnterprisesDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listEnterprises( + @EndpointLink("enterprises") @BinderParam(BindToPath.class) DatacenterDto datacenter, EnterpriseOptions options); + + /** + * @see EnterpriseApi#createEnterprise(EnterpriseDto) + */ + @POST + @Path("/enterprises") + @Produces(EnterpriseDto.BASE_MEDIA_TYPE) + @Consumes(EnterpriseDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture createEnterprise(@BinderParam(BindToXMLPayload.class) EnterpriseDto enterprise); + + /** + * @see EnterpriseApi#getEnterprise(Integer) + */ + @GET + @Path("/enterprises/{enterprise}") + @Consumes(EnterpriseDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + ListenableFuture getEnterprise(@PathParam("enterprise") Integer enterpriseId); + + /** + * @see EnterpriseApi#updateEnterprise(EnterpriseDto) + */ + @PUT + @Produces(EnterpriseDto.BASE_MEDIA_TYPE) + @Consumes(EnterpriseDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture updateEnterprise( + @EndpointLink("edit") @BinderParam(BindToXMLPayloadAndPath.class) EnterpriseDto enterprise); + + /** + * @see EnterpriseApi#deleteEnterprise(EnterpriseDto) + */ + @DELETE + ListenableFuture deleteEnterprise(@EndpointLink("edit") @BinderParam(BindToPath.class) EnterpriseDto enterprise); + + /** + * @see EnterpriseApi#listAllowedDatacenters(Integer) + */ + @GET + @Path("/datacenters") + @Consumes(DatacentersDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listAllowedDatacenters(@QueryParam("idEnterprise") Integer enterpriseId); + + /** + * @see EnterpriseApi#listVirtualDatacenters(EnterpriseDto) + */ + @GET + @Consumes(VirtualDatacentersDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listVirtualDatacenters( + @EndpointLink("cloud/virtualdatacenters") @BinderParam(BindToPath.class) EnterpriseDto enterprise); + + /*********************** Enterprise Properties ***********************/ + + /** + * @see EnterpriseApi#getEnterpriseProperties(EnterpriseDto) + */ + @EnterpriseEdition + @GET + @Consumes(EnterprisePropertiesDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture getEnterpriseProperties( + @EndpointLink("properties") @BinderParam(BindToPath.class) EnterpriseDto enterprise); + + /** + * @see EnterpriseApi#updateEnterpriseProperties(EnterprisePropertiesDto) + */ + @EnterpriseEdition + @PUT + @Produces(EnterprisePropertiesDto.BASE_MEDIA_TYPE) + @Consumes(EnterprisePropertiesDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture updateEnterpriseProperties( + @EndpointLink("edit") @BinderParam(BindToXMLPayloadAndPath.class) EnterprisePropertiesDto properties); + + /*********************** Enterprise Limits ***********************/ + + /** + * @see EnterpriseApi#createLimits(EnterpriseDto, DatacenterDto, + * DatacenterLimitsDto) + */ + @POST + @Produces(DatacenterLimitsDto.BASE_MEDIA_TYPE) + @Consumes(DatacenterLimitsDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture createLimits( + @EndpointLink("limits") @BinderParam(BindToPath.class) final EnterpriseDto enterprise, + @QueryParam("datacenter") @ParamParser(ParseDatacenterId.class) final DatacenterDto datacenter, + @BinderParam(BindToXMLPayload.class) DatacenterLimitsDto limits); + + /** + * @see EnterpriseApi#getLimits(EnterpriseDto, DatacenterDto) + */ + @GET + @Consumes(DatacentersLimitsDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + ListenableFuture getLimits( + @EndpointLink("limits") @BinderParam(BindToPath.class) final EnterpriseDto enterprise, + @QueryParam("datacenter") @ParamParser(ParseDatacenterId.class) final DatacenterDto datacenter); + + /** + * @see EnterpriseApi#updateLimits(DatacenterLimitsDto) + */ + @PUT + @Produces(DatacenterLimitsDto.BASE_MEDIA_TYPE) + @Consumes(DatacenterLimitsDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture updateLimits( + @EndpointLink("edit") @BinderParam(BindToXMLPayloadAndPath.class) DatacenterLimitsDto limits); + + /** + * @see EnterpriseApi#deleteLimits(DatacenterLimitsDto) + */ + @DELETE + ListenableFuture deleteLimits(@EndpointLink("edit") @BinderParam(BindToPath.class) DatacenterLimitsDto limits); + + /** + * @see EnterpriseApi#listLimits(EnterpriseDto) + */ + @GET + @Consumes(DatacentersLimitsDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listLimits( + @EndpointLink("limits") @BinderParam(BindToPath.class) EnterpriseDto enterprise); + + /*********************** User ***********************/ + + /** + * @see EnterpriseApi#listUsers(EnterpriseDto) + */ + @GET + @Consumes(UsersDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listUsers(@EndpointLink("users") @BinderParam(BindToPath.class) EnterpriseDto enterprise); + + /** + * @see EnterpriseApi#getUser(EnterpriseDto, Integer) + */ + @GET + @Consumes(UserDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + ListenableFuture getUser(@EndpointLink("users") @BinderParam(BindToPath.class) EnterpriseDto enterprise, + @BinderParam(AppendToPath.class) Integer userId); + + /** + * @see EnterpriseApi#createUser(EnterpriseDto) + */ + @POST + @Produces(UserDto.BASE_MEDIA_TYPE) + @Consumes(UserDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture createUser(@EndpointLink("users") @BinderParam(BindToPath.class) EnterpriseDto enterprise, + @BinderParam(BindToXMLPayload.class) UserDto user); + + /** + * @see EnterpriseApi#updateUser(UserDto) + */ + @PUT + @Produces(UserDto.BASE_MEDIA_TYPE) + @Consumes(UserDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture updateUser(@EndpointLink("edit") @BinderParam(BindToXMLPayloadAndPath.class) UserDto user); + + /** + * @see EnterpriseApi#deleteUser(UserDto) + */ + @DELETE + ListenableFuture deleteUser(@EndpointLink("edit") @BinderParam(BindToPath.class) UserDto user); + + /** + * @see EnterpriseApi#listVirtualMachines(UserDto) + */ + @GET + @Consumes(VirtualMachinesWithNodeExtendedDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listVirtualMachines( + @EndpointLink("virtualmachines") @BinderParam(BindToPath.class) final UserDto user); + + /*********************** Datacenter Repository ***********************/ + + /** + * @see EnterpriseApi#getDatacenterRepository(EnterpriseDto, Integer) + */ + @GET + @Consumes(DatacenterRepositoryDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + ListenableFuture getDatacenterRepository( + @EndpointLink("datacenterrepositories") @BinderParam(BindToPath.class) EnterpriseDto enterprise, + @BinderParam(AppendToPath.class) Integer datacenterRepositoryId); + + /** + * @see EnterpriseApi#refreshTemplateRepository(Integer, Integer) + */ + @PUT + @Path("/enterprises/{enterprise}/datacenterrepositories/{datacenterrepository}/actions/refresh") + ListenableFuture refreshTemplateRepository(@PathParam("enterprise") Integer enterpriseId, + @PathParam("datacenterrepository") Integer datacenterRepositoryId); + + /*********************** External Network ***********************/ + + /** + * @see EnterpriseApi#listExternalNetworks(EnterpriseDto) + */ + @EnterpriseEdition + @GET + @Consumes(VLANNetworksDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listExternalNetworks( + @EndpointLink("externalnetworks") @BinderParam(BindToPath.class) EnterpriseDto enterprise); + + /*********************** Cloud ***********************/ + + /** + * @see EnterpriseApi#listVirtualAppliances(EnterpriseDto) + */ + @GET + @Consumes(VirtualAppliancesDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listVirtualAppliances( + @EndpointLink("virtualappliances") @BinderParam(BindToPath.class) final EnterpriseDto enterprise); + + /** + * @see EnterpriseApi#listVirtualMachines(EnterpriseDto) + */ + @GET + @Consumes(VirtualMachinesWithNodeExtendedDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listVirtualMachines( + @EndpointLink("virtualmachines") @BinderParam(BindToPath.class) EnterpriseDto enterprise); + + /*********************** Machine ***********************/ + + /** + * @see EnterpriseApi#listVirtualMachines(EnterpriseDto) + */ + @GET + @Consumes(MachinesDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listReservedMachines( + @EndpointLink("reservedmachines") @BinderParam(BindToPath.class) EnterpriseDto enterprise); + + /*********************** Template definition list ***********************/ + + /** + * @see EnterpriseApi#listTemplateDefinitionLists(EnterpriseDto) + */ + @GET + @Consumes(TemplateDefinitionListsDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listTemplateDefinitionLists( + @EndpointLink("appslib/templateDefinitionLists") @BinderParam(BindToPath.class) EnterpriseDto enterprise); + + /** + * @see EnterpriseApi#createTemplateDefinitionList(EnterpriseDto, + * TemplateDefinitionListDto) + */ + @POST + @Produces(TemplateDefinitionListDto.BASE_MEDIA_TYPE) + @Consumes(TemplateDefinitionListDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture createTemplateDefinitionList( + @EndpointLink("appslib/templateDefinitionLists") @BinderParam(BindToPath.class) EnterpriseDto enterprise, + @BinderParam(BindToXMLPayload.class) TemplateDefinitionListDto templateList); + + /** + * @see EnterpriseApi#updateTemplateDefinitionList(TemplateDefinitionListDto) + */ + @PUT + @Produces(TemplateDefinitionListDto.BASE_MEDIA_TYPE) + @Consumes(TemplateDefinitionListDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture updateTemplateDefinitionList( + @EndpointLink("edit") @BinderParam(BindToXMLPayloadAndPath.class) TemplateDefinitionListDto templateList); + + /** + * @see EnterpriseApi#deleteTemplateDefinitionList(EnterpriseDto) + */ + @DELETE + ListenableFuture deleteTemplateDefinitionList( + @EndpointLink("edit") @BinderParam(BindToPath.class) TemplateDefinitionListDto templateList); + + /** + * @see EnterpriseApi#getTemplateDefinitionList(EnterpriseDto, Integer) + */ + @GET + @Consumes(TemplateDefinitionListDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + ListenableFuture getTemplateDefinitionList( + @EndpointLink("appslib/templateDefinitionLists") @BinderParam(BindToPath.class) EnterpriseDto enterprise, + @BinderParam(AppendToPath.class) Integer templateListId); + + /** + * @see EnterpriseApi#getTemplateDefinitionList(EnterpriseDto, Integer) + */ + @GET + @Consumes(TemplatesStateDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listTemplateListStatus( + @EndpointLink("repositoryStatus") @BinderParam(BindToPath.class) TemplateDefinitionListDto templateList, + @QueryParam("datacenterId") @ParamParser(ParseDatacenterId.class) DatacenterDto datacenter); +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/features/EventApi.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/features/EventApi.java new file mode 100644 index 0000000000..b6730af9fa --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/features/EventApi.java @@ -0,0 +1,53 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.features; + +import java.util.concurrent.TimeUnit; + +import org.jclouds.abiquo.domain.event.options.EventOptions; +import org.jclouds.concurrent.Timeout; + +import com.abiquo.server.core.event.EventsDto; + +/** + * Provides synchronous access to Abiquo Event API. + * + * @see API: + * http://community.abiquo.com/display/ABI20/API+Reference + * @see EventAsyncApi + * @author Ignasi Barrera + * @author Vivien Mahé + */ +@Timeout(duration = 30, timeUnit = TimeUnit.SECONDS) +public interface EventApi { + /** + * List events. + * + * @return The list of events. + */ + EventsDto listEvents(); + + /** + * List events using filters. + * + * @return The list of events using filters. + */ + EventsDto listEvents(EventOptions options); +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/features/EventAsyncApi.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/features/EventAsyncApi.java new file mode 100644 index 0000000000..5bdbc926f3 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/features/EventAsyncApi.java @@ -0,0 +1,63 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.features; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.Path; + +import org.jclouds.abiquo.domain.event.options.EventOptions; +import org.jclouds.abiquo.http.filters.AbiquoAuthentication; +import org.jclouds.abiquo.http.filters.AppendApiVersionToMediaType; +import org.jclouds.rest.annotations.JAXBResponseParser; +import org.jclouds.rest.annotations.RequestFilters; + +import com.abiquo.server.core.event.EventsDto; +import com.google.common.util.concurrent.ListenableFuture; + +/** + * Provides asynchronous access to Abiquo Event API. + * + * @see API: + * http://community.abiquo.com/display/ABI20/API+Reference + * @see EventApi + * @author Ignasi Barrera + * @author Vivien Mahé + */ +@RequestFilters({ AbiquoAuthentication.class, AppendApiVersionToMediaType.class }) +public interface EventAsyncApi { + /** + * @see EventApi#listEvents() + */ + @GET + @Path("/events") + @Consumes(EventsDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listEvents(); + + /** + * @see EventApi#listEvents() + */ + @GET + @Path("/events") + @Consumes(EventsDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listEvents(EventOptions options); +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/features/InfrastructureApi.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/features/InfrastructureApi.java new file mode 100644 index 0000000000..8ea854abb2 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/features/InfrastructureApi.java @@ -0,0 +1,1208 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.features; + +import java.util.concurrent.TimeUnit; + +import org.jclouds.abiquo.domain.infrastructure.options.DatacenterOptions; +import org.jclouds.abiquo.domain.infrastructure.options.IpmiOptions; +import org.jclouds.abiquo.domain.infrastructure.options.MachineOptions; +import org.jclouds.abiquo.domain.infrastructure.options.StoragePoolOptions; +import org.jclouds.abiquo.domain.network.options.IpOptions; +import org.jclouds.abiquo.domain.network.options.NetworkOptions; +import org.jclouds.abiquo.domain.options.search.FilterOptions; +import org.jclouds.abiquo.reference.annotations.EnterpriseEdition; +import org.jclouds.concurrent.Timeout; + +import com.abiquo.model.enumerator.HypervisorType; +import com.abiquo.model.enumerator.RemoteServiceType; +import com.abiquo.server.core.cloud.HypervisorTypesDto; +import com.abiquo.server.core.cloud.VirtualMachineWithNodeExtendedDto; +import com.abiquo.server.core.cloud.VirtualMachinesWithNodeExtendedDto; +import com.abiquo.server.core.enterprise.DatacentersLimitsDto; +import com.abiquo.server.core.enterprise.EnterpriseDto; +import com.abiquo.server.core.infrastructure.BladeLocatorLedDto; +import com.abiquo.server.core.infrastructure.DatacenterDto; +import com.abiquo.server.core.infrastructure.DatacentersDto; +import com.abiquo.server.core.infrastructure.FsmsDto; +import com.abiquo.server.core.infrastructure.LogicServerDto; +import com.abiquo.server.core.infrastructure.LogicServersDto; +import com.abiquo.server.core.infrastructure.MachineDto; +import com.abiquo.server.core.infrastructure.MachineIpmiStateDto; +import com.abiquo.server.core.infrastructure.MachineStateDto; +import com.abiquo.server.core.infrastructure.MachinesDto; +import com.abiquo.server.core.infrastructure.OrganizationDto; +import com.abiquo.server.core.infrastructure.OrganizationsDto; +import com.abiquo.server.core.infrastructure.RackDto; +import com.abiquo.server.core.infrastructure.RacksDto; +import com.abiquo.server.core.infrastructure.RemoteServiceDto; +import com.abiquo.server.core.infrastructure.RemoteServicesDto; +import com.abiquo.server.core.infrastructure.UcsRackDto; +import com.abiquo.server.core.infrastructure.UcsRacksDto; +import com.abiquo.server.core.infrastructure.network.ExternalIpDto; +import com.abiquo.server.core.infrastructure.network.ExternalIpsDto; +import com.abiquo.server.core.infrastructure.network.PublicIpDto; +import com.abiquo.server.core.infrastructure.network.PublicIpsDto; +import com.abiquo.server.core.infrastructure.network.UnmanagedIpDto; +import com.abiquo.server.core.infrastructure.network.UnmanagedIpsDto; +import com.abiquo.server.core.infrastructure.network.VLANNetworkDto; +import com.abiquo.server.core.infrastructure.network.VLANNetworksDto; +import com.abiquo.server.core.infrastructure.network.VlanTagAvailabilityDto; +import com.abiquo.server.core.infrastructure.storage.StorageDeviceDto; +import com.abiquo.server.core.infrastructure.storage.StorageDevicesDto; +import com.abiquo.server.core.infrastructure.storage.StorageDevicesMetadataDto; +import com.abiquo.server.core.infrastructure.storage.StoragePoolDto; +import com.abiquo.server.core.infrastructure.storage.StoragePoolsDto; +import com.abiquo.server.core.infrastructure.storage.TierDto; +import com.abiquo.server.core.infrastructure.storage.TiersDto; + +/** + * Provides synchronous access to Abiquo Infrastructure API. + * + * @see API: + * http://community.abiquo.com/display/ABI20/API+Reference + * @see InfrastructureAsyncApi + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +@Timeout(duration = 30, timeUnit = TimeUnit.SECONDS) +public interface InfrastructureApi { + /*********************** Datacenter ***********************/ + + /** + * List all datacenters. + * + * @return The list of Datacenters. + */ + DatacentersDto listDatacenters(); + + /** + * Create a new datacenter. + * + * @param datacenter + * The datacenter to be created. + * @return The created datacenter. + */ + DatacenterDto createDatacenter(DatacenterDto datacenter); + + /** + * Get the given datacenter. + * + * @param datacenterId + * The id of the datacenter. + * @return The datacenter or null if it does not exist. + */ + DatacenterDto getDatacenter(Integer datacenterId); + + /** + * Updates an existing datacenter. + * + * @param datacenter + * The new attributes for the datacenter. + * @return The updated datacenter. + */ + DatacenterDto updateDatacenter(DatacenterDto datacenter); + + /** + * Deletes an existing datacenter. + * + * @param datacenter + * The datacenter to delete. + */ + void deleteDatacenter(DatacenterDto datacenter); + + /** + * Retrieve remote machine information. + * + * @see API: http://community.abiquo.com/display/ABI20/DatacenterResource# + * DatacenterResource- Retrieveremotemachineinformation + * @param datacenter + * The datacenter. + * @param ip + * IP address of the remote hypervisor to connect. + * @param hypervisorType + * Kind of hypervisor we want to connect. Valid values are {vbox, + * kvm, xen-3, vmx-04, hyperv-301, xenserver}. + * @param user + * User to log in. + * @param password + * Password to authenticate. + * @return The physical machine. + */ + @Timeout(duration = 90, timeUnit = TimeUnit.SECONDS) + MachineDto discoverSingleMachine(DatacenterDto datacenter, String ip, HypervisorType hypervisorType, String user, + String password); + + /** + * Retrieve remote machine information. + * + * @see API: http://community.abiquo.com/display/ABI20/DatacenterResource# + * DatacenterResource- Retrieveremotemachineinformation + * @param datacenter + * The datacenter. + * @param ip + * IP address of the remote hypervisor to connect. + * @param hypervisorType + * Kind of hypervisor we want to connect. Valid values are {vbox, + * kvm, xen-3, vmx-04, hyperv-301, xenserver}. + * @param user + * User to log in. + * @param password + * Password to authenticate. + * @param options + * Optional query params. + * @return The physical machine. + */ + @Timeout(duration = 90, timeUnit = TimeUnit.SECONDS) + MachineDto discoverSingleMachine(DatacenterDto datacenter, String ip, HypervisorType hypervisorType, String user, + String password, MachineOptions options); + + /** + * Retrieve a list of remote machine information. + * + * @see API: http://community.abiquo.com/display/ABI20/DatacenterResource# + * DatacenterResource- Retrievealistofremotemachineinformation + * @param datacenter + * The datacenter. + * @param ipFrom + * IP address of the remote first hypervisor to check. + * @param ipTo + * IP address of the remote last hypervisor to check. + * @param hypervisorType + * Kind of hypervisor we want to connect. Valid values are {vbox, + * kvm, xen-3, vmx-04, hyperv-301, xenserver}. + * @param user + * User to log in. + * @param password + * Password to authenticate. + * @return The physical machine list. + */ + @Timeout(duration = 90, timeUnit = TimeUnit.SECONDS) + MachinesDto discoverMultipleMachines(final DatacenterDto datacenter, final String ipFrom, final String ipTo, + final HypervisorType hypervisorType, final String user, final String password); + + /** + * Retrieve a list of remote machine information. + * + * @see API: http://community.abiquo.com/display/ABI20/DatacenterResource# + * DatacenterResource- Retrievealistofremotemachineinformation + * @param datacenter + * The datacenter. + * @param ipFrom + * IP address of the remote first hypervisor to check. + * @param ipTo + * IP address of the remote last hypervisor to check. + * @param hypervisorType + * Kind of hypervisor we want to connect. Valid values are {vbox, + * kvm, xen-3, vmx-04, hyperv-301, xenserver}. + * @param user + * User to log in. + * @param password + * Password to authenticate. + * @param options + * Optional query params. + * @return The physical machine list. + */ + @Timeout(duration = 90, timeUnit = TimeUnit.SECONDS) + MachinesDto discoverMultipleMachines(final DatacenterDto datacenter, final String ipFrom, final String ipTo, + final HypervisorType hypervisorType, final String user, final String password, final MachineOptions options); + + /** + * Retreives limits for the given datacenter and any enterprise. + * + * @param datacenter + * The datacenter. + * @return The usage limits for the datacenter on any enterprise. + */ + DatacentersLimitsDto listLimits(DatacenterDto datacenter); + + /** + * Check the state of a remote machine. This machine does not need to be + * managed by Abiquo. + * + * @param datacenter + * The datacenter. + * @param ip + * IP address of the remote hypervisor to connect. + * @param hypervisorType + * Kind of hypervisor we want to connect. Valid values are {vbox, + * kvm, xen-3, vmx-04, hyperv-301, xenserver}. + * @param user + * User to log in. + * @param password + * Password to authenticate. + * @return The physical machine state information. + */ + MachineStateDto checkMachineState(DatacenterDto datacenter, String ip, HypervisorType hypervisorType, String user, + String password); + + /** + * Check the state of a remote machine. This machine does not need to be + * managed by Abiquo. + * + * @param datacenter + * The datacenter. + * @param ip + * IP address of the remote hypervisor to connect. + * @param hypervisorType + * Kind of hypervisor we want to connect. Valid values are {vbox, + * kvm, xen-3, vmx-04, hyperv-301, xenserver}. + * @param user + * User to log in. + * @param password + * Password to authenticate. + * @param options + * Optional query params. + * @return The physical machine state information. + */ + MachineStateDto checkMachineState(DatacenterDto datacenter, String ip, HypervisorType hypervisorType, String user, + String password, MachineOptions options); + + /** + * Check the ipmi configuration state of a remote machine. This machine does + * not need to be managed by Abiquo. + * + * @param datacenter + * The datacenter. + * @param ip + * IP address of the remote hypervisor to connect. + * @param user + * User to log in. + * @param password + * Password to authenticate. + * @return The ipmi configuration state information + */ + MachineIpmiStateDto checkMachineIpmiState(DatacenterDto datacenter, String ip, String user, String password); + + /** + * Check the ipmi configuration state of a remote machine. This machine does + * not need to be managed by Abiquo. + * + * @param datacenter + * The datacenter. + * @param ip + * IP address of the remote hypervisor to connect. + * @param user + * User to log in. + * @param password + * Password to authenticate. + * @param options + * Optional query params. + * @return The ipmi configuration state information + */ + MachineIpmiStateDto checkMachineIpmiState(DatacenterDto datacenter, String ip, String user, String password, + IpmiOptions options); + + /*********************** Hypervisor ***********************/ + + /** + * Retreives the hypervisor type of a remote a machine. + * + * @param datacenter + * The datacenter. + * @param options + * Optional query params. + * @return The hypervisor type. + */ + String getHypervisorTypeFromMachine(DatacenterDto datacenter, DatacenterOptions options); + + /** + * Retreives the hypervisor types in the datacenter. + * + * @param datacenter + * The datacenter. + * @return The hypervisor types. + */ + HypervisorTypesDto getHypervisorTypes(DatacenterDto datacenter); + + /*********************** Unmanaged Rack ********************** */ + + /** + * List all not managed racks for a datacenter. + * + * @param datacenter + * The datacenter. + * @return The list of not managed racks for the datacenter. + */ + RacksDto listRacks(DatacenterDto datacenter); + + /** + * Create a new not managed rack in a datacenter. + * + * @param datacenter + * The datacenter. + * @param rack + * The rack to be created. + * @return The created rack. + */ + RackDto createRack(final DatacenterDto datacenter, final RackDto rack); + + /** + * Get the given rack from the given datacenter. + * + * @param datacenter + * The datacenter. + * @param rackId + * The id of the rack. + * @return The rack or null if it does not exist. + */ + RackDto getRack(DatacenterDto datacenter, Integer rackId); + + /** + * Updates an existing rack from the given datacenter. + * + * @param rack + * The new attributes for the rack. + * @return The updated rack. + */ + RackDto updateRack(final RackDto rack); + + /** + * Deletes an existing rack. + * + * @param rack + * The rack to delete. + */ + void deleteRack(final RackDto rack); + + /*********************** Managed Rack **********************/ + + /** + * List all managed racks for a datacenter. + * + * @param datacenter + * The datacenter. + * @return The list of managed racks for the datacenter. + */ + @EnterpriseEdition + @Timeout(duration = 60, timeUnit = TimeUnit.SECONDS) + UcsRacksDto listManagedRacks(DatacenterDto datacenter); + + /** + * Create a new managed rack in a datacenter. + * + * @param datacenter + * The datacenter. + * @param rack + * The managed rack to be created. + * @return The created rack. + */ + @EnterpriseEdition + @Timeout(duration = 90, timeUnit = TimeUnit.SECONDS) + UcsRackDto createManagedRack(final DatacenterDto datacenter, final UcsRackDto rack); + + /** + * Get the given managed rack from the given datacenter. + * + * @param datacenter + * The datacenter. + * @param rackId + * The id of the rack. + * @return The rack or null if it does not exist. + */ + @EnterpriseEdition + @Timeout(duration = 60, timeUnit = TimeUnit.SECONDS) + UcsRackDto getManagedRack(DatacenterDto datacenter, Integer rackId); + + /** + * Updates an existing managed rack from the given datacenter. + * + * @param rack + * The new attributes for the rack. + * @return The updated rack. + */ + @EnterpriseEdition + @Timeout(duration = 90, timeUnit = TimeUnit.SECONDS) + UcsRackDto updateManagedRack(final UcsRackDto rack); + + /** + * List all service profiles of the ucs rack. + * + * @param rack + * The ucs rack. + * @return The list of service profiles for the rack. + */ + @EnterpriseEdition + @Timeout(duration = 90, timeUnit = TimeUnit.SECONDS) + LogicServersDto listServiceProfiles(UcsRackDto rack); + + /** + * List service profiles of the ucs rack with filtering options. + * + * @param rack + * The ucs rack. + * @param options + * Optional query params. + * @return The list of service profiles for the rack. + */ + @EnterpriseEdition + @Timeout(duration = 90, timeUnit = TimeUnit.SECONDS) + LogicServersDto listServiceProfiles(UcsRackDto rack, FilterOptions options); + + /** + * List all service profile templates of the ucs rack. + * + * @param rack + * The ucs rack. + * @return The list of service profile templates for the rack. + */ + @EnterpriseEdition + @Timeout(duration = 90, timeUnit = TimeUnit.SECONDS) + LogicServersDto listServiceProfileTemplates(UcsRackDto rack); + + /** + * List all service profile templates of the ucs rack with options. + * + * @param rack + * The ucs rack. + * @param options + * Optional query params. + * @return The list of service profile templates for the rack. + */ + @EnterpriseEdition + @Timeout(duration = 90, timeUnit = TimeUnit.SECONDS) + LogicServersDto listServiceProfileTemplates(UcsRackDto rack, FilterOptions options); + + /** + * List all organizations of the ucs rack. + * + * @param rack + * The ucs rack. + * @return The list of organizations for the rack. + */ + @EnterpriseEdition + @Timeout(duration = 90, timeUnit = TimeUnit.SECONDS) + OrganizationsDto listOrganizations(UcsRackDto rack); + + /** + * List all organizations of the ucs rack with options. + * + * @param rack + * The ucs rack. + * @param options + * Optional query params. + * @return The list of organizations for the rack. + */ + @EnterpriseEdition + @Timeout(duration = 90, timeUnit = TimeUnit.SECONDS) + OrganizationsDto listOrganizations(UcsRackDto rack, FilterOptions options); + + /** + * Clone a service profile. + * + * @param rack + * The managed rack where thw service profile will be created. + * @param logicServer + * The original logic server. + * @param organization + * The organization to be associated. + * @param newName + * The name of the new service profile. + */ + @EnterpriseEdition + @Timeout(duration = 90, timeUnit = TimeUnit.SECONDS) + void cloneLogicServer(UcsRackDto rack, LogicServerDto logicServer, OrganizationDto organization, String newName); + + /** + * Delete a service profile. + * + * @param rack + * The managed rack where the service profile will be created. + * @param logicServer + * The original logic server. + */ + @EnterpriseEdition + @Timeout(duration = 90, timeUnit = TimeUnit.SECONDS) + void deleteLogicServer(UcsRackDto rack, LogicServerDto logicServer); + + /** + * Associate a service profile with a blade. + * + * @param rack + * The managed rack where the service profile is. + * @param logicServer + * The logic server. + * @param organization + * The organization to be associated. + * @param bladeName + * The name of the blade. + */ + @EnterpriseEdition + @Timeout(duration = 90, timeUnit = TimeUnit.SECONDS) + void associateLogicServer(UcsRackDto rack, LogicServerDto logicServer, OrganizationDto organization, String bladeName); + + /** + * Associate a service profile with a blade instantiating a service profile + * template. + * + * @param rack + * The managed rack where the service profile is. + * @param logicServer + * The logic server. + * @param organization + * The organization to be associated. + * @param newName + * Name of the new service profile. + * @param bladeName + * The name of the blade. + */ + @EnterpriseEdition + @Timeout(duration = 90, timeUnit = TimeUnit.SECONDS) + void associateTemplate(UcsRackDto rack, LogicServerDto logicServer, OrganizationDto organization, String newName, + String bladeName); + + /** + * Clone a service profile and associate it with a blade. + * + * @param rack + * The managed rack where the service profile is. + * @param logicServer + * The logic server. + * @param organization + * The organization to be associated. + * @param newName + * Name of the new service profile. + * @param bladeName + * The name of the blade. + */ + @EnterpriseEdition + @Timeout(duration = 90, timeUnit = TimeUnit.SECONDS) + void cloneAndAssociateLogicServer(UcsRackDto rack, LogicServerDto logicServer, OrganizationDto organization, + String newName, String bladeName); + + /** + * Dissociate a service profile from a blade. + * + * @param rack + * The managed rack where the service profile is. + * @param logicServer + * The logic server. + */ + @EnterpriseEdition + @Timeout(duration = 90, timeUnit = TimeUnit.SECONDS) + void dissociateLogicServer(UcsRackDto rack, LogicServerDto logicServer); + + /** + * Get FSM list of an entity + * + * @param rack + * The managed rack where the entity belongs. + * @param dn + * Distinguished name of the entity. + * @param fsm + * The fsm. + */ + @EnterpriseEdition + @Timeout(duration = 90, timeUnit = TimeUnit.SECONDS) + FsmsDto listFsms(UcsRackDto rack, String dn); + + /*********************** Remote Service ********************** */ + + /** + * List all remote services of the datacenter. + * + * @param datacenter + * The datacenter. + * @return The list of remote services for the datacenter. + */ + RemoteServicesDto listRemoteServices(DatacenterDto dataceter); + + /** + * Create a new remote service in a datacenter. + * + * @param datacenter + * The datacenter. + * @param remoteService + * The remote service to be created. + * @return The created remote service. + */ + RemoteServiceDto createRemoteService(final DatacenterDto datacenter, final RemoteServiceDto remoteService); + + /** + * Get the given remote service from the given datacenter. + * + * @param datacenter + * The datacenter. + * @param remoteServiceType + * The type of the remote service. + * @return The remote service or null if it does not exist. + */ + RemoteServiceDto getRemoteService(DatacenterDto datacenter, RemoteServiceType remoteServiceType); + + /** + * Updates an existing remote service from the given datacenter. + * + * @param remoteService + * The new attributes for the remote service. + * @return The updated remote service. + */ + RemoteServiceDto updateRemoteService(RemoteServiceDto remoteService); + + /** + * Deletes an existing remote service. + * + * @param remoteService + * The remote service to delete. + */ + void deleteRemoteService(RemoteServiceDto remoteService); + + /** + * Check if the given remote service is available and properly configured. + * + * @param remoteService + * The remote service to check. + * @return A Boolean indicating if the remote service is available. + */ + boolean isAvailable(RemoteServiceDto remoteService); + + /*********************** Machine ********************** */ + + /** + * Create a new physical machine in a rack. + * + * @param rack + * The rack. + * @param machine + * The physical machine to be created. + * @return The created physical machine. + */ + MachineDto createMachine(RackDto rack, MachineDto machine); + + /** + * Get the given machine from the given rack. + * + * @param rack + * The rack. + * @param machineId + * The id of the machine. + * @return The machine or null if it does not exist. + */ + MachineDto getMachine(RackDto rack, Integer machineId); + + /** + * Checks the real infrastructure state for the given physical machine. The + * machine is updated with the result state. + * + * @param machine + * The machine to check + * @paran boolean that indicates a database synchronization + * @return A machineStateDto with a machine state value from enum + * MachineState + */ + MachineStateDto checkMachineState(MachineDto machine, boolean sync); + + /** + * Checks the ipmi configuration state for the given physical machine. + * + * @param machine + * The machine to check + * @return A machineIpmiStateDto with a machine ipmi configuration state + * value from enum MachineState + */ + MachineIpmiStateDto checkMachineIpmiState(MachineDto machine); + + /** + * Updates an existing physical machine. + * + * @param machine + * The new attributes for the physical machine. + * @return The updated machine. + */ + MachineDto updateMachine(MachineDto machine); + + /** + * Deletes an existing physical machine. + * + * @param machine + * The physical machine to delete. + */ + void deleteMachine(MachineDto machine); + + /** + * Reserve the given machine for the given enterprise. + * + * @param enterprise + * The enterprise reserving the machine. + * @param machine + * The machine to reserve. + * @return The reserved machine. + */ + MachineDto reserveMachine(EnterpriseDto enterprise, MachineDto machine); + + /** + * Cancels the reservation of the given machine. + * + * @param enterprise + * The enterprise to cancel reservation. + * @param machine + * The machine to release. + */ + Void cancelReservation(EnterpriseDto enterprise, MachineDto machine); + + /** + * List all machines racks for a rack. + * + * @param rack + * The rack. + * @return The list of physical machines for the rack. + */ + MachinesDto listMachines(RackDto rack); + + /*********************** Blade ***********************/ + + /** + * Power off a physical machine in a UCS rack. + * + * @param machime + * The phyisical machine. + */ + @EnterpriseEdition + void powerOff(MachineDto machine); + + /** + * Power on a physical machine in a UCS rack. + * + * @param machime + * The phyisical machine. + */ + @EnterpriseEdition + void powerOn(MachineDto machine); + + /** + * Get the logic server associated with a machine in a Cisc UCS rack. + * + * @param machime + * The phyisical machine. + * @return The logic server. + */ + @EnterpriseEdition + LogicServerDto getLogicServer(MachineDto machine); + + /** + * Turn off locator led of a physical machine in a UCS rack. + * + * @param machime + * The phyisical machine. + */ + @EnterpriseEdition + void ledOn(MachineDto machine); + + /** + * Light locator led of a physical machine in a UCS rack. + * + * @param machime + * The phyisical machine. + */ + @EnterpriseEdition + void ledOff(MachineDto machine); + + /** + * Get led locator info from a physical machine in a UCS rack. + * + * @param machime + * The phyisical machine. + * @return Led locator information. + */ + @EnterpriseEdition + BladeLocatorLedDto getLocatorLed(MachineDto machine); + + /** + * List all virtual machines in a physical machine. + * + * @param machine + * The physical machine. + * @return The list of virtual machines in the physical machine. + */ + VirtualMachinesWithNodeExtendedDto listVirtualMachinesByMachine(MachineDto machine, MachineOptions options); + + /** + * Get the given virtual machine + * + * @param machine + * @param virtualMachineId + * @return + */ + VirtualMachineWithNodeExtendedDto getVirtualMachine(MachineDto machine, Integer virtualMachineId); + + /*********************** Storage Device ***********************/ + + /** + * List all storage devices of the datacenter. + * + * @param datacenter + * The datacenter. + * @return The list of storage devices in the datacenter. + */ + @EnterpriseEdition + StorageDevicesDto listStorageDevices(DatacenterDto datacenter); + + /** + * List all supported storage devices. + * + * @param datacenter + * The datacenter. + * @return The list of supported storage devices. + */ + @EnterpriseEdition + StorageDevicesMetadataDto listSupportedStorageDevices(DatacenterDto datacenter); + + /** + * Get the storage device. + * + * @param storageDeviceId + * The id of the storage device. + * @return The storage device or null if it does not exist. + */ + @EnterpriseEdition + StorageDeviceDto getStorageDevice(DatacenterDto datacenter, Integer storageDeviceId); + + /** + * Create a new storage device. + * + * @param datacenter + * The datacenter. + * @param storageDevice + * The storage device to be created. + * @return The created storage device. + */ + @EnterpriseEdition + StorageDeviceDto createStorageDevice(final DatacenterDto datacenter, final StorageDeviceDto storageDevice); + + /** + * Deletes an existing storage device. + * + * @param storageDevice + * The storage device to delete. + */ + @EnterpriseEdition + void deleteStorageDevice(StorageDeviceDto storageDevice); + + /** + * Updates an existing storage device. + * + * @param storageDevice + * The new attributes for the storage device. + * @return The updated storage device. + */ + @EnterpriseEdition + StorageDeviceDto updateStorageDevice(StorageDeviceDto storageDevice); + + /*********************** Tier ***********************/ + /** + * List all tiers of the datacenter. + * + * @param datacenter + * The datacenter. + * @return The list of tiers in the datacenter. + */ + @EnterpriseEdition + TiersDto listTiers(DatacenterDto datacenter); + + /** + * Updates a tier. + * + * @param tier + * The new attributes for the tier. + * @return The updated tier. + */ + @EnterpriseEdition + TierDto updateTier(TierDto tier); + + /** + * Get the tier. + * + * @param tierId + * The id of the tier. + * @return The tier or null if it does not exist. + */ + @EnterpriseEdition + TierDto getTier(DatacenterDto datacenter, Integer tierId); + + /*********************** Storage Pool ***********************/ + + /** + * List storage pools on a storage device. + * + * @param storageDevice + * The storage device. + * @param options + * Optional query params. + * @return The list of storage pools in the storage device. + */ + @EnterpriseEdition + StoragePoolsDto listStoragePools(StorageDeviceDto storageDeviceDto, StoragePoolOptions storagePoolOptions); + + /** + * List storage pools on a tier. + * + * @param tier + * The tier device. + * @return The list of storage pools in the tier. + */ + @EnterpriseEdition + StoragePoolsDto listStoragePools(TierDto tier); + + /** + * Create a new storage pool in a storage device. + * + * @param storageDevice + * The storage device. + * @param storagePool + * The storage pool to be created. + * @return The created storage pool. + */ + @EnterpriseEdition + StoragePoolDto createStoragePool(StorageDeviceDto storageDevice, StoragePoolDto storagePool); + + /** + * Updates a storage pool. + * + * @param storagePool + * The new attributes for the storage pool. + * @return The updated tier. + */ + @EnterpriseEdition + StoragePoolDto updateStoragePool(StoragePoolDto storagePool); + + /** + * Deletes an existing storage pool. + * + * @param storagePool + * The storage pool to delete. + */ + @EnterpriseEdition + void deleteStoragePool(StoragePoolDto storagePool); + + /** + * Get the storage pool. + * + * @param storageDevice + * The storage device. + * @param storagePoolId + * The id of the storage pool. + * @return The storage pool or null if it does not exist. + */ + @EnterpriseEdition + StoragePoolDto getStoragePool(StorageDeviceDto storageDevice, String storagePoolId); + + /** + * Refresh the given storage pool data. + * + * @param storagePool + * The storage pool to refresh. + * @param options + * The options to query the storage pool. + * @return The updated storage pool. + */ + @EnterpriseEdition + StoragePoolDto refreshStoragePool(StoragePoolDto storagePool, StoragePoolOptions options); + + /*********************** Network ***********************/ + + /** + * List all public, external and not managed networks of a datacenter. + * + * @param datacenter + * The datacenter. + * @return The list of not public, external and not managed for the + * datacenter. + */ + @EnterpriseEdition + VLANNetworksDto listNetworks(DatacenterDto datacenter); + + /** + * List networks of a datacenter with options. + * + * @param datacenter + * The datacenter. + * @param options + * Optional query params. + * @return The list of not public, external and not managed for the + * datacenter. + */ + @EnterpriseEdition + VLANNetworksDto listNetworks(DatacenterDto datacenter, NetworkOptions options); + + /** + * Get the given network from the given datacenter. + * + * @param datacenter + * The datacenter. + * @param networkId + * The id of the network. + * @return The rack or null if it does not exist. + */ + VLANNetworkDto getNetwork(DatacenterDto datacenter, Integer networkId); + + /** + * Create a new public network. + * + * @param storageDevice + * The storage device. + * @param storagePool + * The storage pool to be created. + * @return The created storage pool. + */ + @EnterpriseEdition + VLANNetworkDto createNetwork(DatacenterDto datacenter, VLANNetworkDto network); + + /** + * Updates a network. + * + * @param network + * The new attributes for the network. + * @return The updated tier. + */ + @EnterpriseEdition + VLANNetworkDto updateNetwork(VLANNetworkDto network); + + /** + * Deletes an existing network. + * + * @param network + * The network to delete. + */ + @EnterpriseEdition + void deleteNetwork(VLANNetworkDto network); + + /** + * Check the availability of a tag. + * + * @param datacenter + * The datacenter. + * @param tag + * Tag to check. + * @return A tag availability object. + */ + @EnterpriseEdition + VlanTagAvailabilityDto checkTagAvailability(DatacenterDto datacenter, Integer tag); + + /*********************** Network IPs ***********************/ + + /** + * List all the IPs in the given public network. + * + * @param network + * The public network. + * @return The IPs in the given public network. + * @since 2.3 + */ + PublicIpsDto listPublicIps(VLANNetworkDto network); + + /** + * List all the IPs in the given public network. + * + * @param network + * The public network. + * @param options + * The filtering options. + * @return The IPs in the given public network. + * @since 2.3 + */ + PublicIpsDto listPublicIps(VLANNetworkDto network, IpOptions options); + + /** + * Get the given public ip. + * + * @param network + * The public network. + * @param ipId + * The id of the ip to get. + * @return The requested ip. + * @since 2.3 + */ + PublicIpDto getPublicIp(VLANNetworkDto network, Integer ipId); + + /** + * List all the IPs in the given external network. + * + * @param network + * The external network. + * @return The IPs in the given external network. + * @since 2.3 + */ + ExternalIpsDto listExternalIps(VLANNetworkDto network); + + /** + * List all the IPs in the given external network. + * + * @param network + * The external network. + * @param options + * The filtering options. + * @return The IPs in the given external network. + * @since 2.3 + */ + ExternalIpsDto listExternalIps(VLANNetworkDto network, IpOptions options); + + /** + * Get the given external ip. + * + * @param network + * The external network. + * @param ipId + * The id of the ip to get. + * @return The requested ip. + * @since 2.3 + */ + ExternalIpDto getExternalIp(VLANNetworkDto network, Integer ipId); + + /** + * List all the IPs in the given unmanaged network. + * + * @param network + * The unmanaged network. + * @return The IPs in the given unmanaged network. + * @since 2.3 + */ + UnmanagedIpsDto listUnmanagedIps(VLANNetworkDto network); + + /** + * List all the IPs in the given unmanaged network. + * + * @param network + * The unmanaged network. + * @param options + * The filtering options. + * @return The IPs in the given unmanaged network. + * @since 2.3 + */ + UnmanagedIpsDto listUnmanagedIps(VLANNetworkDto network, IpOptions options); + + /** + * Get the given unmanaged ip. + * + * @param network + * The unmanaged network. + * @param ipId + * The id of the ip to get. + * @return The requested ip. + * @since 2.3 + */ + UnmanagedIpDto getUnmanagedIp(VLANNetworkDto network, Integer ipId); +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/features/InfrastructureAsyncApi.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/features/InfrastructureAsyncApi.java new file mode 100644 index 0000000000..a0d77e4724 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/features/InfrastructureAsyncApi.java @@ -0,0 +1,1081 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.features; + +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 javax.ws.rs.QueryParam; +import javax.ws.rs.core.MediaType; + +import org.jclouds.abiquo.binders.AppendToPath; +import org.jclouds.abiquo.binders.BindToPath; +import org.jclouds.abiquo.binders.BindToXMLPayloadAndPath; +import org.jclouds.abiquo.binders.infrastructure.AppendMachineIdToPath; +import org.jclouds.abiquo.binders.infrastructure.AppendRemoteServiceTypeToPath; +import org.jclouds.abiquo.binders.infrastructure.BindSupportedDevicesLinkToPath; +import org.jclouds.abiquo.binders.infrastructure.ucs.BindLogicServerParameters; +import org.jclouds.abiquo.binders.infrastructure.ucs.BindOrganizationParameters; +import org.jclouds.abiquo.domain.infrastructure.options.DatacenterOptions; +import org.jclouds.abiquo.domain.infrastructure.options.IpmiOptions; +import org.jclouds.abiquo.domain.infrastructure.options.MachineOptions; +import org.jclouds.abiquo.domain.infrastructure.options.StoragePoolOptions; +import org.jclouds.abiquo.domain.network.options.IpOptions; +import org.jclouds.abiquo.domain.network.options.NetworkOptions; +import org.jclouds.abiquo.domain.options.search.FilterOptions; +import org.jclouds.abiquo.functions.ReturnAbiquoExceptionOnNotFoundOr4xx; +import org.jclouds.abiquo.functions.ReturnFalseIfNotAvailable; +import org.jclouds.abiquo.functions.infrastructure.ParseDatacenterId; +import org.jclouds.abiquo.http.filters.AbiquoAuthentication; +import org.jclouds.abiquo.http.filters.AppendApiVersionToMediaType; +import org.jclouds.abiquo.reference.annotations.EnterpriseEdition; +import org.jclouds.abiquo.rest.annotations.EndpointLink; +import org.jclouds.http.functions.ReturnStringIf2xx; +import org.jclouds.rest.annotations.BinderParam; +import org.jclouds.rest.annotations.ExceptionParser; +import org.jclouds.rest.annotations.JAXBResponseParser; +import org.jclouds.rest.annotations.ParamParser; +import org.jclouds.rest.annotations.RequestFilters; +import org.jclouds.rest.annotations.ResponseParser; +import org.jclouds.rest.binders.BindToXMLPayload; +import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; + +import com.abiquo.model.enumerator.HypervisorType; +import com.abiquo.model.enumerator.RemoteServiceType; +import com.abiquo.server.core.cloud.HypervisorTypesDto; +import com.abiquo.server.core.cloud.VirtualMachineWithNodeExtendedDto; +import com.abiquo.server.core.cloud.VirtualMachinesWithNodeExtendedDto; +import com.abiquo.server.core.enterprise.DatacentersLimitsDto; +import com.abiquo.server.core.enterprise.EnterpriseDto; +import com.abiquo.server.core.infrastructure.BladeLocatorLedDto; +import com.abiquo.server.core.infrastructure.DatacenterDto; +import com.abiquo.server.core.infrastructure.DatacentersDto; +import com.abiquo.server.core.infrastructure.FsmsDto; +import com.abiquo.server.core.infrastructure.LogicServerDto; +import com.abiquo.server.core.infrastructure.LogicServersDto; +import com.abiquo.server.core.infrastructure.MachineDto; +import com.abiquo.server.core.infrastructure.MachineIpmiStateDto; +import com.abiquo.server.core.infrastructure.MachineStateDto; +import com.abiquo.server.core.infrastructure.MachinesDto; +import com.abiquo.server.core.infrastructure.OrganizationDto; +import com.abiquo.server.core.infrastructure.OrganizationsDto; +import com.abiquo.server.core.infrastructure.RackDto; +import com.abiquo.server.core.infrastructure.RacksDto; +import com.abiquo.server.core.infrastructure.RemoteServiceDto; +import com.abiquo.server.core.infrastructure.RemoteServicesDto; +import com.abiquo.server.core.infrastructure.UcsRackDto; +import com.abiquo.server.core.infrastructure.UcsRacksDto; +import com.abiquo.server.core.infrastructure.network.ExternalIpDto; +import com.abiquo.server.core.infrastructure.network.ExternalIpsDto; +import com.abiquo.server.core.infrastructure.network.PublicIpDto; +import com.abiquo.server.core.infrastructure.network.PublicIpsDto; +import com.abiquo.server.core.infrastructure.network.UnmanagedIpDto; +import com.abiquo.server.core.infrastructure.network.UnmanagedIpsDto; +import com.abiquo.server.core.infrastructure.network.VLANNetworkDto; +import com.abiquo.server.core.infrastructure.network.VLANNetworksDto; +import com.abiquo.server.core.infrastructure.network.VlanTagAvailabilityDto; +import com.abiquo.server.core.infrastructure.storage.StorageDeviceDto; +import com.abiquo.server.core.infrastructure.storage.StorageDevicesDto; +import com.abiquo.server.core.infrastructure.storage.StorageDevicesMetadataDto; +import com.abiquo.server.core.infrastructure.storage.StoragePoolDto; +import com.abiquo.server.core.infrastructure.storage.StoragePoolsDto; +import com.abiquo.server.core.infrastructure.storage.TierDto; +import com.abiquo.server.core.infrastructure.storage.TiersDto; +import com.google.common.util.concurrent.ListenableFuture; + +/** + * Provides asynchronous access to Abiquo Infrastructure API. + * + * @see API: + * http://community.abiquo.com/display/ABI20/API+Reference + * @see InfrastructureApi + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +@RequestFilters({ AbiquoAuthentication.class, AppendApiVersionToMediaType.class }) +@Path("/admin") +public interface InfrastructureAsyncApi { + /*********************** Datacenter ***********************/ + + /** + * @see InfrastructureApi#listDatacenters() + */ + @GET + @Path("/datacenters") + @Consumes(DatacentersDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listDatacenters(); + + /** + * @see InfrastructureApi#createDatacenter(DatacenterDto) + */ + @POST + @Path("/datacenters") + @Produces(DatacenterDto.BASE_MEDIA_TYPE) + @Consumes(DatacenterDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture createDatacenter(@BinderParam(BindToXMLPayload.class) DatacenterDto datacenter); + + /** + * @see InfrastructureApi#getDatacenter(Integer) + */ + @GET + @Path("/datacenters/{datacenter}") + @Consumes(DatacenterDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + ListenableFuture getDatacenter(@PathParam("datacenter") Integer datacenterId); + + /** + * @see InfrastructureApi#updateDatacenter(DatacenterDto) + */ + @PUT + @Produces(DatacenterDto.BASE_MEDIA_TYPE) + @Consumes(DatacenterDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture updateDatacenter( + @EndpointLink("edit") @BinderParam(BindToXMLPayloadAndPath.class) DatacenterDto datacenter); + + /** + * @see InfrastructureApi#deleteDatacenter(DatacenterDto) + */ + @DELETE + ListenableFuture deleteDatacenter(@EndpointLink("edit") @BinderParam(BindToPath.class) DatacenterDto datacenter); + + /** + * @see InfrastructureApi#discoverSingleMachine(DatacenterDto, String, + * HypervisorType, String, String) + */ + @GET + @Consumes(MachineDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + @ExceptionParser(ReturnAbiquoExceptionOnNotFoundOr4xx.class) + ListenableFuture discoverSingleMachine( + @EndpointLink("discoversingle") @BinderParam(BindToPath.class) DatacenterDto datacenter, + @QueryParam("ip") String ip, @QueryParam("hypervisor") HypervisorType hypervisorType, + @QueryParam("user") String user, @QueryParam("password") String password); + + /** + * @see InfrastructureApi#discoverSingleMachine(DatacenterDto, String, + * HypervisorType, String, String, MachineOptions) + */ + @GET + @Consumes(MachineDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + @ExceptionParser(ReturnAbiquoExceptionOnNotFoundOr4xx.class) + ListenableFuture discoverSingleMachine( + @EndpointLink("discoversingle") @BinderParam(BindToPath.class) DatacenterDto datacenter, + @QueryParam("ip") String ip, @QueryParam("hypervisor") HypervisorType hypervisorType, + @QueryParam("user") String user, @QueryParam("password") String password, MachineOptions options); + + /** + * @see InfrastructureApi#discoverMultipleMachines(DatacenterDto, String, + * String, HypervisorType, String, String) + */ + @GET + @Consumes(MachinesDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + @ExceptionParser(ReturnAbiquoExceptionOnNotFoundOr4xx.class) + ListenableFuture discoverMultipleMachines( + @EndpointLink("discovermultiple") @BinderParam(BindToPath.class) DatacenterDto datacenter, + @QueryParam("ipFrom") String ipFrom, @QueryParam("ipTo") String ipTo, + @QueryParam("hypervisor") HypervisorType hypervisorType, @QueryParam("user") String user, + @QueryParam("password") String password); + + /** + * @see InfrastructureApi#discoverMultipleMachines(DatacenterDto, String, + * String, HypervisorType, String, String, MachineOptions) + */ + @GET + @Consumes(MachinesDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + @ExceptionParser(ReturnAbiquoExceptionOnNotFoundOr4xx.class) + ListenableFuture discoverMultipleMachines( + @EndpointLink("discovermultiple") @BinderParam(BindToPath.class) DatacenterDto datacenter, + @QueryParam("ipFrom") String ipFrom, @QueryParam("ipTo") String ipTo, + @QueryParam("hypervisor") HypervisorType hypervisorType, @QueryParam("user") String user, + @QueryParam("password") String password, MachineOptions options); + + /** + * @see InfrastructureApi#listLimits(DatacenterDto) + */ + @GET + @Consumes(DatacentersLimitsDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listLimits( + @EndpointLink("getLimits") @BinderParam(BindToPath.class) DatacenterDto datacenter); + + /** + * @see InfrastructureApi#checkMachineState(DatacenterDto, String, String, + * HypervisorType, String, String) + */ + @GET + @Consumes(MachineStateDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + @ExceptionParser(ReturnAbiquoExceptionOnNotFoundOr4xx.class) + ListenableFuture checkMachineState( + @EndpointLink("checkmachinestate") @BinderParam(BindToPath.class) DatacenterDto datacenter, + @QueryParam("ip") String ip, @QueryParam("hypervisor") HypervisorType hypervisorType, + @QueryParam("user") String user, @QueryParam("password") String password); + + /** + * @see InfrastructureApi#checkMachineState(DatacenterDto, String, String, + * HypervisorType, String, String, MachineOptions) + */ + @GET + @Consumes(MachineStateDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + @ExceptionParser(ReturnAbiquoExceptionOnNotFoundOr4xx.class) + ListenableFuture checkMachineState( + @EndpointLink("checkmachinestate") @BinderParam(BindToPath.class) DatacenterDto datacenter, + @QueryParam("ip") String ip, @QueryParam("hypervisor") HypervisorType hypervisorType, + @QueryParam("user") String user, @QueryParam("password") String password, MachineOptions options); + + /** + * @see InfrastructureApi#checkMachineIpmiState(DatacenterDto, String, + * String, String) + */ + @GET + @Consumes(MachineIpmiStateDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + @ExceptionParser(ReturnAbiquoExceptionOnNotFoundOr4xx.class) + ListenableFuture checkMachineIpmiState( + @EndpointLink("checkmachineipmistate") @BinderParam(BindToPath.class) DatacenterDto datacenter, + @QueryParam("ip") String ip, @QueryParam("user") String user, @QueryParam("password") String password); + + /** + * @see InfrastructureApi#checkMachineIpmiState(DatacenterDto, String, + * String, String, IpmiOptions) + */ + @GET + @Consumes(MachineIpmiStateDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + @ExceptionParser(ReturnAbiquoExceptionOnNotFoundOr4xx.class) + ListenableFuture checkMachineIpmiState( + @EndpointLink("checkmachineipmistate") @BinderParam(BindToPath.class) DatacenterDto datacenter, + @QueryParam("ip") String ip, @QueryParam("user") String user, @QueryParam("password") String password, + IpmiOptions options); + + /*********************** Hypervisor ***********************/ + /** + * @see InfrastructureApi#getHypervisorTypeFromMachine(DatacenterDto, + * DatacenterOptions) + */ + @GET + @Consumes(MediaType.TEXT_PLAIN) + @ResponseParser(ReturnStringIf2xx.class) + ListenableFuture getHypervisorTypeFromMachine( + @EndpointLink("hypervisor") @BinderParam(BindToPath.class) DatacenterDto datacenter, DatacenterOptions options); + + /** + * @see InfrastructureApi#getHypervisorTypes(DatacenterDto) + */ + @GET + @Consumes(HypervisorTypesDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture getHypervisorTypes( + @EndpointLink("hypervisors") @BinderParam(BindToPath.class) DatacenterDto datacenter); + + /*********************** Unmanaged Rack ***********************/ + + /** + * @see InfrastructureApi#listRacks(DatacenterDto) + */ + @GET + @Consumes(RacksDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listRacks(@EndpointLink("racks") @BinderParam(BindToPath.class) DatacenterDto datacenter); + + /** + * @see InfrastructureApi#createRack(DatacenterDto, RackDto) + */ + @POST + @Produces(RackDto.BASE_MEDIA_TYPE) + @Consumes(RackDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture createRack(@EndpointLink("racks") @BinderParam(BindToPath.class) DatacenterDto datacenter, + @BinderParam(BindToXMLPayload.class) RackDto rack); + + /** + * @see InfrastructureApi#getRack(DatacenterDto, Integer) + */ + @GET + @Consumes(RackDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + ListenableFuture getRack(@EndpointLink("racks") @BinderParam(BindToPath.class) DatacenterDto datacenter, + @BinderParam(AppendToPath.class) Integer rackId); + + /** + * @see InfrastructureApi#updateRack(RackDto) + */ + @PUT + @Consumes(RackDto.BASE_MEDIA_TYPE) + @Produces(RackDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture updateRack(@EndpointLink("edit") @BinderParam(BindToXMLPayloadAndPath.class) RackDto rack); + + /** + * @see InfrastructureApi#deleteRack(RackDto) + */ + @DELETE + ListenableFuture deleteRack(@EndpointLink("edit") @BinderParam(BindToPath.class) RackDto rack); + + /*********************** Managed Rack ***********************/ + + /** + * @see InfrastructureApi#listManagedRacks(DatacenterDto) + */ + @EnterpriseEdition + @GET + @Consumes(UcsRacksDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listManagedRacks( + @EndpointLink("racks") @BinderParam(BindToPath.class) DatacenterDto datacenter); + + /** + * @see InfrastructureApi#createManagedRack(DatacenterDto, UcsRackDto) + */ + @EnterpriseEdition + @POST + @Produces(UcsRackDto.BASE_MEDIA_TYPE) + @Consumes(UcsRackDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture createManagedRack( + @EndpointLink("racks") @BinderParam(BindToPath.class) DatacenterDto datacenter, + @BinderParam(BindToXMLPayload.class) UcsRackDto rack); + + /** + * @see InfrastructureApi#getManagedRack(DatacenterDto, Integer) + */ + @EnterpriseEdition + @GET + @Consumes(UcsRackDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + ListenableFuture getManagedRack( + @EndpointLink("racks") @BinderParam(BindToPath.class) DatacenterDto datacenter, + @BinderParam(AppendToPath.class) Integer rackId); + + /** + * @see InfrastructureApi#updateManagedRack(UcsRackDto) + */ + @EnterpriseEdition + @PUT + @Consumes(UcsRackDto.BASE_MEDIA_TYPE) + @Produces(UcsRackDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture updateManagedRack( + @EndpointLink("edit") @BinderParam(BindToXMLPayloadAndPath.class) UcsRackDto rack); + + /** + * @see InfrastructureApi#listServiceProfiles(UcsRackDto) + */ + @EnterpriseEdition + @GET + @Consumes(LogicServersDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listServiceProfiles( + @EndpointLink("logicservers") @BinderParam(BindToPath.class) UcsRackDto rack); + + /** + * @see InfrastructureApi#listServiceProfiles(UcsRackDto, QueryOptions) + */ + @EnterpriseEdition + @GET + @Consumes(LogicServersDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listServiceProfiles( + @EndpointLink("logicservers") @BinderParam(BindToPath.class) UcsRackDto rack, FilterOptions options); + + /** + * @see InfrastructureApi#listServiceProfileTemplates(UcsRackDto) + */ + @EnterpriseEdition + @GET + @Consumes(LogicServersDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listServiceProfileTemplates( + @EndpointLink("ls-templates") @BinderParam(BindToPath.class) UcsRackDto rack); + + /** + * @see InfrastructureApi#listServiceProfileTemplates(UcsRackDto, + * LogicServerOptions) + */ + @EnterpriseEdition + @GET + @Consumes(LogicServersDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listServiceProfileTemplates( + @EndpointLink("ls-templates") @BinderParam(BindToPath.class) UcsRackDto rack, FilterOptions options); + + /** + * @see InfrastructureApi#listOrganizations(UcsRackDto) + */ + @EnterpriseEdition + @GET + @Consumes(OrganizationsDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listOrganizations( + @EndpointLink("organizations") @BinderParam(BindToPath.class) UcsRackDto rack); + + /** + * @see InfrastructureApi#listOrganizations(UcsRackDto, OrganizationOptions) + */ + @EnterpriseEdition + @GET + @Consumes(OrganizationsDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listOrganizations( + @EndpointLink("organizations") @BinderParam(BindToPath.class) UcsRackDto rack, FilterOptions options); + + /** + * @see InfrastructureApi#cloneLogicServer(UcsRackDto, LogicServerDto, + * OrganizationDto, String) + */ + @EnterpriseEdition + @POST + ListenableFuture cloneLogicServer(@EndpointLink("ls-clone") @BinderParam(BindToPath.class) UcsRackDto rack, + @BinderParam(BindLogicServerParameters.class) LogicServerDto logicServer, + @BinderParam(BindOrganizationParameters.class) OrganizationDto organization, + @QueryParam("newName") String newName); + + /** + * @see InfrastructureApi#associateLogicServer(UcsRackDto, LogicServerDto, + * OrganizationDto, String) + */ + @EnterpriseEdition + @POST + ListenableFuture associateLogicServer( + @EndpointLink("ls-associate") @BinderParam(BindToPath.class) UcsRackDto rack, + @BinderParam(BindLogicServerParameters.class) LogicServerDto logicServer, + @BinderParam(BindOrganizationParameters.class) OrganizationDto organization, + @QueryParam("bladeDn") String bladeName); + + /** + * @see InfrastructureApi#associateTemplate(UcsRackDto, LogicServerDto, + * OrganizationDto, String, String) + */ + @EnterpriseEdition + @POST + ListenableFuture associateTemplate( + @EndpointLink("ls-associatetemplate") @BinderParam(BindToPath.class) UcsRackDto rack, + @BinderParam(BindLogicServerParameters.class) LogicServerDto logicServer, + @BinderParam(BindOrganizationParameters.class) OrganizationDto organization, + @QueryParam("newName") String newName, @QueryParam("bladeDn") String bladeName); + + /** + * @see InfrastructureApi#cloneAndAssociateLogicServer(UcsRackDto, + * LogicServerDto, OrganizationDto, String, String) + */ + @EnterpriseEdition + @POST + ListenableFuture cloneAndAssociateLogicServer( + @EndpointLink("ls-associateclone") @BinderParam(BindToPath.class) UcsRackDto rack, + @BinderParam(BindLogicServerParameters.class) LogicServerDto logicServer, + @BinderParam(BindOrganizationParameters.class) OrganizationDto organization, + @QueryParam("newName") String newName, @QueryParam("bladeDn") String bladeName); + + /** + * @see InfrastructureApi#dissociateLogicServer(UcsRackDto, LogicServerDto) + */ + @EnterpriseEdition + @POST + ListenableFuture dissociateLogicServer( + @EndpointLink("ls-dissociate") @BinderParam(BindToPath.class) UcsRackDto rack, + @BinderParam(BindLogicServerParameters.class) LogicServerDto logicServer); + + /** + * @see InfrastructureApi#deleteLogicServer(UcsRackDto, LogicServerDto) + */ + @EnterpriseEdition + @POST + ListenableFuture deleteLogicServer(@EndpointLink("ls-delete") @BinderParam(BindToPath.class) UcsRackDto rack, + @BinderParam(BindLogicServerParameters.class) LogicServerDto logicServer); + + /** + * @see InfrastructureApi#listFsms(UcsRackDto, String) + */ + @EnterpriseEdition + @GET + @Consumes(FsmsDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listFsms(@EndpointLink("fsm") @BinderParam(BindToPath.class) UcsRackDto rack, + @QueryParam("dn") String dn); + + /*********************** Remote Service ***********************/ + + /** + * @see InfrastructureApi#listRemoteServices(DatacenterDto) + */ + @GET + @Consumes(RemoteServicesDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listRemoteServices( + @EndpointLink("remoteservices") @BinderParam(BindToPath.class) DatacenterDto datacenter); + + /** + * @see InfrastructureApi#createRemoteService(DatacenterDto, + * RemoteServiceDto) + */ + @POST + @Produces(RemoteServiceDto.BASE_MEDIA_TYPE) + @Consumes(RemoteServiceDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture createRemoteService( + @EndpointLink("remoteservices") @BinderParam(BindToPath.class) DatacenterDto datacenter, + @BinderParam(BindToXMLPayload.class) RemoteServiceDto remoteService); + + /** + * @see InfrastructureApi#getRemoteService(DatacenterDto, RemoteServiceType) + */ + @GET + @Consumes(RemoteServiceDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + ListenableFuture getRemoteService( + @EndpointLink("remoteservices") @BinderParam(BindToPath.class) final DatacenterDto datacenter, + @BinderParam(AppendRemoteServiceTypeToPath.class) final RemoteServiceType remoteServiceType); + + /** + * @see InfrastructureApi#updateRemoteService(RemoteServiceDto) + */ + @PUT + @Consumes(RemoteServiceDto.BASE_MEDIA_TYPE) + @Produces(RemoteServiceDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture updateRemoteService( + @EndpointLink("edit") @BinderParam(BindToXMLPayloadAndPath.class) RemoteServiceDto remoteService); + + /** + * @see InfrastructureApi#deleteRemoteService(RemoteServiceDto) + */ + @DELETE + ListenableFuture deleteRemoteService( + @EndpointLink("edit") @BinderParam(BindToPath.class) RemoteServiceDto remoteService); + + /** + * @see InfrastructureApi#isAvailable(RemoteServiceDto) + */ + @GET + @ExceptionParser(ReturnFalseIfNotAvailable.class) + ListenableFuture isAvailable( + @EndpointLink("check") @BinderParam(BindToPath.class) RemoteServiceDto remoteService); + + /*********************** Machine ***********************/ + + /** + * @see InfrastructureApi#listMachines(RackDto) + */ + @GET + @Consumes(MachinesDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listMachines(@EndpointLink("machines") @BinderParam(BindToPath.class) RackDto rack); + + /** + * @see InfrastructureApi#createMachine(RackDto, MachineDto) + */ + @POST + @Produces(MachineDto.BASE_MEDIA_TYPE) + @Consumes(MachineDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture createMachine(@EndpointLink("machines") @BinderParam(BindToPath.class) RackDto rack, + @BinderParam(BindToXMLPayload.class) MachineDto machine); + + /** + * @see InfrastructureApi#getMachine(RackDto, Integer) + */ + @GET + @Consumes(MachineDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + ListenableFuture getMachine(@EndpointLink("machines") @BinderParam(BindToPath.class) final RackDto rack, + @BinderParam(AppendToPath.class) Integer machineId); + + /** + * @see InfrastructureApi#checkMachineState(MachineDto) + */ + @GET + @Consumes(MachineStateDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture checkMachineState( + @EndpointLink("checkstate") @BinderParam(BindToPath.class) final MachineDto machine, + @QueryParam("sync") boolean sync); + + /** + * @see InfrastructureApi#checkMachineIpmiState(MachineDto) + */ + @GET + @Consumes(MachineIpmiStateDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture checkMachineIpmiState( + @EndpointLink("checkipmistate") @BinderParam(BindToPath.class) final MachineDto machine); + + /** + * @see InfrastructureApi#updateMachine(MachineDto) + */ + @PUT + @Produces(MachineDto.BASE_MEDIA_TYPE) + @Consumes(MachineDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture updateMachine( + @EndpointLink("edit") @BinderParam(BindToXMLPayloadAndPath.class) MachineDto machine); + + /** + * @see InfrastructureApi#deleteMachine(MachineDto) + */ + @DELETE + ListenableFuture deleteMachine(@EndpointLink("edit") @BinderParam(BindToPath.class) MachineDto machine); + + /** + * @see InfrastructureApi#reserveMachine(EnterpriseDto, MachineDto) + */ + @POST + @Consumes(MachineDto.BASE_MEDIA_TYPE) + @Produces(MachineDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture reserveMachine( + @EndpointLink("reservedmachines") @BinderParam(BindToPath.class) EnterpriseDto enterprise, + @BinderParam(BindToXMLPayload.class) MachineDto machine); + + /** + * @see InfrastructureApi#cancelReservation(EnterpriseDto, MachineDto) + */ + @DELETE + ListenableFuture cancelReservation( + @EndpointLink("reservedmachines") @BinderParam(BindToPath.class) EnterpriseDto enterprise, + @BinderParam(AppendMachineIdToPath.class) MachineDto machine); + + /*********************** Blade ***********************/ + + /** + * @see InfrastructureApi#powerOff(MachineDto) + */ + @EnterpriseEdition + @PUT + ListenableFuture powerOff(@EndpointLink("poweroff") @BinderParam(BindToPath.class) MachineDto machine); + + /** + * @see InfrastructureApi#powerOn(MachineDto) + */ + @EnterpriseEdition + @PUT + ListenableFuture powerOn(@EndpointLink("poweron") @BinderParam(BindToPath.class) MachineDto machine); + + /** + * @see InfrastructureApi#getLogicServer(MachineDto) + */ + @EnterpriseEdition + @GET + @Consumes(LogicServerDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture getLogicServer( + @EndpointLink("logicserver") @BinderParam(BindToPath.class) MachineDto machine); + + /** + * @see InfrastructureApi#ledOn(MachineDto) + */ + @EnterpriseEdition + @POST + ListenableFuture ledOn(@EndpointLink("ledon") @BinderParam(BindToPath.class) MachineDto machine); + + /** + * @see InfrastructureApi#ledOff(MachineDto) + */ + @EnterpriseEdition + @POST + ListenableFuture ledOff(@EndpointLink("ledoff") @BinderParam(BindToPath.class) MachineDto machine); + + /** + * @see InfrastructureApi#getLedLocator(MachineDto) + */ + @EnterpriseEdition + @GET + @Consumes(BladeLocatorLedDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture getLocatorLed( + @EndpointLink("led") @BinderParam(BindToPath.class) MachineDto machine); + + /*********************** Storage Device ***********************/ + + /** + * @see InfrastructureApi#listVirtualMachinesByMachine(MachineDto) + */ + @GET + @Consumes(VirtualMachinesWithNodeExtendedDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listVirtualMachinesByMachine( + @EndpointLink("virtualmachines") @BinderParam(BindToPath.class) MachineDto machine, MachineOptions options); + + /** + * @see InfrastructureApi#getVirtualMachine(MachineDto, Integer) + */ + @GET + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + @Consumes(VirtualMachineWithNodeExtendedDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture getVirtualMachine( + @EndpointLink("virtualmachines") @BinderParam(BindToPath.class) MachineDto machine, + @BinderParam(AppendToPath.class) Integer virtualMachineId); + + /*********************** Storage Device ***********************/ + + /** + * @see InfrastructureApi#listStorageDevices(DatacenterDto) + */ + @EnterpriseEdition + @GET + @Consumes(StorageDevicesDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listStorageDevices( + @EndpointLink("devices") @BinderParam(BindToPath.class) DatacenterDto datacenter); + + /** + * @see InfrastructureApi#listSupportedStorageDevices(DatacenterDto) + */ + @EnterpriseEdition + @GET + @Consumes(StorageDevicesMetadataDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listSupportedStorageDevices( + @EndpointLink("devices") @BinderParam(BindSupportedDevicesLinkToPath.class) DatacenterDto datacenter); + + /** + * @see InfrastructureApi#getStorageDevice(DatacenterDto, Integer) + */ + @EnterpriseEdition + @GET + @Consumes(StorageDeviceDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + ListenableFuture getStorageDevice( + @EndpointLink("devices") @BinderParam(BindToPath.class) DatacenterDto datacenter, + @BinderParam(AppendToPath.class) Integer storageDeviceId); + + /** + * @see InfrastructureApi#createStorageDevice(DatacenterDto, + * StorageDeviceDto) + */ + @EnterpriseEdition + @POST + @Produces(StorageDeviceDto.BASE_MEDIA_TYPE) + @Consumes(StorageDeviceDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture createStorageDevice( + @EndpointLink("devices") @BinderParam(BindToPath.class) DatacenterDto datacenter, + @BinderParam(BindToXMLPayload.class) StorageDeviceDto storageDevice); + + /** + * @see InfrastructureApi#deleteStorageDevice(StorageDeviceDto) + */ + @EnterpriseEdition + @DELETE + ListenableFuture deleteStorageDevice( + @EndpointLink("edit") @BinderParam(BindToPath.class) StorageDeviceDto storageDevice); + + /** + * @see InfrastructureApi#updateStorageDevice(StorageDeviceDto) + */ + @EnterpriseEdition + @PUT + @Produces(StorageDeviceDto.BASE_MEDIA_TYPE) + @Consumes(StorageDeviceDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture updateStorageDevice( + @EndpointLink("edit") @BinderParam(BindToXMLPayloadAndPath.class) StorageDeviceDto storageDevice); + + /*********************** Tier ***********************/ + + /** + * @see InfrastructureApi#listTiers(DatacenterDto) + */ + @EnterpriseEdition + @GET + @Consumes(TiersDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listTiers(@EndpointLink("tiers") @BinderParam(BindToPath.class) DatacenterDto datacenter); + + /** + * @see InfrastructureApi#updateTier(TierDto) + */ + @EnterpriseEdition + @PUT + @Produces(TierDto.BASE_MEDIA_TYPE) + @Consumes(TierDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture updateTier(@EndpointLink("edit") @BinderParam(BindToXMLPayloadAndPath.class) TierDto tier); + + /** + * @see InfrastructureApi#getTier(DatacenterDto, Integer) + */ + @EnterpriseEdition + @GET + @Consumes(TierDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + ListenableFuture getTier(@EndpointLink("tiers") @BinderParam(BindToPath.class) DatacenterDto datacenter, + @BinderParam(AppendToPath.class) Integer tierId); + + /*********************** Storage Pool ***********************/ + + /** + * @see InfrastructureApi#listStoragePools(StorageDeviceDto, + * StoragePoolOptions) + */ + @EnterpriseEdition + @GET + @Consumes(StoragePoolsDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listStoragePools( + @EndpointLink("pools") @BinderParam(BindToPath.class) StorageDeviceDto storageDevice, + StoragePoolOptions options); + + /** + * @see InfrastructureApi#listStoragePools(TierDto) + */ + @EnterpriseEdition + @GET + @Consumes(StoragePoolsDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listStoragePools(@EndpointLink("pools") @BinderParam(BindToPath.class) TierDto tier); + + /** + * @see InfrastructureApi#createStoragePool(StorageDeviceDto, StoragePoolDto) + */ + @EnterpriseEdition + @POST + @Consumes(StoragePoolDto.BASE_MEDIA_TYPE) + @Produces(StoragePoolDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture createStoragePool( + @EndpointLink("pools") @BinderParam(BindToPath.class) StorageDeviceDto storageDevice, + @BinderParam(BindToXMLPayload.class) StoragePoolDto storagePool); + + /** + * @see InfrastructureApi#updateStoragePool(StoragePoolDto) + */ + @EnterpriseEdition + @PUT + // For the most strangest reason in world, compiler does not accept + // constants StoragePoolDto.BASE_MEDIA_TYPE for this method. + @Consumes("application/vnd.abiquo.storagepool+xml") + @Produces("application/vnd.abiquo.storagepool+xml") + @JAXBResponseParser + ListenableFuture updateStoragePool( + @EndpointLink("edit") @BinderParam(BindToXMLPayloadAndPath.class) StoragePoolDto StoragePoolDto); + + /** + * @see InfrastructureApi#deleteStoragePool(StoragePoolDto) + */ + @EnterpriseEdition + @DELETE + ListenableFuture deleteStoragePool( + @EndpointLink("edit") @BinderParam(BindToPath.class) StoragePoolDto storagePool); + + /** + * @see InfrastructureApi#getStoragePool(StorageDeviceDto, String) + */ + @EnterpriseEdition + @GET + @Consumes(StoragePoolDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + ListenableFuture getStoragePool( + @EndpointLink("pools") @BinderParam(BindToPath.class) final StorageDeviceDto storageDevice, + @BinderParam(AppendToPath.class) final String storagePoolId); + + /** + * @see InfrastructureApi#refreshStoragePool(StoragePoolDto, + * StoragePoolOptions) + */ + @EnterpriseEdition + @GET + @Consumes(StoragePoolDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture refreshStoragePool( + @EndpointLink("edit") @BinderParam(BindToPath.class) StoragePoolDto storagePool, StoragePoolOptions options); + + /*********************** Network ***********************/ + + /** + * @see InfrastructureApi#listNetworks(DatacenterDto) + */ + @EnterpriseEdition + @GET + @Consumes(VLANNetworksDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listNetworks( + @EndpointLink("network") @BinderParam(BindToPath.class) DatacenterDto datacenter); + + /** + * @see InfrastructureApi#listNetwork(DatacenterDto, NetworkOptions) + */ + @EnterpriseEdition + @GET + @Consumes(VLANNetworksDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listNetworks( + @EndpointLink("network") @BinderParam(BindToPath.class) DatacenterDto datacenter, NetworkOptions options); + + /** + * @see InfrastructureApi#getNetwork(DatacenterDto, Integer) + */ + @EnterpriseEdition + @GET + @Consumes(VLANNetworkDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + ListenableFuture getNetwork( + @EndpointLink("network") @BinderParam(BindToPath.class) DatacenterDto datacenter, + @BinderParam(AppendToPath.class) Integer networkId); + + /** + * @see InfrastructureApi#createNetwork(DatacenterDto, VLANNetworkDto) + */ + @EnterpriseEdition + @POST + @Produces(VLANNetworkDto.BASE_MEDIA_TYPE) + @Consumes(VLANNetworkDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture createNetwork( + @EndpointLink("network") @BinderParam(BindToPath.class) DatacenterDto datacenter, + @BinderParam(BindToXMLPayload.class) VLANNetworkDto network); + + /** + * @see InfrastructureApi#updateNetwork(VLANNetworkDto) + */ + @EnterpriseEdition + @PUT + @Produces(VLANNetworkDto.BASE_MEDIA_TYPE) + @Consumes(VLANNetworkDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture updateNetwork( + @EndpointLink("edit") @BinderParam(BindToXMLPayloadAndPath.class) VLANNetworkDto network); + + /** + * @see InfrastructureApi#deleteNetwork(VLANNetworkDto) + */ + @EnterpriseEdition + @DELETE + ListenableFuture deleteNetwork(@EndpointLink("edit") @BinderParam(BindToPath.class) VLANNetworkDto network); + + /** + * @see InfrastructureApi#checkTagAvailability(DatacenterDto, Integer) + */ + @EnterpriseEdition + @GET + @Path("/datacenters/{datacenter}/network/action/checkavailability") + @Consumes(VlanTagAvailabilityDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture checkTagAvailability( + @PathParam("datacenter") @ParamParser(ParseDatacenterId.class) DatacenterDto datacenter, + @QueryParam("tag") Integer tag); + + /*********************** Public Network IPs ***********************/ + + /** + * @see InfrastructureApi#listPublicIps(VLANNetworkDto) + */ + @GET + @Consumes(PublicIpsDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listPublicIps( + @EndpointLink("ips") @BinderParam(BindToPath.class) VLANNetworkDto network); + + /** + * @see InfrastructureApi#listPublicIps(VLANNetworkDto, IpOptions) + */ + @GET + @Consumes(PublicIpsDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listPublicIps( + @EndpointLink("ips") @BinderParam(BindToPath.class) VLANNetworkDto network, IpOptions options); + + /** + * @see InfrastructureApi#getPublicIp(VLANNetworkDto, Integer) + */ + @GET + @Consumes(PublicIpDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture getPublicIp( + @EndpointLink("ips") @BinderParam(BindToPath.class) VLANNetworkDto network, + @BinderParam(AppendToPath.class) Integer ipId); + + /** + * @see InfrastructureApi#listExternalIps(VLANNetworkDto) + */ + @GET + @Consumes(ExternalIpsDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listExternalIps( + @EndpointLink("ips") @BinderParam(BindToPath.class) VLANNetworkDto network); + + /** + * @see InfrastructureApi#listExternalIps(VLANNetworkDto, IpOptions) + */ + @GET + @Consumes(ExternalIpsDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listExternalIps( + @EndpointLink("ips") @BinderParam(BindToPath.class) VLANNetworkDto network, IpOptions options); + + /** + * @see InfrastructureApi#getExternalIp(VLANNetworkDto, Integer) + */ + @GET + @Consumes(ExternalIpDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture getExternalIp( + @EndpointLink("ips") @BinderParam(BindToPath.class) VLANNetworkDto network, + @BinderParam(AppendToPath.class) Integer ipId); + + /** + * @see InfrastructureApi#listUnmanagedIps(VLANNetworkDto) + */ + @GET + @Consumes(UnmanagedIpsDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listUnmanagedIps( + @EndpointLink("ips") @BinderParam(BindToPath.class) VLANNetworkDto network); + + /** + * @see InfrastructureApi#listUnmanagedIps(VLANNetworkDto, IpOptions) + */ + @GET + @Consumes(UnmanagedIpsDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listUnmanagedIps( + @EndpointLink("ips") @BinderParam(BindToPath.class) VLANNetworkDto network, IpOptions options); + + /** + * @see InfrastructureApi#getUnmanagedIp(VLANNetworkDto, Integer) + */ + @GET + @Consumes(UnmanagedIpDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture getUnmanagedIp( + @EndpointLink("ips") @BinderParam(BindToPath.class) VLANNetworkDto network, + @BinderParam(AppendToPath.class) Integer ipId); +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/features/PricingApi.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/features/PricingApi.java new file mode 100644 index 0000000000..d52734d08a --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/features/PricingApi.java @@ -0,0 +1,257 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.abiquo.features; + +import java.util.concurrent.TimeUnit; + +import org.jclouds.concurrent.Timeout; + +import com.abiquo.server.core.pricing.CostCodeCurrenciesDto; +import com.abiquo.server.core.pricing.CostCodeDto; +import com.abiquo.server.core.pricing.CostCodesDto; +import com.abiquo.server.core.pricing.CurrenciesDto; +import com.abiquo.server.core.pricing.CurrencyDto; +import com.abiquo.server.core.pricing.PricingCostCodeDto; +import com.abiquo.server.core.pricing.PricingCostCodesDto; +import com.abiquo.server.core.pricing.PricingTemplateDto; +import com.abiquo.server.core.pricing.PricingTemplatesDto; +import com.abiquo.server.core.pricing.PricingTierDto; +import com.abiquo.server.core.pricing.PricingTiersDto; + +/** + * Provides synchronous access to Abiquo Pricing API. + * + * @see API: + * http://community.abiquo.com/display/ABI20/APIReference + * @see PricingAsyncApi + * @author Ignasi Barrera + * @author Susana Acedo + */ +@Timeout(duration = 30, timeUnit = TimeUnit.SECONDS) +public interface PricingApi { + + /*********************** Currency ********************** */ + + /** + * List all currencies + * + * @return The list of currencies + */ + CurrenciesDto listCurrencies(); + + /** + * Get the given currency + * + * @param currencyId + * The id of the currency + * @return The currency + */ + CurrencyDto getCurrency(Integer currencyId); + + /** + * Create a new currency + * + * @param currency + * The currency to be created. + * @return The created currency. + */ + CurrencyDto createCurrency(CurrencyDto currency); + + /** + * Updates an existing currency + * + * @param currency + * The new attributes for the currency + * @return The updated currency + */ + CurrencyDto updateCurrency(final CurrencyDto currency); + + /** + * Deletes an existing currency + * + * @param currency + * The currency to delete + */ + void deleteCurrency(final CurrencyDto currency); + + /*********************** CostCode ********************** */ + + /** + * List all costcodes + * + * @return The list of costcodes + */ + CostCodesDto listCostCodes(); + + /** + * Get the given costcode + * + * @param costcodeId + * The id of the costcode + * @return The costcode + */ + CostCodeDto getCostCode(Integer costcodeId); + + /** + * Create a new costcode + * + * @param costcode + * The costcode to be created. + * @return The created costcode. + */ + CostCodeDto createCostCode(CostCodeDto costcode); + + /** + * Updates an existing costcode + * + * @param costcode + * The new attributes for the costcode + * @return The updated costcode + */ + CostCodeDto updateCostCode(CostCodeDto costcode); + + /** + * Deletes an existing costcode + * + * @param currency + * The costcode to delete + */ + void deleteCostCode(CostCodeDto costcode); + + /*********************** PricingTemplate ********************** */ + + /** + * List all pricingtemplates + * + * @return The list of pricingtemplates + */ + PricingTemplatesDto listPricingTemplates(); + + /** + * Get the given pricingtemplate + * + * @param pricingTemplateId + * The id of the pricingtemplate + * @return The pricingtemplate + */ + PricingTemplateDto getPricingTemplate(Integer pricingTemplateId); + + /** + * Create a new pricing template + * + * @param pricingtemplate + * The pricingtemplate to be created + * @return The created pricingtemplate + */ + PricingTemplateDto createPricingTemplate(PricingTemplateDto pricingtemplate); + + /** + * Updates an existing pricing template + * + * @param pricingtemplate + * The new attributes for the pricingtemplate + * @return The updated pricingtemplate + */ + PricingTemplateDto updatePricingTemplate(PricingTemplateDto pricingtemplate); + + /** + * Deletes an existing pricingtemplate + * + * @param pricingtemplate + * The pricingtemplate to delete + */ + void deletePricingTemplate(PricingTemplateDto pricingtemplate); + + /*********************** CostCodeCurrency ********************** */ + + /** + * Get the given costcodecurrency + * + * @param costcodecurrencyId + * The id of the costcodecurrency + * @return The costcodecurrency + */ + CostCodeCurrenciesDto getCostCodeCurrencies(Integer costcodeId, Integer currencyId); + + /** + * Updates cost code currencies + * + * @param costcodeCurrency + * The new attributes for the costcodecurrencies + * @return The updated costcodecurrencies + */ + CostCodeCurrenciesDto updateCostCodeCurrencies(Integer costcodeId, CostCodeCurrenciesDto costcodeCurrencies); + + /*********************** PricingTemplateCostCode ********************** */ + + /** + * Get the pricing cost codes for a pricing template + * + * @param pricingTemplateId + * @return pricingcostcodes + */ + PricingCostCodesDto getPricingCostCodes(Integer pricingTemplateId); + + /** + * Get the given pricing cost code + * + * @param pricingCostCodeId + * the id of the pricing cost code + * @return The pricingcostcode + */ + PricingCostCodeDto getPricingCostCode(Integer pricingTemplateId, Integer pricingCostCodeId); + + /** + * Updates an existing pricingcostcode + * + * @param costcodeCurrency + * The new attributes for the pricingcostcode + * @return The updated pricingcostcode + */ + PricingCostCodeDto updatePricingCostCode(PricingCostCodeDto pricingCostCode, Integer pricingTemplateId, + Integer pricingCostCodeId); + + /*********************** PricingTemplateTier ********************** */ + + /** + * Get the pricing tiers for a pricing template + * + * @param pricingTemplateId + * @return pricingtiers + */ + PricingTiersDto getPricingTiers(Integer pricingTemplateId); + + /** + * Get the given pricing tier + * + * @param pricingTierId + * The id of the pricing tier + * @return The pricingtier + */ + PricingTierDto getPricingTier(Integer pricingTemplateId, Integer pricingTierId); + + /** + * Updates an existing pricing tier + * + * @param costcodeCurrency + * The new attributes for the pricing tier + * @return The updated pricing tier + */ + PricingTierDto updatePricingTier(PricingTierDto pricingTier, Integer pricingTemplateId, Integer pricingTierId); +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/features/PricingAsyncApi.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/features/PricingAsyncApi.java new file mode 100644 index 0000000000..952c7c483e --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/features/PricingAsyncApi.java @@ -0,0 +1,304 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.abiquo.features; + +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 javax.ws.rs.QueryParam; + +import org.jclouds.abiquo.binders.BindToPath; +import org.jclouds.abiquo.binders.BindToXMLPayloadAndPath; +import org.jclouds.abiquo.http.filters.AbiquoAuthentication; +import org.jclouds.abiquo.http.filters.AppendApiVersionToMediaType; +import org.jclouds.abiquo.rest.annotations.EndpointLink; +import org.jclouds.rest.annotations.BinderParam; +import org.jclouds.rest.annotations.ExceptionParser; +import org.jclouds.rest.annotations.JAXBResponseParser; +import org.jclouds.rest.annotations.RequestFilters; +import org.jclouds.rest.binders.BindToXMLPayload; +import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; + +import com.abiquo.server.core.pricing.CostCodeCurrenciesDto; +import com.abiquo.server.core.pricing.CostCodeDto; +import com.abiquo.server.core.pricing.CostCodesDto; +import com.abiquo.server.core.pricing.CurrenciesDto; +import com.abiquo.server.core.pricing.CurrencyDto; +import com.abiquo.server.core.pricing.PricingCostCodeDto; +import com.abiquo.server.core.pricing.PricingCostCodesDto; +import com.abiquo.server.core.pricing.PricingTemplateDto; +import com.abiquo.server.core.pricing.PricingTemplatesDto; +import com.abiquo.server.core.pricing.PricingTierDto; +import com.abiquo.server.core.pricing.PricingTiersDto; +import com.google.common.util.concurrent.ListenableFuture; + +/** + * Provides synchronous access to Abiquo Pricing API. + * + * @see API: + * http://community.abiquo.com/display/ABI20/APIReference + * @see PricingAsyncApi + * @author Ignasi Barrera + * @author Susana Acedo + */ +@RequestFilters({ AbiquoAuthentication.class, AppendApiVersionToMediaType.class }) +@Path("/config") +public interface PricingAsyncApi { + /*********************** Currency ********************** */ + + /** + * @see ConfigApi#listCurrencies() + */ + @GET + @Path("/currencies") + @Consumes(CurrenciesDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listCurrencies(); + + /** + * @see ConfigApi#getCurrency(Integer) + */ + @GET + @Path("/currencies/{currency}") + @Consumes(CurrencyDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + ListenableFuture getCurrency(@PathParam("currency") Integer currencyId); + + /** + * @see ConfigApi#createCurrency(CurrencyDto) + */ + @POST + @Path("/currencies") + @Produces(CurrencyDto.BASE_MEDIA_TYPE) + @Consumes(CurrencyDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture createCurrency(@BinderParam(BindToXMLPayload.class) CurrencyDto currency); + + /** + * @see ConfigApi#updateCurrency(CurrencyDto) + */ + @PUT + @Produces(CurrencyDto.BASE_MEDIA_TYPE) + @Consumes(CurrencyDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture updateCurrency( + @EndpointLink("edit") @BinderParam(BindToXMLPayloadAndPath.class) CurrencyDto currency); + + /** + * @see ConfigApi#deleteCurrency(CurrencyDto) + */ + @DELETE + ListenableFuture deleteCurrency(@EndpointLink("edit") @BinderParam(BindToPath.class) CurrencyDto currency); + + /*********************** CostCode ********************** */ + + /** + * @see PricingApi#listCostCodes() + */ + @GET + @Path("/costcodes") + @Consumes(CostCodesDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listCostCodes(); + + /** + * @see PricingApi#getCostCode(Integer) + */ + @GET + @Path("/costcodes/{costcode}") + @Consumes(CostCodeDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + ListenableFuture getCostCode(@PathParam("costcode") Integer costcodeId); + + /** + * @see PricingApi#createCostCode(CostCodeDto) + */ + @POST + @Path("/costcodes") + @Produces(CostCodeDto.BASE_MEDIA_TYPE) + @Consumes(CostCodeDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture createCostCode(@BinderParam(BindToXMLPayload.class) CostCodeDto costcode); + + /** + * @see PricingApi#updateCostCode(CostCodeDto) + */ + @PUT + @Produces(CostCodeDto.BASE_MEDIA_TYPE) + @Consumes(CostCodeDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture updateCostCode( + @EndpointLink("edit") @BinderParam(BindToXMLPayloadAndPath.class) CostCodeDto costcode); + + /** + * @see PricingApi#deleteCostCode(CostCodeDto) + */ + @DELETE + ListenableFuture deleteCostCode(@EndpointLink("edit") @BinderParam(BindToPath.class) CostCodeDto costcode); + + /*********************** PricingTemplate ********************** */ + + /** + * @see PricingApi#listPricingTemplates() + */ + @GET + @Path("/pricingtemplates") + @Consumes(PricingTemplatesDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listPricingTemplates(); + + /** + * @see PricingApi#getPricingTemplate(Integer) + */ + @GET + @Path("/pricingtemplates/{pricingtemplate}") + @Consumes(PricingTemplateDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + ListenableFuture getPricingTemplate(@PathParam("pricingtemplate") Integer pricingTemplateId); + + /** + * @see PricingApi#createPricingTemplate(PricingTemplateDto) + */ + @POST + @Path("/pricingtemplates") + @Produces(PricingTemplateDto.BASE_MEDIA_TYPE) + @Consumes(PricingTemplateDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture createPricingTemplate( + @BinderParam(BindToXMLPayload.class) PricingTemplateDto pricingtemplate); + + /** + * @see PricingApi#updatePricingTemplate(PricingTemplateDto) + */ + @PUT + @Produces(PricingTemplateDto.BASE_MEDIA_TYPE) + @Consumes(PricingTemplateDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture updatePricingTemplate( + @EndpointLink("edit") @BinderParam(BindToXMLPayloadAndPath.class) PricingTemplateDto pricingtemplate); + + /** + * @see PricingApi#deletePricingTemplate(PricingTemplateDto) + */ + @DELETE + ListenableFuture deletePricingTemplate( + @EndpointLink("edit") @BinderParam(BindToPath.class) PricingTemplateDto pricingtemplate); + + /*********************** CostCodeCurrency ********************** */ + + /** + * @see PricingApi#getCostCodeCurrency(Integer) + */ + @GET + @Path("/costcodes/{costcode}/currencies") + @Consumes(CostCodeCurrenciesDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + ListenableFuture getCostCodeCurrencies(@PathParam("costcode") Integer costcodeId, + @QueryParam("idCurrency") Integer currencyId); + + /** + * @see PricingApi#updateCostCodeCurrencies(CostCodeCurrenciesDto) + */ + @PUT + @Path("/costcodes/{costcode}/currencies") + @Produces(CostCodeCurrenciesDto.BASE_MEDIA_TYPE) + @Consumes(CostCodeCurrenciesDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture updateCostCodeCurrencies(@PathParam("costcode") Integer costcodeId, + @BinderParam(BindToXMLPayload.class) CostCodeCurrenciesDto costcodecurrencies); + + /*********************** PricingCostCode ********************** */ + + /** + * @see PricingApi#getPricingCostCodes(Integer) + */ + @GET + @Path("/pricingtemplates/{pricingtemplate}/costcodes") + @Consumes(PricingCostCodesDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + ListenableFuture getPricingCostCodes(@PathParam("pricingtemplate") Integer pricingTemplateId); + + /** + * @see PricingApi#getPricingCostCode(Integer) + */ + @GET + @Path("/pricingtemplates/{pricingtemplate}/costcodes/{costcode}") + @Consumes(PricingCostCodeDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + ListenableFuture getPricingCostCode(@PathParam("pricingtemplate") Integer pricingTemplateId, + @PathParam("costcode") Integer pricingCostcodeId); + + /** + * @see PricingApi#updatePricingCostCode(PricingCostCodeDto) + */ + @PUT + @Path("/pricingtemplates/{pricingtemplate}/costcodes/{costcode}") + @Produces(PricingCostCodeDto.BASE_MEDIA_TYPE) + @Consumes(PricingCostCodeDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture updatePricingCostCode( + @EndpointLink("edit") @BinderParam(BindToXMLPayloadAndPath.class) PricingCostCodeDto pricingcostcode, + @PathParam("pricingtemplate") Integer pricingTemplateId, @PathParam("costcode") Integer pricingCostcodeId); + + /*********************** PricingTier ********************** */ + + /** + * @see PricingApi#getPricingTiers(Integer) + */ + @GET + @Path("/pricingtemplates/{pricingtemplate}/tiers") + @Consumes(PricingTiersDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + ListenableFuture getPricingTiers(@PathParam("pricingtemplate") Integer pricingTemplateId); + + /** + * @see PricingApi#getPricingTier(Integer) + */ + @GET + @Path("/pricingtemplates/{pricingtemplate}/tiers/{tier}") + @Consumes(PricingTierDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + ListenableFuture getPricingTier(@PathParam("pricingtemplate") Integer pricingTemplateId, + @PathParam("tier") Integer pricingTierId); + + /** + * @see PricingApi#updatePricingTier(PricingTierDto) + */ + @PUT + @Path("/pricingtemplates/{pricingtemplate}/tiers/{tier}") + @Produces(PricingTierDto.BASE_MEDIA_TYPE) + @Consumes(PricingTierDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture updatePricingTier( + @EndpointLink("edit") @BinderParam(BindToXMLPayloadAndPath.class) PricingTierDto pricingtier, + @PathParam("pricingtemplate") Integer pricingTemplateId, @PathParam("tier") Integer pricingTierId); +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/features/TaskApi.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/features/TaskApi.java new file mode 100644 index 0000000000..cb4b32423a --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/features/TaskApi.java @@ -0,0 +1,61 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.features; + +import java.util.concurrent.TimeUnit; + +import org.jclouds.concurrent.Timeout; + +import com.abiquo.model.rest.RESTLink; +import com.abiquo.model.transport.SingleResourceTransportDto; +import com.abiquo.server.core.task.TaskDto; +import com.abiquo.server.core.task.TasksDto; + +/** + * Provides synchronous access to Abiquo Task API. + * + * @see API: + * http://community.abiquo.com/display/ABI20/API+Reference + * @see TaskAsyncApi + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +@Timeout(duration = 30, timeUnit = TimeUnit.SECONDS) +public interface TaskApi { + /*********************** Task ***********************/ + + /** + * Get a task from its link. + * + * @param link + * The link of the task. + * @return The task. + */ + TaskDto getTask(final RESTLink link); + + /** + * Get the list of tasks of the given object. + * + * @param dto + * The object. + * @return The list of tasks for the given object. + */ + TasksDto listTasks(T dto); +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/features/TaskAsyncApi.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/features/TaskAsyncApi.java new file mode 100644 index 0000000000..9d5531dc63 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/features/TaskAsyncApi.java @@ -0,0 +1,72 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.features; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; + +import org.jclouds.abiquo.binders.BindLinkToPath; +import org.jclouds.abiquo.binders.BindToPath; +import org.jclouds.abiquo.functions.ReturnNullOn303; +import org.jclouds.abiquo.http.filters.AbiquoAuthentication; +import org.jclouds.abiquo.http.filters.AppendApiVersionToMediaType; +import org.jclouds.abiquo.rest.annotations.EndpointLink; +import org.jclouds.rest.annotations.BinderParam; +import org.jclouds.rest.annotations.ExceptionParser; +import org.jclouds.rest.annotations.JAXBResponseParser; +import org.jclouds.rest.annotations.RequestFilters; + +import com.abiquo.model.rest.RESTLink; +import com.abiquo.model.transport.SingleResourceTransportDto; +import com.abiquo.server.core.task.TaskDto; +import com.abiquo.server.core.task.TasksDto; +import com.google.common.util.concurrent.ListenableFuture; + +/** + * Provides asynchronous access to Abiquo Task API. + * + * @see API: + * http://community.abiquo.com/display/ABI20/API+Reference + * @see TaskApi + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +@RequestFilters({ AbiquoAuthentication.class, AppendApiVersionToMediaType.class }) +public interface TaskAsyncApi { + /*********************** Task ***********************/ + + /** + * @see TaskApi#getTask(RESTLink) + */ + @GET + @Consumes(TaskDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + @ExceptionParser(ReturnNullOn303.class) + ListenableFuture getTask(@BinderParam(BindLinkToPath.class) RESTLink link); + + /** + * @see TaskApi#listTasks(SingleResourceTransportDto) + */ + @GET + @Consumes(TasksDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listTasks( + @EndpointLink("tasks") @BinderParam(BindToPath.class) T dto); +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/features/VirtualMachineTemplateApi.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/features/VirtualMachineTemplateApi.java new file mode 100644 index 0000000000..3c8237ace5 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/features/VirtualMachineTemplateApi.java @@ -0,0 +1,176 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.features; + +import java.util.concurrent.TimeUnit; + +import org.jclouds.abiquo.domain.cloud.options.ConversionOptions; +import org.jclouds.abiquo.domain.cloud.options.VirtualMachineTemplateOptions; +import org.jclouds.concurrent.Timeout; + +import com.abiquo.model.enumerator.DiskFormatType; +import com.abiquo.model.transport.AcceptedRequestDto; +import com.abiquo.server.core.appslibrary.ConversionDto; +import com.abiquo.server.core.appslibrary.ConversionsDto; +import com.abiquo.server.core.appslibrary.VirtualMachineTemplateDto; +import com.abiquo.server.core.appslibrary.VirtualMachineTemplatePersistentDto; +import com.abiquo.server.core.appslibrary.VirtualMachineTemplatesDto; + +/** + * Provides synchronous access to Abiquo Apps library API. + * + * @see API: + * http://community.abiquo.com/display/ABI20/API+Reference + * @see VirtualMachineTemplateAsyncApi + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +@Timeout(duration = 60, timeUnit = TimeUnit.SECONDS) +public interface VirtualMachineTemplateApi { + /*********************** Virtual Machine Template ***********************/ + + /** + * List all virtual machine templates for an enterprise in a datacenter + * repository. + * + * @param enterpriseId + * Id of the enterprise. + * @param datacenterRepositoryId + * Id of the datacenter repository contaning the templates. + * @return The list of virtual machine templates for the enterprise in the + * datacenter repository. + */ + VirtualMachineTemplatesDto listVirtualMachineTemplates(Integer enterpriseId, Integer datacenterRepositoryId); + + /** + * List all virtual machine templates for an enterprise in a datacenter + * repository. + * + * @param enterpriseId + * Id of the enterprise. + * @param datacenterRepositoryId + * Id of the datacenter repository contaning the templates. + * @param options + * The options to query the virtual machine templates. + * @return The filtered list of virtual machine templates for the enterprise + * in the datacenter repository. + */ + VirtualMachineTemplatesDto listVirtualMachineTemplates(Integer enterpriseId, Integer datacenterRepositoryId, + VirtualMachineTemplateOptions options); + + /** + * Get the given virtual machine template. + * + * @param enterpriseId + * Id of the enterprise. + * @param datacenterRepositoryId + * Id of the datacenter repository contaning the templates. + * @param enterpriseId + * The id of the virtual machine template. + * @return The virtual machine template or null if it does not + * exist. + */ + VirtualMachineTemplateDto getVirtualMachineTemplate(Integer entepriseId, Integer datacenterRepositoryId, + Integer virtualMachineTemplateId); + + /** + * Updates an existing virtual machine template. + * + * @param template + * The new attributes for the template. + * @return The updated template. + */ + VirtualMachineTemplateDto updateVirtualMachineTemplate(VirtualMachineTemplateDto template); + + /** + * Deletes an existing virtual machine template. + * + * @param template + * The virtual machine template to delete. + */ + void deleteVirtualMachineTemplate(VirtualMachineTemplateDto template); + + /** + * Creates a persistent virtual machine template from other virtual machine + * template. + * + * @param dcRepository + * The repository where the persistent virtual machine template + * will be created. + * @param options + * The persistent options like name, volume/tier, virtual + * datacenter and original template. + * @return Response message to the persistent request. + */ + @Timeout(duration = 90, timeUnit = TimeUnit.SECONDS) + AcceptedRequestDto createPersistentVirtualMachineTemplate(Integer enterpriseId, + Integer datacenterRepositoryId, VirtualMachineTemplatePersistentDto persistentOptions); + + /** + * List all the conversions for a virtual machine template. + * + * @param template + * , The virtual machine template of the conversions. + * @return The list of conversions for the virtual machine template. + */ + ConversionsDto listConversions(VirtualMachineTemplateDto template); + + /** + * List conversions for a virtual machine template. + * + * @param template + * , The virtual machine template of the conversions + * @param options + * , Optionally filter compatible conversions with a provided + * hypervisor or with the desired state. + * @return The list of conversions for the virtual machine template with the + * applied constrains. + */ + ConversionsDto listConversions(VirtualMachineTemplateDto template, ConversionOptions options); + + /** + * Get the conversions for a virtual machine template and the desired target + * format. + * + * @param template + * , The virtual machine template of the conversion + * @param targetFormat + * The disk format type of the requested conversion + * @return The conversions for the virtual machine template with the desired + * target disk format type. + */ + ConversionDto getConversion(VirtualMachineTemplateDto template, DiskFormatType targetFormat); + + /** + * Starts a V2V conversion of the current virtual machine template, or + * updates a failed conversion. + * + * @param template + * The virtual machine template to convert + * @param targetFormat + * The requested target {@link DiskFormatType} of the conversion. + * @param conversion + * , the dto representing the conversion + * @return an accepted request with a link to track the progress of the + * conversion tasks. + */ + AcceptedRequestDto requestConversion(VirtualMachineTemplateDto template, DiskFormatType targetFormat, + ConversionDto conversion); +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/features/VirtualMachineTemplateAsyncApi.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/features/VirtualMachineTemplateAsyncApi.java new file mode 100644 index 0000000000..88497766e7 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/features/VirtualMachineTemplateAsyncApi.java @@ -0,0 +1,185 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.features; + +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.abiquo.binders.AppendToPath; +import org.jclouds.abiquo.binders.BindToPath; +import org.jclouds.abiquo.binders.BindToXMLPayloadAndPath; +import org.jclouds.abiquo.domain.cloud.options.ConversionOptions; +import org.jclouds.abiquo.domain.cloud.options.VirtualMachineTemplateOptions; +import org.jclouds.abiquo.functions.ReturnTaskReferenceOrNull; +import org.jclouds.abiquo.http.filters.AbiquoAuthentication; +import org.jclouds.abiquo.http.filters.AppendApiVersionToMediaType; +import org.jclouds.abiquo.rest.annotations.EndpointLink; +import org.jclouds.rest.annotations.BinderParam; +import org.jclouds.rest.annotations.ExceptionParser; +import org.jclouds.rest.annotations.JAXBResponseParser; +import org.jclouds.rest.annotations.RequestFilters; +import org.jclouds.rest.annotations.ResponseParser; +import org.jclouds.rest.binders.BindToXMLPayload; +import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; + +import com.abiquo.model.enumerator.DiskFormatType; +import com.abiquo.model.transport.AcceptedRequestDto; +import com.abiquo.server.core.appslibrary.ConversionDto; +import com.abiquo.server.core.appslibrary.ConversionsDto; +import com.abiquo.server.core.appslibrary.DatacenterRepositoryDto; +import com.abiquo.server.core.appslibrary.VirtualMachineTemplateDto; +import com.abiquo.server.core.appslibrary.VirtualMachineTemplatePersistentDto; +import com.abiquo.server.core.appslibrary.VirtualMachineTemplatesDto; +import com.google.common.util.concurrent.ListenableFuture; + +/** + * Provides asynchronous access to Abiquo Abiquo Apps library API. * @see API: + * + * http://community.abiquo.com/display/ABI20/API+Reference + * + * @see VirtualMachineTemplateApi + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +@RequestFilters({ AbiquoAuthentication.class, AppendApiVersionToMediaType.class }) +@Path("/admin/enterprises") +public interface VirtualMachineTemplateAsyncApi { + /*********************** Virtual Machine Template ***********************/ + + /** + * @see VirtualMachineTemplateApi#listVirtualMachineTemplates(Integer, + * Integer) + */ + @GET + @Path("/{enterprise}/datacenterrepositories/{datacenterrepository}/virtualmachinetemplates") + @Consumes(VirtualMachineTemplatesDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listVirtualMachineTemplates( + @PathParam("enterprise") Integer enterpriseId, + @PathParam("datacenterrepository") Integer datacenterRepositoryId); + + /** + * @see VirtualMachineTemplateApi#listVirtualMachineTemplates(Integer, + * Integer, VirtualMachineTemplateOptions) + */ + @GET + @Path("/{enterprise}/datacenterrepositories/{datacenterrepository}/virtualmachinetemplates") + @Consumes(VirtualMachineTemplatesDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listVirtualMachineTemplates( + @PathParam("enterprise") Integer enterpriseId, + @PathParam("datacenterrepository") Integer datacenterRepositoryId, VirtualMachineTemplateOptions options); + + /** + * @see VirtualMachineTemplateApi#getVirtualMachineTemplate(Integer, Integer, + * Integer) + */ + @GET + @Path("/{enterprise}/datacenterrepositories/{datacenterrepository}/virtualmachinetemplates/{virtualmachinetemplate}") + @Consumes(VirtualMachineTemplateDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + ListenableFuture getVirtualMachineTemplate(@PathParam("enterprise") Integer enterpriseId, + @PathParam("datacenterrepository") Integer datacenterRepositoryId, + @PathParam("virtualmachinetemplate") Integer virtualMachineTemplateId); + + /** + * @see VirtualMachineTemplateApi#updateVirtualMachineTemplate(VirtualMachineTemplateDto) + */ + @PUT + @Produces(VirtualMachineTemplateDto.BASE_MEDIA_TYPE) + @Consumes(VirtualMachineTemplateDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture updateVirtualMachineTemplate( + @EndpointLink("edit") @BinderParam(BindToXMLPayloadAndPath.class) VirtualMachineTemplateDto template); + + /** + * @see VirtualMachineTemplateApi#deleteVirtualMachineTemplate(VirtualMachineTemplateDto) + */ + @DELETE + ListenableFuture deleteVirtualMachineTemplate( + @EndpointLink("edit") @BinderParam(BindToPath.class) VirtualMachineTemplateDto template); + + /** + * @see VirtualMachineTemplateApi#createPersistentVirtualMachineTemplate(DatacenterRepositoryDto, + * VirtualMachineTemplatePersistentDto) + */ + @POST + @Consumes(AcceptedRequestDto.BASE_MEDIA_TYPE) + @Produces(VirtualMachineTemplatePersistentDto.BASE_MEDIA_TYPE) + @Path("/{enterprise}/datacenterrepositories/{datacenterrepository}/virtualmachinetemplates") + @JAXBResponseParser + ListenableFuture> createPersistentVirtualMachineTemplate( + @PathParam("enterprise") Integer enterpriseId, + @PathParam("datacenterrepository") Integer datacenterRepositoryId, + @BinderParam(BindToXMLPayload.class) VirtualMachineTemplatePersistentDto persistentOptions); + + /*********************** Conversions ***********************/ + + /** + * @see VirtualMachineTemplateApi#listConversions(VirtualMachineTemplateDto) + */ + @GET + @Consumes(ConversionsDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listConversions( + @EndpointLink("conversions") @BinderParam(BindToPath.class) VirtualMachineTemplateDto template); + + /** + * @see VirtualMachineTemplateApi#listConversions(VirtualMachineTemplateDto, + * ConversionOptions) + */ + @GET + @Consumes(ConversionsDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + ListenableFuture listConversions( + @EndpointLink("conversions") @BinderParam(BindToPath.class) final VirtualMachineTemplateDto template, + ConversionOptions options); + + /** + * @see VirtualMachineTemplateApi#getConversion(VirtualMachineTemplateDto, + * DiskFormatType) + */ + @GET + @Consumes(ConversionDto.BASE_MEDIA_TYPE) + @JAXBResponseParser + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + ListenableFuture getConversion( + @EndpointLink("conversions") @BinderParam(BindToPath.class) final VirtualMachineTemplateDto template, + @BinderParam(AppendToPath.class) DiskFormatType targetFormat); + + /** + * @see VirtualMachineTemplateApi#updateConversion(ConversinoDto) + */ + @PUT + @ResponseParser(ReturnTaskReferenceOrNull.class) + @Consumes(AcceptedRequestDto.BASE_MEDIA_TYPE) + @Produces(ConversionDto.BASE_MEDIA_TYPE) + ListenableFuture> requestConversion( + @EndpointLink("conversions") @BinderParam(BindToPath.class) final VirtualMachineTemplateDto template, + @BinderParam(AppendToPath.class) DiskFormatType targetFormat, + @BinderParam(BindToXMLPayload.class) ConversionDto conversion); +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/features/services/AdministrationService.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/features/services/AdministrationService.java new file mode 100644 index 0000000000..a6648d171e --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/features/services/AdministrationService.java @@ -0,0 +1,248 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.features.services; + +import java.util.List; + +import org.jclouds.abiquo.domain.config.Category; +import org.jclouds.abiquo.domain.config.License; +import org.jclouds.abiquo.domain.config.Privilege; +import org.jclouds.abiquo.domain.config.SystemProperty; +import org.jclouds.abiquo.domain.enterprise.Enterprise; +import org.jclouds.abiquo.domain.enterprise.EnterpriseProperties; +import org.jclouds.abiquo.domain.enterprise.Role; +import org.jclouds.abiquo.domain.enterprise.User; +import org.jclouds.abiquo.domain.infrastructure.Datacenter; +import org.jclouds.abiquo.domain.infrastructure.Machine; +import org.jclouds.abiquo.internal.BaseAdministrationService; + +import com.google.common.base.Predicate; +import com.google.inject.ImplementedBy; + +/** + * Provides high level Abiquo administration operations. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +@ImplementedBy(BaseAdministrationService.class) +public interface AdministrationService { + /*********************** Datacenter ***********************/ + + /** + * Get the list of all datacenters. + */ + Iterable listDatacenters(); + + /** + * Get the list of datacenters matching the given filter. + */ + Iterable listDatacenters(final Predicate filter); + + /** + * Get the first datacenter that matches the given filter or + * null if none is found. + */ + Datacenter findDatacenter(final Predicate filter); + + /** + * Get the datacenter with the given id. + */ + Datacenter getDatacenter(final Integer datacenterId); + + /** + * Get the list of datacenters with the given ids. + */ + Iterable getDatacenters(final List datacenterIds); + + /*********************** Machine ***********************/ + + /** + * Get the list of all machines in the infrastructure. + */ + public Iterable listMachines(); + + /** + * Get the list of all machines in the infrastructure matching the given + * filter. + */ + public Iterable listMachines(Predicate filter); + + /** + * Get the first machine in the infrastructure that matches the given filter. + */ + public Machine findMachine(Predicate filter); + + /*********************** Enterprise ***********************/ + + /** + * Get the list of all enterprises. + */ + Iterable listEnterprises(); + + /** + * Get the list of enterprises matching the given filter. + */ + Iterable listEnterprises(final Predicate filter); + + /** + * Get the first enterprises that matches the given filter or + * null if none is found. + */ + Enterprise findEnterprise(final Predicate filter); + + /** + * Get the enterprise with the given id. + */ + Enterprise getEnterprise(final Integer enterpriseId); + + /*********************** Enterprise Properties ***********************/ + /** + * Get the properties of an enterprise. + */ + EnterpriseProperties getEnterpriseProperties(final Enterprise enterprise); + + /*********************** Role ***********************/ + + /** + * Get the list of global roles. + */ + Iterable listRoles(); + + /** + * Get the list of roles matching the given filter. + */ + Iterable listRoles(final Predicate filter); + + /** + * Get the first role that matches the given filter or null if + * none is found. + */ + Role findRole(final Predicate filter); + + /** + * Get the role with the given id. + */ + Role getRole(final Integer roleId); + + /*********************** Privilege ***********************/ + + /** + * Get the list of global privileges. + */ + Iterable listPrivileges(); + + /** + * Get the list of privileges matching the given filter. + */ + Iterable listPrivileges(final Predicate filter); + + /** + * Get the first privilege that matches the given filter or null + * if none is found. + */ + Privilege findPrivilege(final Predicate filter); + + /*********************** User ***********************/ + + /** + * Get the current user. + */ + User getCurrentUser(); + + /** + * Get the enterprise of the current user. + */ + Enterprise getCurrentEnterprise(); + + /*********************** License ***********************/ + + /** + * Get the list of all licenses. + */ + Iterable listLicenses(); + + /** + * Get the list of all active/inactive licenses. + * + * @param active + * Defines if searching for active (true) or inactive + * ( false) licenses. + */ + Iterable listLicenses(boolean active); + + /** + * Get the list of licenses matching the given filter. + */ + Iterable listLicenses(final Predicate filter); + + /** + * Get the first license that matches the given filter or null + * if none is found. + */ + License findLicense(final Predicate filter); + + /*********************** System Properties ***********************/ + + /** + * Get the list of system properties. + */ + Iterable listSystemProperties(); + + /** + * Get the list of system properties matching the given filter. + */ + Iterable listSystemProperties(final Predicate filter); + + /** + * Get the first system property that matches the given filter or + * null if none is found. + */ + SystemProperty findSystemProperty(final Predicate filter); + + /** + * Get the system property with the give name or null if none is + * found. + */ + SystemProperty getSystemProperty(String name); + + /** + * Get the list of system properties with options. + */ + Iterable listSystemProperties(String component); + + /*********************** Category ***********************/ + + /** + * Get the list of categories. + */ + Iterable listCategories(); + + /** + * Get the list of categories matching the given filter. + */ + Iterable listCategories(final Predicate filter); + + /** + * Get the first categories that matches the given filter or + * null if none is found. + */ + Category findCategory(final Predicate filter); +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/features/services/CloudService.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/features/services/CloudService.java new file mode 100644 index 0000000000..9ab79e84c8 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/features/services/CloudService.java @@ -0,0 +1,112 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.features.services; + +import java.util.List; + +import org.jclouds.abiquo.domain.cloud.VirtualAppliance; +import org.jclouds.abiquo.domain.cloud.VirtualDatacenter; +import org.jclouds.abiquo.domain.cloud.VirtualMachine; +import org.jclouds.abiquo.domain.enterprise.Enterprise; +import org.jclouds.abiquo.internal.BaseCloudService; + +import com.google.common.base.Predicate; +import com.google.inject.ImplementedBy; + +/** + * Provides high level Abiquo cloud operations. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +@ImplementedBy(BaseCloudService.class) +public interface CloudService { + /*********************** Virtual Datacenter ***********************/ + + /** + * Get the list of all virtual datacenters. + */ + Iterable listVirtualDatacenters(); + + /** + * Get the list of all virtual datacenters for a pair enterprise-datacenter. + * + * @param enterprise + * The given enterprise. + * @param datacenter + * The given datacenter. + */ + Iterable listVirtualDatacenters(final Enterprise enterprise); + + /** + * Get the list of virtual datacenters matching the given filter. + */ + Iterable listVirtualDatacenters(final Predicate filter); + + /** + * Get the first virtual datacenter that matches the given filter or + * null if none is found. + */ + VirtualDatacenter findVirtualDatacenter(final Predicate filter); + + /** + * Get the virtual datacenter with the given id. + */ + VirtualDatacenter getVirtualDatacenter(final Integer virtualDatacenterId); + + /** + * Get the list of virtual datacenter with the given ids. + */ + Iterable getVirtualDatacenters(final List virtualDatacenterIds); + + /*********************** Virtual Appliance ***********************/ + + /** + * Get the list of all virtual appliances. + */ + Iterable listVirtualAppliances(); + + /** + * Get the list of the virtual appliances matching the given filter. + */ + Iterable listVirtualAppliances(Predicate filter); + + /** + * Get the first virtual appliance that matches the given filter. + */ + VirtualAppliance findVirtualAppliance(Predicate filter); + + /*********************** Virtual Machine ***********************/ + + /** + * Get the list of all virtual machines. + */ + Iterable listVirtualMachines(); + + /** + * Get the list of the virtual machines matching the given filter. + */ + Iterable listVirtualMachines(Predicate filter); + + /** + * Get the first virtual machine that matches the given filter. + */ + VirtualMachine findVirtualMachine(Predicate filter); +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/features/services/EventService.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/features/services/EventService.java new file mode 100644 index 0000000000..37fdaf373c --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/features/services/EventService.java @@ -0,0 +1,45 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.features.services; + +import org.jclouds.abiquo.domain.event.Event; +import org.jclouds.abiquo.domain.event.options.EventOptions; +import org.jclouds.abiquo.internal.BaseEventService; + +import com.google.inject.ImplementedBy; + +/** + * Provides high level Abiquo event operations. + * + * @author Ignasi Barrera + * @author Vivien Mahé + */ +@ImplementedBy(BaseEventService.class) +public interface EventService { + /** + * Get the list of all events. + */ + Iterable listEvents(); + + /** + * Get the list of all events using filters as query params. + */ + Iterable listEvents(EventOptions options); +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/features/services/MonitoringService.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/features/services/MonitoringService.java new file mode 100644 index 0000000000..812134bff3 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/features/services/MonitoringService.java @@ -0,0 +1,151 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.features.services; + +import java.util.concurrent.TimeUnit; + +import org.jclouds.abiquo.events.handlers.AbstractEventHandler; +import org.jclouds.abiquo.internal.BaseMonitoringService; +import org.jclouds.abiquo.monitor.AsyncTaskMonitor; +import org.jclouds.abiquo.monitor.ConversionMonitor; +import org.jclouds.abiquo.monitor.MonitorStatus; +import org.jclouds.abiquo.monitor.VirtualApplianceMonitor; +import org.jclouds.abiquo.monitor.VirtualMachineMonitor; + +import com.google.common.base.Function; +import com.google.inject.ImplementedBy; + +/** + * Utility service to monitor asynchronous operations. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +@ImplementedBy(BaseMonitoringService.class) +public interface MonitoringService { + + /*************** Generic monitoring methods ***************/ + + /** + * Monitor the given objects using the given complete condition. + * + * @param completeCondition + * The function that will be used to decide if the asynchronous + * operations have finished. + * @param objects + * The objects to monitor. + */ + public void awaitCompletion(final Function completeCondition, final T... objects); + + /** + * Monitor the given objects using the given complete condition. + * + * @param maxWait + * The maximum time to wait. + * @param timeUnit + * The time unit for the maxWait parameter. + * @param completeCondition + * The function that will be used to decide if the asynchronous + * operations have finished. + * @param objects + * The objects to monitor. + */ + public void awaitCompletion(final Long maxWait, final TimeUnit timeUnit, + final Function completeCondition, final T... objects); + + /** + * Monitor the given objects using the given complete condition. + * + * @param completeCondition + * The function that will be used to decide if the asynchronous + * operations have finished. + * @param objects + * The objects to monitor. + */ + public void monitor(final Function completeCondition, final T... objects); + + /** + * Monitor the given objects using the given complete condition. + * + * @param maxWait + * The maximum time to wait. + * @param timeUnit + * The time unit for the maxWait parameter. + * @param completeCondition + * The function that will be used to decide if the asynchronous + * operations have finished. + * @param objects + * The objects to monitor. + */ + public void monitor(final Long maxWait, final TimeUnit timeUnit, + final Function completeCondition, final T... objects); + + /*************** Handler registration methods ***************/ + + /** + * Registers the given event handler. + * + * @param + * The type of event handler to register. + * @param handler + * The event handler to register. + */ + public > void register(T handler); + + /** + * Unregisters the given event handler. + * + * @param + * The type of event handler to unregister. + * @param handler + * The event handler to unregister. + */ + public > void unregister(T handler); + + /*************** Delegating monitors ***************/ + + /** + * Gets the virtual machine monitor service. + * + * @return The virtual machine monitor service. + */ + public VirtualMachineMonitor getVirtualMachineMonitor(); + + /** + * Gets the virtual appliance monitor service. + * + * @return The virtual appliance monitor service. + */ + public VirtualApplianceMonitor getVirtualApplianceMonitor(); + + /** + * Gets the asynchronous task monitor service. + * + * @return The asynchronous task monitor service. + */ + public AsyncTaskMonitor getAsyncTaskMonitor(); + + /** + * Gets the conversion monitor service. + * + * @return The conversion monitor service. + */ + public ConversionMonitor getConversionMonitor(); +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/features/services/PricingService.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/features/services/PricingService.java new file mode 100644 index 0000000000..dd26afdb3e --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/features/services/PricingService.java @@ -0,0 +1,129 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.features.services; + +import java.util.Collection; + +import org.jclouds.abiquo.domain.config.CostCode; +import org.jclouds.abiquo.domain.config.CostCodeCurrency; +import org.jclouds.abiquo.domain.config.Currency; +import org.jclouds.abiquo.domain.config.PricingCostCode; +import org.jclouds.abiquo.domain.config.PricingTemplate; +import org.jclouds.abiquo.domain.config.PricingTier; +import org.jclouds.abiquo.internal.BasePricingService; + +import com.google.common.base.Predicate; +import com.google.inject.ImplementedBy; + +/** + * Provides high level Abiquo administration operations. + * + * @author Ignasi Barrera + * @author Susana Acedo + */ +@ImplementedBy(BasePricingService.class) +public interface PricingService { + + /*********************** Currency ***********************/ + + /** + * Get the list of currencies. + */ + Iterable listCurrencies(); + + /** + * Get the list of currencies matching the given filter. + */ + Iterable listCurrencies(final Predicate filter); + + /** + * Get the first currencies that matches the given filter or + * null if none is found. + */ + Currency findCurrency(final Predicate filter); + + /*********************** CostCode ***********************/ + + /** + * Get the list of costcodes. + */ + Iterable listCostCodes(); + + /** + * Get the list of costcodes matching the given filter. + */ + Iterable listCostCodes(final Predicate filter); + + /** + * Get the first costcodes that matches the given filter or null + * if none is found. + */ + CostCode findCostCode(final Predicate filter); + + /*********************** PricingTemplate ***********************/ + + /** + * Get the list of pricingtemplates. + */ + public Iterable listPricingTemplates(); + + /** + * Get the list of pricingtemplates matching the given filter. + */ + public Iterable listPricingTemplates(final Predicate filter); + + /** + * Get the first pricingtemplates that matches the given filter or + * null if none is found. + */ + public PricingTemplate findPricingTemplate(final Predicate filter); + + /*********************** CostCodeCurrency ***********************/ + + /** + * Get a cost code currency + */ + public Iterable getCostCodeCurrencies(Integer costcodeid, Integer currencyid); + + /*********************** PricingCostCode ***********************/ + + /** + * Get pricing cost codes + */ + public Collection getPricingCostCodes(Integer pricingTemplateId); + + /** + * Get a pricing cost code + */ + PricingCostCode getPricingCostCode(Integer pricingTemplateId, Integer pricingCostCodeId); + + /*********************** PricingTier ***********************/ + + /** + * Get pricing tiers + */ + Collection getPricingTiers(Integer pricingTemplateId); + + /** + * Get a pricing tier + */ + PricingTier getPricingTier(Integer pricingTemplateId, Integer pricingTierId); + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/features/services/SearchService.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/features/services/SearchService.java new file mode 100644 index 0000000000..d4d1c3033f --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/features/services/SearchService.java @@ -0,0 +1,153 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.features.services; + +import org.jclouds.abiquo.domain.cloud.VirtualDatacenter; +import org.jclouds.abiquo.domain.cloud.Volume; +import org.jclouds.abiquo.domain.cloud.options.VolumeOptions; +import org.jclouds.abiquo.domain.enterprise.Enterprise; +import org.jclouds.abiquo.domain.enterprise.options.EnterpriseOptions; +import org.jclouds.abiquo.domain.infrastructure.Datacenter; +import org.jclouds.abiquo.domain.infrastructure.LogicServer; +import org.jclouds.abiquo.domain.infrastructure.ManagedRack; +import org.jclouds.abiquo.domain.infrastructure.StorageDevice; +import org.jclouds.abiquo.domain.infrastructure.StoragePool; +import org.jclouds.abiquo.domain.infrastructure.options.StoragePoolOptions; +import org.jclouds.abiquo.domain.network.PrivateIp; +import org.jclouds.abiquo.domain.network.PrivateNetwork; +import org.jclouds.abiquo.domain.network.PublicIp; +import org.jclouds.abiquo.domain.network.options.IpOptions; +import org.jclouds.abiquo.domain.options.search.FilterOptions; +import org.jclouds.abiquo.internal.BaseSearchService; + +import com.google.inject.ImplementedBy; + +/** + * Provides high level Abiquo search, filter and pagination operations. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +@ImplementedBy(BaseSearchService.class) +public interface SearchService { + /*********************** Enterprise ***********************/ + + /** + * Get the list of filtered enterprises. + * + * @param options + * The set of filtering and pagination options of the search. + */ + Iterable searchEnterprises(final EnterpriseOptions options); + + /** + * Get the list of filtered enterprises for a datacenter. + * + * @param datacenter + * The given datacenter. + * @param options + * The set of filtering and pagination options of the search. + * @see API: http://community.abiquo.com/display/ABI20/Datacenter+Resource# + * DatacenterResource- Retrievealistofenterprisesusingdatacenter + */ + Iterable searchEnterprisesUsingDatacenter(final Datacenter datacenter, final EnterpriseOptions options); + + /*********************** Volume ***********************/ + + /** + * Get the list of filtered volumes for a virtual datacenter. + * + * @param virtualDatacenter + * The given virtual datacenter. + * @param options + * The set of filtering and pagination options of the search. + */ + Iterable searchVolumes(final VirtualDatacenter virtualDatacenter, final VolumeOptions options); + + /*********************** Storage Pool ***********************/ + + /** + * Get the list of filtered storage pools for a storage device. + * + * @param device + * The given storage device. + * @param options + * The set of filtering and pagination options of the search. + */ + Iterable searchStoragePools(final StorageDevice device, final StoragePoolOptions options); + + /*********************** Private IPs ***********************/ + + /** + * Get the list of filtered ips for a private network. + * + * @param network + * The given private network. + * @param options + * The set of filtering and pagination options of the search. + */ + Iterable searchPrivateIps(final PrivateNetwork network, final IpOptions options); + + /*********************** Public IPs ***********************/ + + /** + * Get the list of filtered public ips to purchase by a virtual datacenter. + * + * @param virtualDatacenter + * The given virtual datacenter. + * @param options + * The set of filtering and pagination options of the search. + */ + Iterable searchPublicIpsToPurchase(final VirtualDatacenter virtualDatacenter, final IpOptions options); + + /** + * Get the list of filtered purchased public ips by a virtual datacenter. + * + * @param virtualDatacenter + * The given virtual datacenter. + * @param options + * The set of filtering and pagination options of the search. + */ + Iterable searchPurchasedPublicIps(final VirtualDatacenter virtualDatacenter, final IpOptions options); + + /*********************** Logic Server ***********************/ + + /** + * Get the list of service profiles for managed rack. + * + * @param managedRack + * The given rack. + * @param options + * The set of filtering and pagination options of the search. + */ + Iterable searchServiceProfiles(final ManagedRack rack, final FilterOptions options); + + /** + * Get the list of service profile templates for managed rack. + * + * @param managedRack + * The given rack. + * @param options + * The set of filtering and pagination options of the search. + */ + Iterable searchServiceProfileTemplates(final ManagedRack rack, final FilterOptions options); +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/functions/AppendApiVersionToAbiquoMimeType.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/functions/AppendApiVersionToAbiquoMimeType.java new file mode 100644 index 0000000000..00e9d3f940 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/functions/AppendApiVersionToAbiquoMimeType.java @@ -0,0 +1,65 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.functions; + +import static com.google.common.base.Preconditions.checkNotNull; + +import javax.inject.Inject; +import javax.inject.Singleton; +import javax.ws.rs.core.MediaType; + +import org.jclouds.rest.annotations.ApiVersion; + +import com.google.common.base.Function; + +/** + * Appends the Api version to the given mime type. + * + * @author Ignasi Barrera + */ +@Singleton +public class AppendApiVersionToAbiquoMimeType implements Function { + /** The prefix for Abiquo custom media types. */ + private static final String ABIQUO_MIME_TYPE_PREFIX = "application/vnd.abiquo."; + + /** The version to append to media types without version. */ + protected String apiVersion; + + @Inject + public AppendApiVersionToAbiquoMimeType(@ApiVersion final String apiVersion) { + super(); + this.apiVersion = checkNotNull(apiVersion, "apiVersion"); + } + + @Override + public String apply(final String input) { + MediaType mediaType = MediaType.valueOf(checkNotNull(input, "input")); + if (isAbiquoMimeType(input) && !mediaType.getParameters().containsKey("version")) { + return mediaType.toString() + ";version=" + apiVersion; + } else { + return mediaType.toString(); + } + } + + private static boolean isAbiquoMimeType(final String mimeType) { + return mimeType.startsWith(ABIQUO_MIME_TYPE_PREFIX); + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/functions/ParseErrors.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/functions/ParseErrors.java new file mode 100644 index 0000000000..2042cc2a90 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/functions/ParseErrors.java @@ -0,0 +1,43 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.functions; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.http.functions.ParseXMLWithJAXB; +import org.jclouds.xml.XMLParser; + +import com.abiquo.model.transport.error.ErrorsDto; +import com.google.inject.TypeLiteral; + +/** + * Parses a errors object. + * + * @author Ignasi Barrera + */ +@Singleton +public class ParseErrors extends ParseXMLWithJAXB { + @Inject + public ParseErrors(final XMLParser xml, final TypeLiteral type) { + super(xml, type); + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/functions/ReturnAbiquoExceptionOnNotFoundOr4xx.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/functions/ReturnAbiquoExceptionOnNotFoundOr4xx.java new file mode 100644 index 0000000000..81d3f120b8 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/functions/ReturnAbiquoExceptionOnNotFoundOr4xx.java @@ -0,0 +1,55 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.functions; + +import javax.inject.Singleton; + +import org.jclouds.abiquo.domain.exception.AbiquoException; +import org.jclouds.rest.ResourceNotFoundException; + +import com.google.common.base.Function; +import com.google.common.base.Predicate; +import com.google.common.base.Throwables; +import com.google.common.collect.Iterables; + +/** + * Return an Abiquo Exception on not found errors. + * + * @author Ignasi Barrera + */ +@Singleton +public class ReturnAbiquoExceptionOnNotFoundOr4xx implements Function { + @Override + public Object apply(final Exception from) { + Throwable exception = Iterables + .find(Throwables.getCausalChain(from), isNotFoundAndHasAbiquoException(from), null); + + throw Throwables.propagate(exception == null ? from : (AbiquoException) exception.getCause()); + } + + private static Predicate isNotFoundAndHasAbiquoException(final Throwable exception) { + return new Predicate() { + @Override + public boolean apply(final Throwable input) { + return input instanceof ResourceNotFoundException && input.getCause() instanceof AbiquoException; + } + }; + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/functions/ReturnFalseIfNotAvailable.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/functions/ReturnFalseIfNotAvailable.java new file mode 100644 index 0000000000..2753e14ca7 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/functions/ReturnFalseIfNotAvailable.java @@ -0,0 +1,74 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.functions; + +import javax.inject.Singleton; + +import org.jclouds.http.HttpResponse; +import org.jclouds.http.HttpResponseException; +import org.jclouds.rest.ResourceNotFoundException; + +import com.google.common.base.Function; +import com.google.common.base.Predicate; +import com.google.common.base.Throwables; +import com.google.common.collect.Iterables; + +/** + * Return false on service error exceptions. + * + * @author Ignasi Barrera + */ +@Singleton +public class ReturnFalseIfNotAvailable implements Function { + @Override + public Object apply(final Exception from) { + Throwable exception = Iterables.find(Throwables.getCausalChain(from), isNotAvailableException(from), null); + + if (exception != null) { + if (exception instanceof HttpResponseException) { + HttpResponseException responseException = (HttpResponseException) exception; + HttpResponse response = responseException.getResponse(); + + if (response != null && response.getStatusCode() >= 500 && response.getStatusCode() < 600) { + return false; + } + } else { + // Will enter here when exception is a ResourceNotFoundException + return false; + } + } + + throw Throwables.propagate(from); + } + + private static Predicate isNotAvailableException(final Throwable exception) { + return new Predicate() { + @Override + public boolean apply(final Throwable input) { + boolean notAvailable = input instanceof HttpResponseException + && ((HttpResponseException) input).getResponse() != null; + + notAvailable |= input instanceof ResourceNotFoundException; + + return notAvailable; + } + }; + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/functions/ReturnFalseOn5xx.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/functions/ReturnFalseOn5xx.java new file mode 100644 index 0000000000..73bf340903 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/functions/ReturnFalseOn5xx.java @@ -0,0 +1,63 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.functions; + +import javax.inject.Singleton; + +import org.jclouds.http.HttpResponse; +import org.jclouds.http.HttpResponseException; + +import com.google.common.base.Function; +import com.google.common.base.Predicate; +import com.google.common.base.Throwables; +import com.google.common.collect.Iterables; + +/** + * Return false on service error exceptions. + * + * @author Ignasi Barrera + */ +@Singleton +public class ReturnFalseOn5xx implements Function { + @Override + public Object apply(final Exception from) { + Throwable exception = Iterables.find(Throwables.getCausalChain(from), hasResponse(from), null); + + if (exception != null) { + HttpResponseException responseException = (HttpResponseException) exception; + HttpResponse response = responseException.getResponse(); + + if (response != null && response.getStatusCode() >= 500 && response.getStatusCode() < 600) { + return false; + } + } + + throw Throwables.propagate(from); + } + + private static Predicate hasResponse(final Throwable exception) { + return new Predicate() { + @Override + public boolean apply(final Throwable input) { + return input instanceof HttpResponseException && ((HttpResponseException) input).getResponse() != null; + } + }; + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/functions/ReturnMovedResource.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/functions/ReturnMovedResource.java new file mode 100644 index 0000000000..f22a84c60f --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/functions/ReturnMovedResource.java @@ -0,0 +1,68 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.functions; + +import javax.ws.rs.core.Response.Status; + +import org.jclouds.http.HttpResponse; +import org.jclouds.http.HttpResponseException; + +import com.google.common.base.Function; +import com.google.common.base.Predicate; +import com.google.common.base.Throwables; +import com.google.common.collect.Iterables; + +/** + * Return false on service error exceptions. + * + * @author Ignasi Barrera + */ +public abstract class ReturnMovedResource implements Function { + + @Override + public T apply(final Exception from) { + Throwable exception = Iterables.find(Throwables.getCausalChain(from), isMovedException(from), null); + + if (exception != null) { + HttpResponseException responseException = (HttpResponseException) exception; + HttpResponse response = responseException.getResponse(); + + return getMovedEntity(response); + } + + throw Throwables.propagate(from); + } + + protected abstract T getMovedEntity(HttpResponse response); + + private static Predicate isMovedException(final Throwable exception) { + return new Predicate() { + @Override + public boolean apply(final Throwable input) { + if (input instanceof HttpResponseException) { + HttpResponse response = ((HttpResponseException) input).getResponse(); + return response != null && response.getStatusCode() == Status.MOVED_PERMANENTLY.getStatusCode(); + } + + return false; + } + }; + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/functions/ReturnNullOn303.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/functions/ReturnNullOn303.java new file mode 100644 index 0000000000..6a3dd6167e --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/functions/ReturnNullOn303.java @@ -0,0 +1,64 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.functions; + +import javax.inject.Singleton; +import javax.ws.rs.core.Response.Status; + +import org.jclouds.http.HttpResponse; +import org.jclouds.http.HttpResponseException; + +import com.google.common.base.Function; +import com.google.common.base.Predicate; +import com.google.common.base.Throwables; +import com.google.common.collect.Iterables; + +/** + * Return null on 303 response codes when requesting a task. + * + * @author Ignasi Barrera + */ +@Singleton +public class ReturnNullOn303 implements Function { + @Override + public Object apply(final Exception from) { + Throwable exception = Iterables.find(Throwables.getCausalChain(from), hasResponse(from), null); + + if (exception != null) { + HttpResponseException responseException = (HttpResponseException) exception; + HttpResponse response = responseException.getResponse(); + + if (response != null && response.getStatusCode() == Status.SEE_OTHER.getStatusCode()) { + return null; + } + } + + throw Throwables.propagate(from); + } + + private static Predicate hasResponse(final Throwable exception) { + return new Predicate() { + @Override + public boolean apply(final Throwable input) { + return input instanceof HttpResponseException && ((HttpResponseException) input).getResponse() != null; + } + }; + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/functions/ReturnTaskReferenceOrNull.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/functions/ReturnTaskReferenceOrNull.java new file mode 100644 index 0000000000..d5d9691e91 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/functions/ReturnTaskReferenceOrNull.java @@ -0,0 +1,65 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.functions; + +import static org.jclouds.http.HttpUtils.releasePayload; + +import javax.inject.Inject; +import javax.inject.Singleton; +import javax.ws.rs.core.Response.Status; + +import org.jclouds.http.HttpResponse; +import org.jclouds.http.functions.ParseXMLWithJAXB; +import org.jclouds.xml.XMLParser; + +import com.abiquo.model.transport.AcceptedRequestDto; +import com.google.inject.TypeLiteral; + +/** + * Return an {@link AcceptedRequestDto} representing the asynchronous task or + * null if the operation completed synchronously. + *

+ * Operations that generate asynchronous tasks will return one of the following: + *

    + *
  • 204 if the operation completed synchronously
  • + *
  • 202 with the asynchronous task reference in the body if the operation has + * been submitted and will be executed asynchronously
  • + *
+ * + * @author Ignasi Barrera + */ +@Singleton +public class ReturnTaskReferenceOrNull extends ParseXMLWithJAXB> { + @Inject + public ReturnTaskReferenceOrNull(final XMLParser xml, final TypeLiteral> type) { + super(xml, type); + } + + @Override + public AcceptedRequestDto apply(final HttpResponse from) { + if (from.getStatusCode() == Status.NO_CONTENT.getStatusCode()) { + releasePayload(from); + return null; + } else { + return super.apply(from); + } + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/functions/cloud/ReturnMoveVolumeReference.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/functions/cloud/ReturnMoveVolumeReference.java new file mode 100644 index 0000000000..77fd42d19c --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/functions/cloud/ReturnMoveVolumeReference.java @@ -0,0 +1,44 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.functions.cloud; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.http.functions.ParseXMLWithJAXB; +import org.jclouds.xml.XMLParser; + +import com.abiquo.server.core.infrastructure.storage.MovedVolumeDto; +import com.google.inject.TypeLiteral; + +/** + * Return an {@link MovedVolumeDto} representing the reference to a moved + * resource. + * + * @author Ignasi Barrera + */ +@Singleton +public class ReturnMoveVolumeReference extends ParseXMLWithJAXB { + @Inject + public ReturnMoveVolumeReference(final XMLParser xml, final TypeLiteral type) { + super(xml, type); + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/functions/cloud/ReturnMovedVolume.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/functions/cloud/ReturnMovedVolume.java new file mode 100644 index 0000000000..88befbfd27 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/functions/cloud/ReturnMovedVolume.java @@ -0,0 +1,49 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.functions.cloud; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.abiquo.functions.ReturnMovedResource; +import org.jclouds.http.HttpResponse; + +import com.abiquo.server.core.infrastructure.storage.VolumeManagementDto; + +/** + * Return false on service error exceptions. + * + * @author Ignasi Barrera + */ +@Singleton +public class ReturnMovedVolume extends ReturnMovedResource { + private ReturnMoveVolumeReference parser; + + @Inject + public ReturnMovedVolume(final ReturnMoveVolumeReference parser) { + super(); + this.parser = parser; + } + + @Override + protected VolumeManagementDto getMovedEntity(final HttpResponse response) { + return parser.apply(response).getVolume(); + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/functions/enterprise/ParseEnterpriseId.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/functions/enterprise/ParseEnterpriseId.java new file mode 100644 index 0000000000..d8e8728539 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/functions/enterprise/ParseEnterpriseId.java @@ -0,0 +1,45 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.functions.enterprise; + +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; + +import javax.inject.Singleton; + +import com.abiquo.server.core.enterprise.EnterpriseDto; +import com.google.common.base.Function; + +/** + * Parses a {@link EnterpriseDto} object to extract its id. + * + * @author Francesc Montserrat + */ +@Singleton +public class ParseEnterpriseId implements Function { + @Override + public String apply(final Object input) { + checkArgument(checkNotNull(input, "input") instanceof EnterpriseDto, + "This parser is only valid for EnterpriseDto objects"); + + return ((EnterpriseDto) input).getId().toString(); + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/functions/infrastructure/ParseDatacenterId.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/functions/infrastructure/ParseDatacenterId.java new file mode 100644 index 0000000000..cadee5c762 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/functions/infrastructure/ParseDatacenterId.java @@ -0,0 +1,45 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.functions.infrastructure; + +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; + +import javax.inject.Singleton; + +import com.abiquo.server.core.infrastructure.DatacenterDto; +import com.google.common.base.Function; + +/** + * Parses a {@link DatacenterDto} object to extract its id. + * + * @author Francesc Montserrat + */ +@Singleton +public class ParseDatacenterId implements Function { + @Override + public String apply(final Object input) { + checkArgument(checkNotNull(input, "input") instanceof DatacenterDto, + "This parser is only valid for DatacenterDto objects"); + + return ((DatacenterDto) input).getId().toString(); + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/functions/infrastructure/ParseMachineId.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/functions/infrastructure/ParseMachineId.java new file mode 100644 index 0000000000..25e9b3b4ca --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/functions/infrastructure/ParseMachineId.java @@ -0,0 +1,45 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.functions.infrastructure; + +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; + +import javax.inject.Singleton; + +import com.abiquo.server.core.infrastructure.MachineDto; +import com.google.common.base.Function; + +/** + * Parses a {@link MachineDto} object to extract its id. + * + * @author Ignasi Barrera + */ +@Singleton +public class ParseMachineId implements Function { + @Override + public String apply(final Object input) { + checkArgument(checkNotNull(input, "input") instanceof MachineDto, + "This parser is only valid for MachineDto objects"); + + return ((MachineDto) input).getId().toString(); + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/functions/infrastructure/ParseRemoteServiceType.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/functions/infrastructure/ParseRemoteServiceType.java new file mode 100644 index 0000000000..bac565a5fd --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/functions/infrastructure/ParseRemoteServiceType.java @@ -0,0 +1,46 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.functions.infrastructure; + +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; + +import javax.inject.Singleton; + +import com.abiquo.model.enumerator.RemoteServiceType; +import com.google.common.base.Function; + +/** + * Parses a {@link ParseRemoteServiceType} object to extract its type in the + * format that the API expects it. + * + * @author Francesc Montserrat + */ +@Singleton +public class ParseRemoteServiceType implements Function { + @Override + public String apply(final Object input) { + checkArgument(checkNotNull(input, "input") instanceof RemoteServiceType, + "This parser is only valid for RemoteServiceType objects"); + + return ((RemoteServiceType) input).name().replaceAll("_", "").toLowerCase(); + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/handlers/AbiquoErrorHandler.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/handlers/AbiquoErrorHandler.java new file mode 100644 index 0000000000..3d68d61b0c --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/handlers/AbiquoErrorHandler.java @@ -0,0 +1,122 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.handlers; + +import static javax.ws.rs.core.Response.Status.fromStatusCode; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.abiquo.domain.exception.AbiquoException; +import org.jclouds.abiquo.functions.ParseErrors; +import org.jclouds.http.HttpCommand; +import org.jclouds.http.HttpErrorHandler; +import org.jclouds.http.HttpResponse; +import org.jclouds.http.HttpResponseException; +import org.jclouds.rest.AuthorizationException; +import org.jclouds.rest.ResourceNotFoundException; + +import com.abiquo.model.transport.error.ErrorsDto; +import com.google.common.io.Closeables; + +/** + * Parse Abiquo API errors and set the appropriate exception. + * + * @author Ignasi Barrera + */ +@Singleton +public class AbiquoErrorHandler implements HttpErrorHandler { + /** The error parser. */ + private ParseErrors errorParser; + + @Inject + AbiquoErrorHandler(final ParseErrors errorParser) { + super(); + this.errorParser = errorParser; + } + + @Override + public void handleError(final HttpCommand command, final HttpResponse response) { + Exception exception = null; + String defaultMessage = String.format("%s -> %s", command.getCurrentRequest().getRequestLine(), + response.getStatusLine()); + + try { + switch (response.getStatusCode()) { + case 401: + case 403: + // Autorization exceptions do not return an errors DTO, so we + // encapsulate a + // generic exception + exception = new AuthorizationException(defaultMessage, new HttpResponseException(command, response, + defaultMessage)); + break; + case 404: + exception = new ResourceNotFoundException(defaultMessage, getExceptionToPropagate(command, response, + defaultMessage)); + break; + case 301: + // Moved resources in Abiquo should be handled with the + // ReturnMovedResource + // exception parser to return the moved entity. + exception = new HttpResponseException(command, response, defaultMessage); + break; + default: + exception = getExceptionToPropagate(command, response, defaultMessage); + break; + } + } finally { + if (response.getPayload() != null) { + Closeables.closeQuietly(response.getPayload().getInput()); + } + command.setException(exception); + } + } + + private Exception getExceptionToPropagate(final HttpCommand command, final HttpResponse response, + final String defaultMessage) { + Exception exception = null; + + if (hasPayload(response)) { + try { + ErrorsDto errors = errorParser.apply(response); + exception = new AbiquoException(fromStatusCode(response.getStatusCode()), errors); + } catch (Exception ex) { + // If it is not an Abiquo Exception (can not be unmarshalled), + // propagate a standard + // HttpResponseException + exception = new HttpResponseException(command, response, defaultMessage); + } + } else { + // If it is not an Abiquo Exception (there is not an errors xml in the + // payload) + // propagate a standard HttpResponseException + exception = new HttpResponseException(command, response, defaultMessage); + } + + return exception; + } + + private static boolean hasPayload(final HttpResponse response) { + return response.getPayload() != null && response.getPayload().getContentMetadata() != null + && response.getPayload().getContentMetadata().getContentLength() != null + && response.getPayload().getContentMetadata().getContentLength() > 0L; + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/http/filters/AbiquoAuthentication.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/http/filters/AbiquoAuthentication.java new file mode 100644 index 0000000000..f126249426 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/http/filters/AbiquoAuthentication.java @@ -0,0 +1,83 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.http.filters; + +import static com.google.common.base.Preconditions.checkNotNull; +import static org.jclouds.abiquo.config.AbiquoProperties.CREDENTIAL_IS_TOKEN; + +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; +import javax.ws.rs.core.HttpHeaders; + +import org.jclouds.crypto.CryptoStreams; +import org.jclouds.http.HttpException; +import org.jclouds.http.HttpRequest; +import org.jclouds.http.HttpRequestFilter; +import org.jclouds.rest.annotations.Credential; +import org.jclouds.rest.annotations.Identity; + +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Charsets; + +/** + * Authenticates using Basic Authentication or a generated token from previous + * API sessions. + * + * @author Ignasi Barrera + */ +@Singleton +public class AbiquoAuthentication implements HttpRequestFilter { + /** The name of the authentication token. */ + public static final String AUTH_TOKEN_NAME = "auth"; + + protected String identity; + + protected String credential; + + protected boolean credentialIsToken; + + @Inject + public AbiquoAuthentication(@Identity final String identity, @Credential final String credential, + @Named(CREDENTIAL_IS_TOKEN) final String credentialIsToken) { + this.identity = checkNotNull(identity, "identity"); + this.credential = checkNotNull(credential, "credential"); + this.credentialIsToken = Boolean.valueOf(credentialIsToken); + } + + @Override + public HttpRequest filter(final HttpRequest request) throws HttpException { + String header = credentialIsToken ? tokenAuth(credential) : basicAuth(identity, credential); + return request.toBuilder() + .replaceHeader(credentialIsToken ? HttpHeaders.COOKIE : HttpHeaders.AUTHORIZATION, header).build(); + } + + @VisibleForTesting + static String basicAuth(final String user, final String password) { + return "Basic " + + CryptoStreams.base64(String.format("%s:%s", checkNotNull(user, "user"), + checkNotNull(password, "password")).getBytes(Charsets.UTF_8)); + } + + @VisibleForTesting + static String tokenAuth(final String token) { + return AUTH_TOKEN_NAME + "=" + checkNotNull(token, "token"); + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/http/filters/AppendApiVersionToMediaType.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/http/filters/AppendApiVersionToMediaType.java new file mode 100644 index 0000000000..a671315042 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/http/filters/AppendApiVersionToMediaType.java @@ -0,0 +1,78 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.http.filters; + +import java.util.Collection; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.abiquo.functions.AppendApiVersionToAbiquoMimeType; +import org.jclouds.http.HttpException; +import org.jclouds.http.HttpRequest; +import org.jclouds.http.HttpRequestFilter; + +import com.google.common.annotations.VisibleForTesting; +import com.google.common.collect.Iterables; +import com.google.common.net.HttpHeaders; + +/** + * Appends the api version to the Abiquo mime types to ensure the input and + * output of api calls will be in the desired format. + * + * @author Ignasi Barrera + */ +@Singleton +public class AppendApiVersionToMediaType implements HttpRequestFilter { + /** The function used to append the version to media types. */ + private AppendApiVersionToAbiquoMimeType versionAppender; + + @Inject + public AppendApiVersionToMediaType(final AppendApiVersionToAbiquoMimeType versionAppender) { + super(); + this.versionAppender = versionAppender; + } + + @Override + public HttpRequest filter(final HttpRequest request) throws HttpException { + HttpRequest requestWithVersionInMediaTypes = appendVersionToNonPayloadHeaders(request); + return appendVersionToPayloadHeaders(requestWithVersionInMediaTypes); + } + + @VisibleForTesting + HttpRequest appendVersionToNonPayloadHeaders(final HttpRequest request) { + Collection accept = request.getHeaders().get(HttpHeaders.ACCEPT); + return accept.isEmpty() ? request : request + .toBuilder() + .replaceHeader(HttpHeaders.ACCEPT, + Iterables.toArray(Iterables.transform(accept, versionAppender), String.class)).build(); + } + + @VisibleForTesting + HttpRequest appendVersionToPayloadHeaders(final HttpRequest request) { + if (request.getPayload() != null) { + String contentTypeWithVersion = versionAppender.apply(request.getPayload().getContentMetadata() + .getContentType()); + request.getPayload().getContentMetadata().setContentType(contentTypeWithVersion); + } + + return request; + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/internal/AbiquoContextImpl.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/internal/AbiquoContextImpl.java new file mode 100644 index 0000000000..d04b2e33a0 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/internal/AbiquoContextImpl.java @@ -0,0 +1,116 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.internal; + +import static com.google.common.base.Preconditions.checkNotNull; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.Context; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoContext; +import org.jclouds.abiquo.features.services.AdministrationService; +import org.jclouds.abiquo.features.services.CloudService; +import org.jclouds.abiquo.features.services.EventService; +import org.jclouds.abiquo.features.services.MonitoringService; +import org.jclouds.abiquo.features.services.PricingService; +import org.jclouds.abiquo.features.services.SearchService; +import org.jclouds.compute.ComputeService; +import org.jclouds.compute.Utils; +import org.jclouds.compute.internal.ComputeServiceContextImpl; +import org.jclouds.location.Provider; +import org.jclouds.rest.RestContext; +import org.jclouds.rest.internal.RestContextImpl; + +import com.google.common.reflect.TypeToken; + +/** + * Abiquo {@link RestContextImpl} implementation to expose high level Abiquo + * functionalities. + * + * @author Ignasi Barrera + */ +@Singleton +public class AbiquoContextImpl extends ComputeServiceContextImpl implements AbiquoContext { + private final AdministrationService administrationService; + + private final CloudService cloudService; + + private final SearchService searchService; + + private final MonitoringService monitoringService; + + private final EventService eventService; + + private final PricingService pricingService; + + @Inject + public AbiquoContextImpl(@Provider final Context wrapped, @Provider final TypeToken wrappedType, + final ComputeService computeService, final Utils utils, + final RestContext providerSpecificContext, + final AdministrationService administrationService, final CloudService cloudService, + final SearchService searchService, final MonitoringService monitoringService, final EventService eventService, + final PricingService pricingService) { + super(wrapped, wrappedType, computeService, utils); + this.administrationService = checkNotNull(administrationService, "administrationService"); + this.cloudService = checkNotNull(cloudService, "cloudService"); + this.searchService = checkNotNull(searchService, "searchService"); + this.monitoringService = checkNotNull(monitoringService, "monitoringService"); + this.eventService = checkNotNull(eventService, "eventService"); + this.pricingService = checkNotNull(pricingService, "pricingService"); + } + + @Override + public RestContext getApiContext() { + return unwrap(); + } + + @Override + public AdministrationService getAdministrationService() { + return administrationService; + } + + @Override + public CloudService getCloudService() { + return cloudService; + } + + @Override + public SearchService getSearchService() { + return searchService; + } + + @Override + public MonitoringService getMonitoringService() { + return monitoringService; + } + + @Override + public EventService getEventService() { + return eventService; + } + + @Override + public PricingService getPricingService() { + return pricingService; + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/internal/BaseAdministrationService.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/internal/BaseAdministrationService.java new file mode 100644 index 0000000000..25aacb8f2a --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/internal/BaseAdministrationService.java @@ -0,0 +1,323 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.internal; + +import static com.google.common.base.Preconditions.checkNotNull; +import static org.jclouds.abiquo.domain.DomainWrapper.wrap; + +import java.util.List; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.domain.config.Category; +import org.jclouds.abiquo.domain.config.License; +import org.jclouds.abiquo.domain.config.Privilege; +import org.jclouds.abiquo.domain.config.SystemProperty; +import org.jclouds.abiquo.domain.config.options.LicenseOptions; +import org.jclouds.abiquo.domain.config.options.PropertyOptions; +import org.jclouds.abiquo.domain.enterprise.Enterprise; +import org.jclouds.abiquo.domain.enterprise.EnterpriseProperties; +import org.jclouds.abiquo.domain.enterprise.Role; +import org.jclouds.abiquo.domain.enterprise.User; +import org.jclouds.abiquo.domain.infrastructure.Datacenter; +import org.jclouds.abiquo.domain.infrastructure.Machine; +import org.jclouds.abiquo.features.services.AdministrationService; +import org.jclouds.abiquo.reference.ValidationErrors; +import org.jclouds.abiquo.strategy.admin.ListRoles; +import org.jclouds.abiquo.strategy.config.ListCategories; +import org.jclouds.abiquo.strategy.config.ListLicenses; +import org.jclouds.abiquo.strategy.config.ListPrivileges; +import org.jclouds.abiquo.strategy.config.ListProperties; +import org.jclouds.abiquo.strategy.enterprise.ListEnterprises; +import org.jclouds.abiquo.strategy.infrastructure.ListDatacenters; +import org.jclouds.abiquo.strategy.infrastructure.ListMachines; +import org.jclouds.collect.Memoized; +import org.jclouds.rest.RestContext; + +import com.abiquo.server.core.enterprise.EnterpriseDto; +import com.abiquo.server.core.enterprise.EnterprisePropertiesDto; +import com.abiquo.server.core.enterprise.RoleDto; +import com.abiquo.server.core.infrastructure.DatacenterDto; +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Predicate; +import com.google.common.base.Supplier; +import com.google.common.collect.Iterables; + +/** + * Provides high level Abiquo administration operations. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +@Singleton +public class BaseAdministrationService implements AdministrationService { + @VisibleForTesting + protected RestContext context; + + @VisibleForTesting + protected final ListDatacenters listDatacenters; + + @VisibleForTesting + protected final ListMachines listMachines; + + @VisibleForTesting + protected final ListEnterprises listEnterprises; + + @VisibleForTesting + protected final ListRoles listRoles; + + @VisibleForTesting + protected final ListLicenses listLicenses; + + @VisibleForTesting + protected final ListPrivileges listPrivileges; + + @VisibleForTesting + protected final ListProperties listProperties; + + @VisibleForTesting + protected final ListCategories listCategories; + + @VisibleForTesting + protected final Supplier currentUser; + + @VisibleForTesting + protected final Supplier currentEnterprise; + + @Inject + protected BaseAdministrationService(final RestContext context, + final ListDatacenters listDatacenters, final ListMachines listMachines, final ListEnterprises listEnterprises, + final ListRoles listRoles, final ListLicenses listLicenses, final ListPrivileges listPrivileges, + final ListProperties listProperties, final ListCategories listCategories, + @Memoized final Supplier currentUser, @Memoized final Supplier currentEnterprise) { + this.context = checkNotNull(context, "context"); + this.listDatacenters = checkNotNull(listDatacenters, "listDatacenters"); + this.listMachines = checkNotNull(listMachines, "listMachines"); + this.listEnterprises = checkNotNull(listEnterprises, "listEnterprises"); + this.listRoles = checkNotNull(listRoles, "listRoles"); + this.listLicenses = checkNotNull(listLicenses, "listLicenses"); + this.listPrivileges = checkNotNull(listPrivileges, "listPrivileges"); + this.listProperties = checkNotNull(listProperties, "listProperties"); + this.listCategories = checkNotNull(listCategories, "listCategories"); + this.currentUser = checkNotNull(currentUser, "currentUser"); + this.currentEnterprise = checkNotNull(currentEnterprise, "currentEnterprise"); + } + + /*********************** Datacenter ********************** */ + + @Override + public Iterable listDatacenters() { + return listDatacenters.execute(); + } + + @Override + public Iterable listDatacenters(final Predicate filter) { + return listDatacenters.execute(filter); + } + + @Override + public Datacenter getDatacenter(final Integer datacenterId) { + DatacenterDto datacenter = context.getApi().getInfrastructureApi().getDatacenter(datacenterId); + return wrap(context, Datacenter.class, datacenter); + } + + @Override + public Datacenter findDatacenter(final Predicate filter) { + return Iterables.getFirst(listDatacenters(filter), null); + } + + @Override + public Iterable getDatacenters(final List datacenterIds) { + return listDatacenters.execute(datacenterIds); + } + + /*********************** Machine ***********************/ + + @Override + public Iterable listMachines() { + return listMachines.execute(); + } + + @Override + public Iterable listMachines(final Predicate filter) { + return listMachines.execute(filter); + } + + @Override + public Machine findMachine(final Predicate filter) { + return Iterables.getFirst(listMachines(filter), null); + } + + /*********************** Enterprise ***********************/ + + @Override + public Iterable listEnterprises() { + return listEnterprises.execute(); + } + + @Override + public Iterable listEnterprises(final Predicate filter) { + return listEnterprises.execute(filter); + } + + @Override + public Enterprise findEnterprise(final Predicate filter) { + return Iterables.getFirst(listEnterprises(filter), null); + } + + @Override + public Enterprise getEnterprise(final Integer enterpriseId) { + EnterpriseDto enterprise = context.getApi().getEnterpriseApi().getEnterprise(enterpriseId); + return wrap(context, Enterprise.class, enterprise); + } + + /*********************** Enterprise Properties ***********************/ + + @Override + public EnterpriseProperties getEnterpriseProperties(final Enterprise enterprise) { + checkNotNull(enterprise.getId(), ValidationErrors.MISSING_REQUIRED_FIELD + " id in " + Enterprise.class); + + EnterprisePropertiesDto properties = context.getApi().getEnterpriseApi() + .getEnterpriseProperties(enterprise.unwrap()); + return wrap(context, EnterpriseProperties.class, properties); + } + + /*********************** Role ********************** */ + + @Override + public Iterable listRoles() { + return listRoles.execute(); + } + + @Override + public Iterable listRoles(final Predicate filter) { + return listRoles.execute(filter); + } + + @Override + public Role findRole(final Predicate filter) { + return Iterables.getFirst(listRoles(filter), null); + } + + @Override + public Role getRole(final Integer roleId) { + RoleDto role = context.getApi().getAdminApi().getRole(roleId); + return wrap(context, Role.class, role); + } + + /*********************** Privilege ***********************/ + + @Override + public Privilege findPrivilege(final Predicate filter) { + return Iterables.getFirst(listPrivileges(filter), null); + } + + @Override + public Iterable listPrivileges() { + return listPrivileges.execute(); + } + + @Override + public Iterable listPrivileges(final Predicate filter) { + return listPrivileges.execute(filter); + } + + /*********************** User ***********************/ + + @Override + public User getCurrentUser() { + return currentUser.get(); + } + + @Override + public Enterprise getCurrentEnterprise() { + return currentEnterprise.get(); + } + + /*********************** License ***********************/ + + @Override + public Iterable listLicenses() { + return listLicenses.execute(); + } + + @Override + public Iterable listLicenses(final boolean active) { + LicenseOptions options = LicenseOptions.builder().active(active).build(); + return listLicenses.execute(options); + } + + @Override + public Iterable listLicenses(final Predicate filter) { + return listLicenses.execute(filter); + } + + @Override + public License findLicense(final Predicate filter) { + return Iterables.getFirst(listLicenses(filter), null); + } + + /*********************** System Properties ***********************/ + + @Override + public Iterable listSystemProperties() { + return listProperties.execute(); + } + + @Override + public Iterable listSystemProperties(final Predicate filter) { + return listProperties.execute(filter); + } + + @Override + public SystemProperty findSystemProperty(final Predicate filter) { + return Iterables.getFirst(listSystemProperties(filter), null); + } + + @Override + public SystemProperty getSystemProperty(final String name) { + PropertyOptions options = PropertyOptions.builder().name(name).build(); + return Iterables.getFirst(listProperties.execute(options), null); + } + + @Override + public Iterable listSystemProperties(final String component) { + PropertyOptions options = PropertyOptions.builder().component(component).build(); + return listProperties.execute(options); + } + + @Override + public Category findCategory(final Predicate filter) { + return Iterables.getFirst(listCategories(filter), null); + } + + @Override + public Iterable listCategories() { + return listCategories.execute(); + } + + @Override + public Iterable listCategories(final Predicate filter) { + return listCategories.execute(filter); + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/internal/BaseCloudService.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/internal/BaseCloudService.java new file mode 100644 index 0000000000..16d99cba16 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/internal/BaseCloudService.java @@ -0,0 +1,150 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.internal; + +import static com.google.common.base.Preconditions.checkNotNull; +import static org.jclouds.abiquo.domain.DomainWrapper.wrap; + +import java.util.List; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.domain.cloud.VirtualAppliance; +import org.jclouds.abiquo.domain.cloud.VirtualDatacenter; +import org.jclouds.abiquo.domain.cloud.VirtualMachine; +import org.jclouds.abiquo.domain.cloud.options.VirtualDatacenterOptions; +import org.jclouds.abiquo.domain.enterprise.Enterprise; +import org.jclouds.abiquo.features.services.CloudService; +import org.jclouds.abiquo.reference.ValidationErrors; +import org.jclouds.abiquo.strategy.cloud.ListVirtualAppliances; +import org.jclouds.abiquo.strategy.cloud.ListVirtualDatacenters; +import org.jclouds.abiquo.strategy.cloud.ListVirtualMachines; +import org.jclouds.rest.RestContext; + +import com.abiquo.server.core.cloud.VirtualDatacenterDto; +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Predicate; +import com.google.common.collect.Iterables; + +/** + * Provides high level Abiquo cloud operations. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +@Singleton +public class BaseCloudService implements CloudService { + @VisibleForTesting + protected RestContext context; + + @VisibleForTesting + protected final ListVirtualDatacenters listVirtualDatacenters; + + @VisibleForTesting + protected ListVirtualAppliances listVirtualAppliances; + + @VisibleForTesting + protected ListVirtualMachines listVirtualMachines; + + @Inject + protected BaseCloudService(final RestContext context, + final ListVirtualDatacenters listVirtualDatacenters, final ListVirtualAppliances listVirtualAppliances, + final ListVirtualMachines listVirtualMachines) { + this.context = checkNotNull(context, "context"); + this.listVirtualDatacenters = checkNotNull(listVirtualDatacenters, "listVirtualDatacenters"); + this.listVirtualAppliances = checkNotNull(listVirtualAppliances, "listVirtualAppliances"); + this.listVirtualMachines = checkNotNull(listVirtualMachines, "listVirtualMachines"); + } + + /*********************** Virtual Datacenter ********************** */ + + @Override + public Iterable listVirtualDatacenters() { + return listVirtualDatacenters.execute(); + } + + @Override + public Iterable listVirtualDatacenters(final Enterprise enterprise) { + checkNotNull(enterprise, ValidationErrors.NULL_RESOURCE + Enterprise.class); + checkNotNull(enterprise.getId(), ValidationErrors.MISSING_REQUIRED_FIELD + " id in " + Enterprise.class); + + VirtualDatacenterOptions options = VirtualDatacenterOptions.builder().enterpriseId(enterprise.getId()).build(); + + return listVirtualDatacenters.execute(options); + } + + @Override + public Iterable listVirtualDatacenters(final Predicate filter) { + return listVirtualDatacenters.execute(filter); + } + + @Override + public VirtualDatacenter getVirtualDatacenter(final Integer virtualDatacenterId) { + VirtualDatacenterDto virtualDatacenter = context.getApi().getCloudApi().getVirtualDatacenter(virtualDatacenterId); + return wrap(context, VirtualDatacenter.class, virtualDatacenter); + } + + @Override + public Iterable getVirtualDatacenters(final List virtualDatacenterIds) { + return listVirtualDatacenters.execute(virtualDatacenterIds); + } + + @Override + public VirtualDatacenter findVirtualDatacenter(final Predicate filter) { + return Iterables.getFirst(listVirtualDatacenters(filter), null); + } + + /*********************** Virtual Appliance ********************** */ + + @Override + public Iterable listVirtualAppliances() { + return listVirtualAppliances.execute(); + } + + @Override + public Iterable listVirtualAppliances(final Predicate filter) { + return listVirtualAppliances.execute(filter); + } + + @Override + public VirtualAppliance findVirtualAppliance(final Predicate filter) { + return Iterables.getFirst(listVirtualAppliances(filter), null); + } + + /*********************** Virtual Machine ********************** */ + + @Override + public Iterable listVirtualMachines() { + return listVirtualMachines.execute(); + } + + @Override + public Iterable listVirtualMachines(final Predicate filter) { + return listVirtualMachines.execute(filter); + } + + @Override + public VirtualMachine findVirtualMachine(final Predicate filter) { + return Iterables.getFirst(listVirtualMachines(filter), null); + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/internal/BaseEventService.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/internal/BaseEventService.java new file mode 100644 index 0000000000..960065d16a --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/internal/BaseEventService.java @@ -0,0 +1,66 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.internal; + +import static com.google.common.base.Preconditions.checkNotNull; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.domain.event.Event; +import org.jclouds.abiquo.domain.event.options.EventOptions; +import org.jclouds.abiquo.features.services.EventService; +import org.jclouds.abiquo.strategy.event.ListEvents; +import org.jclouds.rest.RestContext; + +import com.google.common.annotations.VisibleForTesting; + +/** + * Provides high level Abiquo event operations. + * + * @author Ignasi Barrera + * @author Vivien Mahé + */ +@Singleton +public class BaseEventService implements EventService { + @VisibleForTesting + protected RestContext context; + + @VisibleForTesting + protected final ListEvents listEvents; + + @Inject + protected BaseEventService(final RestContext context, final ListEvents listEvents) { + this.context = checkNotNull(context, "context"); + this.listEvents = checkNotNull(listEvents, "listEvents"); + } + + @Override + public Iterable listEvents() { + return listEvents.execute(); + } + + @Override + public Iterable listEvents(final EventOptions options) { + return listEvents.execute(options); + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/internal/BaseMonitoringService.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/internal/BaseMonitoringService.java new file mode 100644 index 0000000000..e54f2d4d0e --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/internal/BaseMonitoringService.java @@ -0,0 +1,298 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.internal; + +import static com.google.common.base.Preconditions.checkNotNull; +import static org.jclouds.Constants.PROPERTY_SCHEDULER_THREADS; +import static org.jclouds.abiquo.config.AbiquoProperties.ASYNC_TASK_MONITOR_DELAY; + +import java.util.concurrent.Future; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +import javax.annotation.Resource; +import javax.inject.Named; +import javax.inject.Singleton; + +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.events.handlers.AbstractEventHandler; +import org.jclouds.abiquo.events.handlers.BlockingEventHandler; +import org.jclouds.abiquo.events.monitor.CompletedEvent; +import org.jclouds.abiquo.events.monitor.FailedEvent; +import org.jclouds.abiquo.events.monitor.TimeoutEvent; +import org.jclouds.abiquo.features.services.MonitoringService; +import org.jclouds.abiquo.monitor.AsyncTaskMonitor; +import org.jclouds.abiquo.monitor.ConversionMonitor; +import org.jclouds.abiquo.monitor.MonitorStatus; +import org.jclouds.abiquo.monitor.VirtualApplianceMonitor; +import org.jclouds.abiquo.monitor.VirtualMachineMonitor; +import org.jclouds.logging.Logger; +import org.jclouds.rest.RestContext; + +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Function; +import com.google.common.eventbus.EventBus; +import com.google.inject.Inject; + +/** + * Utility service to monitor asynchronous operations. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +@Singleton +public class BaseMonitoringService implements MonitoringService { + @VisibleForTesting + protected RestContext context; + + /** The scheduler used to perform monitoring tasks. */ + @VisibleForTesting + protected ScheduledExecutorService scheduler; + + @VisibleForTesting + protected Long pollingDelay; + + /** + * The event bus used to dispatch monitoring events. + *

+ * A sync bus is used by default, to prevent deadlocks when using the + * {@link BlockingEventHandler}. + */ + @VisibleForTesting + protected EventBus eventBus; + + @Resource + private Logger logger = Logger.NULL; + + @Inject + public BaseMonitoringService(final RestContext context, + @Named(PROPERTY_SCHEDULER_THREADS) final ScheduledExecutorService scheduler, + @Named(ASYNC_TASK_MONITOR_DELAY) final Long pollingDelay, final EventBus eventBus) { + this.context = checkNotNull(context, "context"); + this.scheduler = checkNotNull(scheduler, "scheduler"); + this.pollingDelay = checkNotNull(pollingDelay, "pollingDelay"); + this.eventBus = checkNotNull(eventBus, "eventBus"); + } + + /*************** Generic monitoring methods ***************/ + + @Override + public void awaitCompletion(final Function completeCondition, final T... objects) { + awaitCompletion(null, null, completeCondition, objects); + } + + @Override + public void awaitCompletion(final Long maxWait, final TimeUnit timeUnit, + final Function completeCondition, final T... objects) { + checkNotNull(completeCondition, "completeCondition"); + + if (objects != null && objects.length > 0) { + BlockingEventHandler blockingHandler = new BlockingEventHandler(logger, objects); + register(blockingHandler); + + monitor(maxWait, timeUnit, completeCondition, objects); + blockingHandler.lock(); + + unregister(blockingHandler); + } + } + + @Override + public void monitor(final Function completeCondition, final T... objects) { + monitor(null, null, completeCondition, objects); + } + + @Override + public void monitor(final Long maxWait, final TimeUnit timeUnit, + final Function completeCondition, final T... objects) { + checkNotNull(completeCondition, "completeCondition"); + if (maxWait != null) { + checkNotNull(timeUnit, "timeUnit"); + } + + if (objects != null && objects.length > 0) { + for (T object : objects) { + AsyncMonitor monitor = new AsyncMonitor(object, completeCondition); + monitor.startMonitoring(maxWait); + } + } + } + + @Override + public > void register(final T handler) { + logger.debug("registering event handler %s", handler); + eventBus.register(handler); + } + + @Override + public > void unregister(final T handler) { + logger.debug("unregistering event handler %s", handler); + eventBus.unregister(handler); + } + + /*************** Delegating monitors ***************/ + + @Override + public VirtualMachineMonitor getVirtualMachineMonitor() { + return checkNotNull(context.getUtils().getInjector().getInstance(VirtualMachineMonitor.class), + "virtualMachineMonitor"); + } + + @Override + public VirtualApplianceMonitor getVirtualApplianceMonitor() { + return checkNotNull(context.getUtils().getInjector().getInstance(VirtualApplianceMonitor.class), + "virtualApplianceMonitor"); + } + + @Override + public AsyncTaskMonitor getAsyncTaskMonitor() { + return checkNotNull(context.getUtils().getInjector().getInstance(AsyncTaskMonitor.class), "asyncTaskMonitor"); + } + + @Override + public ConversionMonitor getConversionMonitor() { + return checkNotNull(context.getUtils().getInjector().getInstance(ConversionMonitor.class), "conversionMonitor"); + } + + /** + * Performs the periodical monitoring tasks. + * + * @author Ignasi Barrera + * @param + * The type of the object being monitored. + */ + @VisibleForTesting + class AsyncMonitor implements Runnable { + /** The object being monitored. */ + private T monitoredObject; + + /** The function used to monitor the target object. */ + private Function completeCondition; + + /** + * The future representing the monitoring job. Needed to be able to cancel + * it when monitor finishes. + */ + private Future future; + + /** The timeout for this monitor. */ + private Long timeout; + + public AsyncMonitor(final T monitoredObject, final Function completeCondition) { + super(); + this.monitoredObject = checkNotNull(monitoredObject, "monitoredObject"); + this.completeCondition = checkNotNull(completeCondition, "completeCondition"); + } + + /** + * Starts the monitoring job with the given timeout. + * + * @param maxWait + * The timeout. + */ + public void startMonitoring(final Long maxWait) { + future = scheduler.scheduleWithFixedDelay(this, 0L, pollingDelay, TimeUnit.MILLISECONDS); + timeout = maxWait == null ? null : System.currentTimeMillis() + maxWait; + logger.debug("started monitor job for %s with %s timeout", monitoredObject, + timeout == null ? "no" : String.valueOf(timeout)); + } + + /** + * Stops the monitoring job, if running. + */ + public void stopMonitoring() { + logger.debug("stopping monitor job for %s", monitoredObject); + + try { + if (future != null && !future.isCancelled() && !future.isDone()) { + // Do not force future cancel. Let it finish gracefully + logger.debug("cancelling future"); + future.cancel(false); + } + } catch (Exception ex) { + logger.warn(ex, "failed to stop monitor job for %s", monitoredObject); + } + } + + /** + * Checks if the monitor has timed out. + */ + public boolean isTimeout() { + return timeout != null && timeout < System.currentTimeMillis(); + } + + @Override + public void run() { + // Do not use Thread.interrupted() since it will clear the interrupted + // flag + // and subsequent calls to it may not return the appropriate value + if (Thread.currentThread().isInterrupted()) { + // If the thread as already been interrupted, just stop monitoring + // the task and + // return + stopMonitoring(); + return; + } + + MonitorStatus status = completeCondition.apply(monitoredObject); + logger.debug("monitored object %s status %s", monitoredObject, status.name()); + + switch (status) { + case DONE: + stopMonitoring(); + logger.debug("publishing COMPLETED event"); + eventBus.post(new CompletedEvent(monitoredObject)); + break; + case FAILED: + stopMonitoring(); + logger.debug("publishing FAILED event"); + eventBus.post(new FailedEvent(monitoredObject)); + break; + case CONTINUE: + default: + if (isTimeout()) { + logger.warn("monitor for object %s timed out. Shutting down monitor.", monitoredObject); + stopMonitoring(); + logger.debug("publishing TIMEOUT event"); + eventBus.post(new TimeoutEvent(monitoredObject)); + } + break; + } + } + + public T getMonitoredObject() { + return monitoredObject; + } + + public Function getCompleteCondition() { + return completeCondition; + } + + public Future getFuture() { + return future; + } + + public Long getTimeout() { + return timeout; + } + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/internal/BasePricingService.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/internal/BasePricingService.java new file mode 100644 index 0000000000..1fc2c9aebc --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/internal/BasePricingService.java @@ -0,0 +1,170 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.internal; + +import static com.google.common.base.Preconditions.checkNotNull; +import static org.jclouds.abiquo.domain.DomainWrapper.wrap; + +import java.util.Collection; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.domain.config.CostCode; +import org.jclouds.abiquo.domain.config.CostCodeCurrency; +import org.jclouds.abiquo.domain.config.Currency; +import org.jclouds.abiquo.domain.config.PricingCostCode; +import org.jclouds.abiquo.domain.config.PricingTemplate; +import org.jclouds.abiquo.domain.config.PricingTier; +import org.jclouds.abiquo.features.services.PricingService; +import org.jclouds.abiquo.strategy.config.ListCostCodes; +import org.jclouds.abiquo.strategy.config.ListCurrencies; +import org.jclouds.abiquo.strategy.config.ListPricingTemplates; +import org.jclouds.rest.RestContext; + +import com.abiquo.server.core.pricing.CostCodeCurrenciesDto; +import com.abiquo.server.core.pricing.PricingCostCodeDto; +import com.abiquo.server.core.pricing.PricingCostCodesDto; +import com.abiquo.server.core.pricing.PricingTierDto; +import com.abiquo.server.core.pricing.PricingTiersDto; +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Predicate; +import com.google.common.collect.Iterables; + +/** + * Provides high level Abiquo administration operations. + * + * @author Ignasi Barrera + * @author Susana Acedo + */ +@Singleton +public class BasePricingService implements PricingService { + @VisibleForTesting + protected RestContext context; + + @VisibleForTesting + protected final ListCurrencies listCurrencies; + + @VisibleForTesting + protected final ListCostCodes listCostCodes; + + @VisibleForTesting + protected final ListPricingTemplates listPricingTemplates; + + @Inject + protected BasePricingService(final RestContext context, + final ListCurrencies listCurrencies, final ListCostCodes listCostCodes, + final ListPricingTemplates listPricingTemplates) { + this.context = checkNotNull(context, "context"); + this.listCurrencies = checkNotNull(listCurrencies, "listCurrencies"); + this.listCostCodes = checkNotNull(listCostCodes, "listCostCodes"); + this.listPricingTemplates = checkNotNull(listPricingTemplates, "listPricingTemplates"); + } + + /*********************** Currency ********************** */ + + @Override + public Iterable listCurrencies() { + return listCurrencies.execute(); + } + + @Override + public Iterable listCurrencies(final Predicate filter) { + return listCurrencies.execute(filter); + } + + @Override + public Currency findCurrency(final Predicate filter) { + return Iterables.getFirst(listCurrencies(filter), null); + } + + /*********************** CostCode ********************** */ + + @Override + public Iterable listCostCodes() { + return listCostCodes.execute(); + } + + @Override + public Iterable listCostCodes(final Predicate filter) { + return listCostCodes.execute(filter); + } + + @Override + public CostCode findCostCode(final Predicate filter) { + return Iterables.getFirst(listCostCodes(filter), null); + } + + /*********************** PricingTemplate ********************** */ + + @Override + public Iterable listPricingTemplates() { + return listPricingTemplates.execute(); + } + + @Override + public Iterable listPricingTemplates(final Predicate filter) { + return listPricingTemplates.execute(filter); + } + + @Override + public PricingTemplate findPricingTemplate(final Predicate filter) { + return Iterables.getFirst(listPricingTemplates(filter), null); + } + + /*********************** CostCodeCurrency ********************** */ + + @Override + public Iterable getCostCodeCurrencies(final Integer costcodeId, final Integer currencyId) { + CostCodeCurrenciesDto result = context.getApi().getPricingApi().getCostCodeCurrencies(costcodeId, currencyId); + return wrap(context, CostCodeCurrency.class, result.getCollection()); + } + + /*********************** Pricing Cost Code ********************** */ + + @Override + public Collection getPricingCostCodes(final Integer pricingTemplateId) { + PricingCostCodesDto result = context.getApi().getPricingApi().getPricingCostCodes(pricingTemplateId); + return wrap(context, PricingCostCode.class, result.getCollection()); + } + + @Override + public PricingCostCode getPricingCostCode(final Integer pricingTemplateId, final Integer pricingCostCodeId) { + PricingCostCodeDto pricingcostcode = context.getApi().getPricingApi() + .getPricingCostCode(pricingTemplateId, pricingCostCodeId); + return wrap(context, PricingCostCode.class, pricingcostcode); + } + + /*********************** Pricing Tier********************** */ + + @Override + public Collection getPricingTiers(final Integer pricingTemplateId) { + PricingTiersDto result = context.getApi().getPricingApi().getPricingTiers(pricingTemplateId); + return wrap(context, PricingTier.class, result.getCollection()); + } + + @Override + public PricingTier getPricingTier(final Integer pricingTemplateId, final Integer pricingTierId) { + PricingTierDto pricingtier = context.getApi().getPricingApi().getPricingTier(pricingTemplateId, pricingTierId); + return wrap(context, PricingTier.class, pricingtier); + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/internal/BaseSearchService.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/internal/BaseSearchService.java new file mode 100644 index 0000000000..0326205ebb --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/internal/BaseSearchService.java @@ -0,0 +1,156 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.internal; + +import static com.google.common.base.Preconditions.checkNotNull; +import static org.jclouds.abiquo.domain.DomainWrapper.wrap; + +import java.util.List; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.domain.cloud.VirtualDatacenter; +import org.jclouds.abiquo.domain.cloud.Volume; +import org.jclouds.abiquo.domain.cloud.options.VolumeOptions; +import org.jclouds.abiquo.domain.enterprise.Enterprise; +import org.jclouds.abiquo.domain.enterprise.options.EnterpriseOptions; +import org.jclouds.abiquo.domain.infrastructure.Datacenter; +import org.jclouds.abiquo.domain.infrastructure.LogicServer; +import org.jclouds.abiquo.domain.infrastructure.ManagedRack; +import org.jclouds.abiquo.domain.infrastructure.StorageDevice; +import org.jclouds.abiquo.domain.infrastructure.StoragePool; +import org.jclouds.abiquo.domain.infrastructure.options.StoragePoolOptions; +import org.jclouds.abiquo.domain.network.PrivateIp; +import org.jclouds.abiquo.domain.network.PrivateNetwork; +import org.jclouds.abiquo.domain.network.PublicIp; +import org.jclouds.abiquo.domain.network.options.IpOptions; +import org.jclouds.abiquo.domain.options.search.FilterOptions; +import org.jclouds.abiquo.features.services.SearchService; +import org.jclouds.rest.RestContext; + +import com.abiquo.server.core.enterprise.EnterpriseDto; +import com.abiquo.server.core.infrastructure.LogicServerDto; +import com.abiquo.server.core.infrastructure.network.PrivateIpDto; +import com.abiquo.server.core.infrastructure.network.PublicIpDto; +import com.abiquo.server.core.infrastructure.storage.StoragePoolDto; +import com.abiquo.server.core.infrastructure.storage.VolumeManagementDto; +import com.google.common.annotations.VisibleForTesting; + +/** + * Provides high level Abiquo search, filter and pagination operations. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +@Singleton +public class BaseSearchService implements SearchService { + @VisibleForTesting + protected RestContext context; + + @Inject + protected BaseSearchService(final RestContext context) { + this.context = checkNotNull(context, "context"); + } + + /*********************** Enterprise ***********************/ + + @Override + public Iterable searchEnterprises(final EnterpriseOptions options) { + List enterprises = context.getApi().getEnterpriseApi().listEnterprises(options).getCollection(); + + return wrap(context, Enterprise.class, enterprises); + } + + @Override + public Iterable searchEnterprisesUsingDatacenter(final Datacenter datacenter, + final EnterpriseOptions options) { + List enterprises = context.getApi().getEnterpriseApi() + .listEnterprises(datacenter.unwrap(), options).getCollection(); + + return wrap(context, Enterprise.class, enterprises); + } + + /*********************** Volume ********************** */ + + @Override + public Iterable searchVolumes(final VirtualDatacenter virtualDatacenter, final VolumeOptions options) { + List volumes = context.getApi().getCloudApi() + .listVolumes(virtualDatacenter.unwrap(), options).getCollection(); + + return wrap(context, Volume.class, volumes); + } + + /*********************** Storage Pool ***********************/ + + @Override + public List searchStoragePools(final StorageDevice device, final StoragePoolOptions options) { + List pools = context.getApi().getInfrastructureApi().listStoragePools(device.unwrap(), options) + .getCollection(); + + return wrap(context, StoragePool.class, pools); + } + + /*********************** Private Network ***********************/ + + @Override + public Iterable searchPrivateIps(final PrivateNetwork network, final IpOptions options) { + List ips = context.getApi().getCloudApi().listPrivateNetworkIps(network.unwrap(), options) + .getCollection(); + + return wrap(context, PrivateIp.class, ips); + } + + @Override + public Iterable searchPublicIpsToPurchase(final VirtualDatacenter virtualDatacenter, + final IpOptions options) { + List ips = context.getApi().getCloudApi() + .listAvailablePublicIps(virtualDatacenter.unwrap(), options).getCollection(); + + return wrap(context, PublicIp.class, ips); + } + + @Override + public Iterable searchPurchasedPublicIps(final VirtualDatacenter virtualDatacenter, final IpOptions options) { + List ips = context.getApi().getCloudApi() + .listPurchasedPublicIps(virtualDatacenter.unwrap(), options).getCollection(); + + return wrap(context, PublicIp.class, ips); + } + + @Override + public Iterable searchServiceProfiles(final ManagedRack rack, final FilterOptions options) { + List profiles = context.getApi().getInfrastructureApi() + .listServiceProfiles(rack.unwrap(), options).getCollection(); + + return wrap(context, LogicServer.class, profiles); + } + + @Override + public Iterable searchServiceProfileTemplates(final ManagedRack rack, final FilterOptions options) { + List profiles = context.getApi().getInfrastructureApi() + .listServiceProfileTemplates(rack.unwrap(), options).getCollection(); + + return wrap(context, LogicServer.class, profiles); + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/monitor/AsyncTaskMonitor.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/monitor/AsyncTaskMonitor.java new file mode 100644 index 0000000000..b698b0838d --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/monitor/AsyncTaskMonitor.java @@ -0,0 +1,78 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.monitor; + +import java.util.concurrent.TimeUnit; + +import org.jclouds.abiquo.domain.task.AsyncTask; +import org.jclouds.abiquo.features.services.MonitoringService; +import org.jclouds.abiquo.monitor.internal.BaseAsyncTaskMonitor; + +import com.google.inject.ImplementedBy; + +/** + * {@link VirtualMachine} monitoring features. + * + * @author Ignasi Barrera + */ +@ImplementedBy(BaseAsyncTaskMonitor.class) +public interface AsyncTaskMonitor extends MonitoringService { + /** + * Monitor the given {@link AsyncTask}s and block until they finishe. + * + * @param tasks + * The {@link AsyncTask}s to monitor. + */ + void awaitCompletion(final AsyncTask... tasks); + + /** + * Monitor the given {@link AsyncTask}s and populate an event when they + * finish. + * + * @param tasks + * The {@link AsyncTask}s to monitor. + */ + public void monitor(final AsyncTask... tasks); + + /** + * Monitor the given {@link AsyncTask}s and block until they finish. + * + * @param maxWait + * The maximum time to wait. + * @param timeUnit + * The time unit for the maxWait parameter. + * @param tasks + * The {@link AsyncTask}s to monitor. + */ + void awaitCompletion(final Long maxWait, final TimeUnit timeUnit, final AsyncTask... tasks); + + /** + * Monitor the given {@link AsyncTask}s and populate an event when they + * finish. + * + * @param maxWait + * The maximum time to wait. + * @param timeUnit + * The time unit for the maxWait parameter. + * @param tasks + * The {@link AsyncTask}s to monitor. + */ + public void monitor(final Long maxWait, final TimeUnit timeUnit, final AsyncTask... tasks); +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/monitor/ConversionMonitor.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/monitor/ConversionMonitor.java new file mode 100644 index 0000000000..b293b380bb --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/monitor/ConversionMonitor.java @@ -0,0 +1,78 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.monitor; + +import java.util.concurrent.TimeUnit; + +import org.jclouds.abiquo.domain.cloud.Conversion; +import org.jclouds.abiquo.features.services.MonitoringService; +import org.jclouds.abiquo.monitor.internal.BaseConversionMonitor; + +import com.google.inject.ImplementedBy; + +/** + * {@link Conversion} monitoring features. + * + * @author Sergi Castro + */ +@ImplementedBy(BaseConversionMonitor.class) +public interface ConversionMonitor extends MonitoringService { + /** + * Monitor the given {@link Conversion}s and block until they finishes. + * + * @param conversions + * The {@link Conversion}s to monitor. + */ + void awaitCompletion(final Conversion... conversions); + + /** + * Monitor the given {@link Conversion}s and populate an event when they + * finish. + * + * @param conversions + * The {@link Conversion}s to monitor. + */ + public void monitor(final Conversion... conversions); + + /** + * Monitor the given {@link Conversion}s and block until they finish. + * + * @param maxWait + * The maximum time to wait. + * @param timeUnit + * The time unit for the maxWait parameter. + * @param conversions + * The {@link Conversion}s to monitor. + */ + void awaitCompletion(final Long maxWait, final TimeUnit timeUnit, final Conversion... conversions); + + /** + * Monitor the given {@link Conversion}s and populate an event when they + * finish. + * + * @param maxWait + * The maximum time to wait. + * @param timeUnit + * The time unit for the maxWait parameter. + * @param conversions + * The {@link Conversion}s to monitor. + */ + public void monitor(final Long maxWait, final TimeUnit timeUnit, final Conversion... conversions); +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/monitor/MonitorStatus.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/monitor/MonitorStatus.java new file mode 100644 index 0000000000..1b744a2be8 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/monitor/MonitorStatus.java @@ -0,0 +1,36 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.monitor; + +/** + * Represents the states of a running monitor. + * + * @author Serafin Sedano + */ +public enum MonitorStatus { + /** The monitoring job has finished. */ + DONE, + + /** The monitoring job has finished and the result is not the expected one. */ + FAILED, + + /** The monitoring job must continue. */ + CONTINUE +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/monitor/VirtualApplianceMonitor.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/monitor/VirtualApplianceMonitor.java new file mode 100644 index 0000000000..07766bc786 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/monitor/VirtualApplianceMonitor.java @@ -0,0 +1,126 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.monitor; + +import java.util.concurrent.TimeUnit; + +import org.jclouds.abiquo.domain.cloud.VirtualAppliance; +import org.jclouds.abiquo.features.services.MonitoringService; +import org.jclouds.abiquo.monitor.internal.BaseVirtualApplianceMonitor; + +import com.google.inject.ImplementedBy; + +/** + * {@link VirtualAppliance} monitoring features. + * + * @author Ignasi Barrera + */ +@ImplementedBy(BaseVirtualApplianceMonitor.class) +public interface VirtualApplianceMonitor extends MonitoringService { + /** + * Monitor the given {@link VirtualAppliance}s and block until the deploy + * finishes. + * + * @param vapp + * The {@link VirtualAppliance}s to monitor. + */ + void awaitCompletionDeploy(final VirtualAppliance... vapp); + + /** + * Monitor the given {@link VirtualAppliance}s and populate an event when the + * deploy finishes. + * + * @param VirtualAppliance + * The {@link VirtualAppliance}s to monitor. + */ + public void monitorDeploy(final VirtualAppliance... vapps); + + /** + * Monitor the given {@link VirtualAppliance}s and block until the deploy + * finishes. + * + * @param maxWait + * The maximum time to wait. + * @param timeUnit + * The time unit for the maxWait parameter. + * @param vapp + * The {@link VirtualAppliance}s to monitor. + */ + void awaitCompletionDeploy(final Long maxWait, final TimeUnit timeUnit, final VirtualAppliance... vapp); + + /** + * Monitor the given {@link VirtualAppliance}s and populate an event when + * deploy finishes. + * + * @param maxWait + * The maximum time to wait. + * @param timeUnit + * The time unit for the maxWait parameter. + * @param vapps + * The {@link VirtualAppliance}s to monitor. + */ + public void monitorDeploy(final Long maxWait, final TimeUnit timeUnit, final VirtualAppliance... vapps); + + /** + * Monitor the given {@link VirtualAppliance}s and block until the undeploy + * finishes. + * + * @param vapp + * The {@link VirtualAppliance}s to monitor. + */ + void awaitCompletionUndeploy(final VirtualAppliance... vapp); + + /** + * Monitor the given {@link VirtualAppliance}s and call populate an event + * when undeploy finishes. + * + * @param vapps + * The {@link VirtualAppliance}s to monitor. + */ + public void monitorUndeploy(final VirtualAppliance... vapps); + + /** + * Monitor the given {@link VirtualAppliance}s and blocks until the undeploy + * finishes. + * + * @param maxWait + * The maximum time to wait. + * @param timeUnit + * The time unit for the maxWait parameter. + * @param vapp + * The {@link VirtualAppliance}s to monitor. + */ + void awaitCompletionUndeploy(final Long maxWait, final TimeUnit timeUnit, final VirtualAppliance... vapp); + + /** + * Monitor the given {@link VirtualAppliance}s and populate an event when + * undeploy finishes. + * + * @param maxWait + * The maximum time to wait. + * @param timeUnit + * The time unit for the maxWait parameter. + * @param callback + * The callback. + * @param vapps + * The {@link VirtualAppliance}s to monitor. + */ + public void monitorUndeploy(final Long maxWait, final TimeUnit timeUnit, final VirtualAppliance... vapps); +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/monitor/VirtualMachineMonitor.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/monitor/VirtualMachineMonitor.java new file mode 100644 index 0000000000..f42bceb0d6 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/monitor/VirtualMachineMonitor.java @@ -0,0 +1,174 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.monitor; + +import java.util.concurrent.TimeUnit; + +import org.jclouds.abiquo.domain.cloud.VirtualMachine; +import org.jclouds.abiquo.features.services.MonitoringService; +import org.jclouds.abiquo.monitor.internal.BaseVirtualMachineMonitor; + +import com.abiquo.server.core.cloud.VirtualMachineState; +import com.google.inject.ImplementedBy; + +/** + * {@link VirtualMachine} monitoring features. + * + * @author Ignasi Barrera + */ +@ImplementedBy(BaseVirtualMachineMonitor.class) +public interface VirtualMachineMonitor extends MonitoringService { + /** + * Monitor the given {@link VirtualMachine}s and block until all deploys + * finish. + * + * @param vm + * The {@link VirtualMachine}s to monitor. + */ + void awaitCompletionDeploy(final VirtualMachine... vm); + + /** + * Monitor the given {@link VirtualMachine}s and populate an event when all + * deploys finish. + * + * @param vms + * The {@link VirtualMachine}s to monitor. + */ + public void monitorDeploy(final VirtualMachine... vms); + + /** + * Monitor the given {@link VirtualMachine}s and block until all deploys + * finish. + * + * @param maxWait + * The maximum time to wait. + * @param timeUnit + * The time unit for the maxWait parameter. + * @param vm + * The {@link VirtualMachine}s to monitor. + */ + void awaitCompletionDeploy(final Long maxWait, final TimeUnit timeUnit, final VirtualMachine... vm); + + /** + * Monitor the given {@link VirtualMachine}s and populate an event when all + * deploys finish. + * + * @param maxWait + * The maximum time to wait. + * @param timeUnit + * The time unit for the maxWait parameter. + * @param vms + * The {@link VirtualMachine}s to monitor. + */ + public void monitorDeploy(final Long maxWait, final TimeUnit timeUnit, final VirtualMachine... vms); + + /** + * Monitor the given {@link VirtualMachine}s and block until all undeploys + * finish. + * + * @param vm + * The {@link VirtualMachine}s to monitor. + */ + void awaitCompletionUndeploy(final VirtualMachine... vm); + + /** + * Monitor the given {@link VirtualMachine}s and populate an event when all + * undeploys finish. + * + * @param vms + * The {@link VirtualMachine}s to monitor. + */ + public void monitorUndeploy(final VirtualMachine... vms); + + /** + * Monitor the given {@link VirtualMachine}s and blocks until all undeploys + * finish. + * + * @param maxWait + * The maximum time to wait. + * @param timeUnit + * The time unit for the maxWait parameter. + * @param vm + * The {@link VirtualMachine}s to monitor. + */ + void awaitCompletionUndeploy(final Long maxWait, final TimeUnit timeUnit, final VirtualMachine... vm); + + /** + * Monitor the given {@link VirtualMachine}s and populate an event when all + * undeploys finish. + * + * @param maxWait + * The maximum time to wait. + * @param timeUnit + * The time unit for the maxWait parameter. + * @param callback + * The callback. + * @param vms + * The {@link VirtualMachine}s to monitor. + */ + public void monitorUndeploy(final Long maxWait, final TimeUnit timeUnit, final VirtualMachine... vms); + + /** + * Monitor the given {@link VirtualMachine}s and block until it is in the + * given state. + * + * @param vm + * The {@link VirtualMachine}s to monitor. + */ + void awaitState(VirtualMachineState state, final VirtualMachine... vm); + + /** + * Monitor the given {@link VirtualMachine}s and populate an event when it is + * in the given state. + * + * @param vms + * The {@link VirtualMachine}s to monitor. + */ + public void monitorState(VirtualMachineState state, final VirtualMachine... vms); + + /** + * Monitor the given {@link VirtualMachine}s and block until it is in the + * given state. + * + * @param maxWait + * The maximum time to wait. + * @param timeUnit + * The time unit for the maxWait parameter. + * @param vm + * The {@link VirtualMachine}s to monitor. + */ + void awaitState(final Long maxWait, final TimeUnit timeUnit, VirtualMachineState state, final VirtualMachine... vm); + + /** + * Monitor the given {@link VirtualMachine}s and populate an event when it is + * in the given state. + * + * @param maxWait + * The maximum time to wait. + * @param timeUnit + * The time unit for the maxWait parameter. + * @param callback + * The callback. + * @param vms + * The {@link VirtualMachine}s to monitor. + */ + public void monitorState(final Long maxWait, final TimeUnit timeUnit, VirtualMachineState state, + final VirtualMachine... vms); +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/monitor/functions/AsyncTaskStatusMonitor.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/monitor/functions/AsyncTaskStatusMonitor.java new file mode 100644 index 0000000000..433df10f86 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/monitor/functions/AsyncTaskStatusMonitor.java @@ -0,0 +1,69 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.monitor.functions; + +import static com.google.common.base.Preconditions.checkNotNull; + +import javax.annotation.Resource; +import javax.inject.Singleton; + +import org.jclouds.abiquo.domain.task.AsyncTask; +import org.jclouds.abiquo.monitor.MonitorStatus; +import org.jclouds.logging.Logger; + +import com.google.common.base.Function; + +/** + * This class takes care of monitoring {@link AsyncTask} jobs. + * + * @author Ignasi Barrera + */ +@Singleton +public class AsyncTaskStatusMonitor implements Function { + @Resource + protected Logger logger = Logger.NULL; + + @Override + public MonitorStatus apply(final AsyncTask asyncTask) { + checkNotNull(asyncTask, "asyncTask"); + + try { + asyncTask.refresh(); + + switch (asyncTask.getState()) { + case ABORTED: + case FINISHED_UNSUCCESSFULLY: + return MonitorStatus.FAILED; + case FINISHED_SUCCESSFULLY: + return MonitorStatus.DONE; + case STARTED: + case PENDING: + return MonitorStatus.CONTINUE; + default: + throw new IllegalStateException("Unsupported task status"); + } + } catch (Exception ex) { + logger.warn(ex, "exception thrown while monitoring %s on %s, returning CONTINUE", asyncTask, getClass() + .getName()); + + return MonitorStatus.CONTINUE; + } + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/monitor/functions/ConversionStatusMonitor.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/monitor/functions/ConversionStatusMonitor.java new file mode 100644 index 0000000000..357e0e53f0 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/monitor/functions/ConversionStatusMonitor.java @@ -0,0 +1,67 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.monitor.functions; + +import static com.google.common.base.Preconditions.checkNotNull; + +import javax.annotation.Resource; +import javax.inject.Singleton; + +import org.jclouds.abiquo.domain.cloud.Conversion; +import org.jclouds.abiquo.monitor.MonitorStatus; +import org.jclouds.logging.Logger; + +import com.google.common.base.Function; + +/** + * This class takes care of monitoring {@link Conversion} jobs. + * + * @author Sergi Castro + */ +@Singleton +public class ConversionStatusMonitor implements Function { + @Resource + protected Logger logger = Logger.NULL; + + @Override + public MonitorStatus apply(final Conversion conversion) { + checkNotNull(conversion, "conversion"); + + try { + conversion.refresh(); + + switch (conversion.getState()) { + case ENQUEUED: + return MonitorStatus.CONTINUE; + case FAILED: + return MonitorStatus.FAILED; + case FINISHED: + return MonitorStatus.DONE; + default: + throw new IllegalStateException("Unsupported conversion status"); + } + } catch (Exception ex) { + logger.warn(ex, "exception thrown while monitoring %s on %s, returning CONTINUE", conversion, getClass() + .getName()); + + return MonitorStatus.CONTINUE; + } + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/monitor/functions/VirtualApplianceDeployMonitor.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/monitor/functions/VirtualApplianceDeployMonitor.java new file mode 100644 index 0000000000..7a77141a2d --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/monitor/functions/VirtualApplianceDeployMonitor.java @@ -0,0 +1,70 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.monitor.functions; + +import static com.google.common.base.Preconditions.checkNotNull; + +import javax.annotation.Resource; +import javax.inject.Singleton; + +import org.jclouds.abiquo.domain.cloud.VirtualAppliance; +import org.jclouds.abiquo.monitor.MonitorStatus; +import org.jclouds.logging.Logger; + +import com.abiquo.server.core.cloud.VirtualApplianceState; +import com.google.common.base.Function; + +/** + * This class takes care of monitoring the a deploy of a + * {@link VirtualAppliance}. + * + * @author Serafin Sedano + */ +@Singleton +public class VirtualApplianceDeployMonitor implements Function { + @Resource + protected Logger logger = Logger.NULL; + + @Override + public MonitorStatus apply(final VirtualAppliance virtualAppliance) { + checkNotNull(virtualAppliance, "virtualAppliance"); + + try { + VirtualApplianceState state = virtualAppliance.getState(); + + switch (state) { + case UNKNOWN: + case NEEDS_SYNC: + case NOT_DEPLOYED: + return MonitorStatus.FAILED; + case DEPLOYED: + return MonitorStatus.DONE; + case LOCKED: + default: + return MonitorStatus.CONTINUE; + } + } catch (Exception ex) { + logger.warn(ex, "exception thrown while monitoring %s on %s, returning CONTINUE", virtualAppliance, getClass() + .getName()); + + return MonitorStatus.CONTINUE; + } + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/monitor/functions/VirtualApplianceUndeployMonitor.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/monitor/functions/VirtualApplianceUndeployMonitor.java new file mode 100644 index 0000000000..ccc0e5e69c --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/monitor/functions/VirtualApplianceUndeployMonitor.java @@ -0,0 +1,75 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.monitor.functions; + +import static com.google.common.base.Preconditions.checkNotNull; + +import javax.annotation.Resource; +import javax.inject.Singleton; + +import org.jclouds.abiquo.domain.cloud.VirtualAppliance; +import org.jclouds.abiquo.monitor.MonitorStatus; +import org.jclouds.logging.Logger; +import org.jclouds.rest.ResourceNotFoundException; + +import com.abiquo.server.core.cloud.VirtualApplianceState; +import com.google.common.base.Function; + +/** + * This class takes care of monitoring the a undeploy of a + * {@link VirtualAppliance}. + * + * @author Serafin Sedano + */ +@Singleton +public class VirtualApplianceUndeployMonitor implements Function { + @Resource + protected Logger logger = Logger.NULL; + + @Override + public MonitorStatus apply(final VirtualAppliance virtualAppliance) { + checkNotNull(virtualAppliance, "virtualAppliance"); + + try { + VirtualApplianceState state = virtualAppliance.getState(); + + switch (state) { + case DEPLOYED: + case UNKNOWN: + case NEEDS_SYNC: + return MonitorStatus.FAILED; + case NOT_DEPLOYED: + return MonitorStatus.DONE; + case LOCKED: + default: + return MonitorStatus.CONTINUE; + } + } catch (ResourceNotFoundException nfe) { + logger.warn("virtual appliance %s not found, assuming it was undeployed successfully, " + + "stop monitor with DONE", virtualAppliance); + return MonitorStatus.DONE; + } catch (Exception ex) { + logger.warn(ex, "exception thrown while monitoring %s on %s, returning CONTINUE", virtualAppliance, getClass() + .getName()); + + return MonitorStatus.CONTINUE; + } + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/monitor/functions/VirtualMachineDeployMonitor.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/monitor/functions/VirtualMachineDeployMonitor.java new file mode 100644 index 0000000000..13da1dfb7e --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/monitor/functions/VirtualMachineDeployMonitor.java @@ -0,0 +1,68 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.monitor.functions; + +import static com.google.common.base.Preconditions.checkNotNull; + +import javax.annotation.Resource; + +import org.jclouds.abiquo.domain.cloud.VirtualMachine; +import org.jclouds.abiquo.monitor.MonitorStatus; +import org.jclouds.logging.Logger; + +import com.abiquo.server.core.cloud.VirtualMachineState; +import com.google.common.base.Function; +import com.google.inject.Singleton; + +/** + * This class takes care of monitoring the a deploy of a {@link VirtualMachine}. + * + * @author Serafin Sedano + * @see MonitoringService + */ +@Singleton +public class VirtualMachineDeployMonitor implements Function { + @Resource + private Logger logger = Logger.NULL; + + @Override + public MonitorStatus apply(final VirtualMachine virtualMachine) { + checkNotNull(virtualMachine, "virtualMachine"); + + try { + VirtualMachineState state = virtualMachine.getState(); + + switch (state) { + case NOT_ALLOCATED: + case UNKNOWN: + return MonitorStatus.FAILED; + case ON: + return MonitorStatus.DONE; + default: + return MonitorStatus.CONTINUE; + } + } catch (Exception ex) { + logger.warn(ex, "exception thrown while monitoring %s on %s, returning CONTINUE", virtualMachine, getClass() + .getName()); + + return MonitorStatus.CONTINUE; + } + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/monitor/functions/VirtualMachineStateMonitor.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/monitor/functions/VirtualMachineStateMonitor.java new file mode 100644 index 0000000000..00f3bd3b87 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/monitor/functions/VirtualMachineStateMonitor.java @@ -0,0 +1,65 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.monitor.functions; + +import static com.google.common.base.Preconditions.checkNotNull; + +import javax.annotation.Resource; + +import org.jclouds.abiquo.domain.cloud.VirtualMachine; +import org.jclouds.abiquo.monitor.MonitorStatus; +import org.jclouds.logging.Logger; + +import com.abiquo.server.core.cloud.VirtualMachineState; +import com.google.common.base.Function; + +/** + * This class takes care of monitoring the state of a {@link VirtualMachine}. + * + * @author Ignasi Barrera + * @see MonitoringService + */ +public class VirtualMachineStateMonitor implements Function { + @Resource + private Logger logger = Logger.NULL; + + private VirtualMachineState expectedState; + + public VirtualMachineStateMonitor(final VirtualMachineState expectedState) { + super(); + this.expectedState = checkNotNull(expectedState, "expectedState"); + } + + @Override + public MonitorStatus apply(final VirtualMachine virtualMachine) { + checkNotNull(virtualMachine, "virtualMachine"); + + try { + VirtualMachineState state = virtualMachine.getState(); + return state == expectedState ? MonitorStatus.DONE : MonitorStatus.CONTINUE; + } catch (Exception ex) { + logger.warn(ex, "exception thrown while monitoring %s on %s, returning CONTINUE", virtualMachine, getClass() + .getName()); + + return MonitorStatus.CONTINUE; + + } + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/monitor/functions/VirtualMachineUndeployMonitor.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/monitor/functions/VirtualMachineUndeployMonitor.java new file mode 100644 index 0000000000..f1f9fb69c9 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/monitor/functions/VirtualMachineUndeployMonitor.java @@ -0,0 +1,78 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.monitor.functions; + +import static com.google.common.base.Preconditions.checkNotNull; + +import javax.annotation.Resource; +import javax.inject.Singleton; + +import org.jclouds.abiquo.domain.cloud.VirtualMachine; +import org.jclouds.abiquo.monitor.MonitorStatus; +import org.jclouds.logging.Logger; +import org.jclouds.rest.ResourceNotFoundException; + +import com.abiquo.server.core.cloud.VirtualMachineState; +import com.google.common.base.Function; + +/** + * This class takes care of monitoring the a undeploy of a + * {@link VirtualMachine}. + * + * @author Serafin Sedano + */ +@Singleton +public class VirtualMachineUndeployMonitor implements Function { + @Resource + protected Logger logger = Logger.NULL; + + @Override + public MonitorStatus apply(final VirtualMachine virtualMachine) { + checkNotNull(virtualMachine, "virtualMachine"); + + try { + VirtualMachineState state = virtualMachine.getState(); + + // This state may be reached if the undeploy process fails and a + // rollback is done + if (state.existsInHypervisor()) { + return MonitorStatus.FAILED; + } + + switch (state) { + case UNKNOWN: + return MonitorStatus.FAILED; + case NOT_ALLOCATED: + return MonitorStatus.DONE; + default: + return MonitorStatus.CONTINUE; + } + } catch (ResourceNotFoundException nfe) { + logger.warn("virtual machine %s not found, assuming it was undeployed successfully, " + + "stop monitor with DONE", virtualMachine); + return MonitorStatus.DONE; + } catch (Exception ex) { + logger.warn(ex, "exception thrown while monitoring %s on %s, returning CONTINUE", virtualMachine, getClass() + .getName()); + + return MonitorStatus.CONTINUE; + } + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/monitor/internal/BaseAsyncTaskMonitor.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/monitor/internal/BaseAsyncTaskMonitor.java new file mode 100644 index 0000000000..7d98f97fbb --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/monitor/internal/BaseAsyncTaskMonitor.java @@ -0,0 +1,84 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.monitor.internal; + +import static com.google.common.base.Preconditions.checkNotNull; +import static org.jclouds.Constants.PROPERTY_SCHEDULER_THREADS; +import static org.jclouds.abiquo.config.AbiquoProperties.ASYNC_TASK_MONITOR_DELAY; + +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; + +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.domain.task.AsyncTask; +import org.jclouds.abiquo.internal.BaseMonitoringService; +import org.jclouds.abiquo.monitor.AsyncTaskMonitor; +import org.jclouds.abiquo.monitor.functions.AsyncTaskStatusMonitor; +import org.jclouds.rest.RestContext; + +import com.google.common.annotations.VisibleForTesting; +import com.google.common.eventbus.EventBus; + +/** + * Default monitor for {@link AsyncTask} objects. + * + * @author Ignasi Barrera + */ +@Singleton +public class BaseAsyncTaskMonitor extends BaseMonitoringService implements AsyncTaskMonitor { + + @VisibleForTesting + protected AsyncTaskStatusMonitor taskMonitor; + + @Inject + public BaseAsyncTaskMonitor(final RestContext context, + @Named(PROPERTY_SCHEDULER_THREADS) final ScheduledExecutorService scheduler, + @Named(ASYNC_TASK_MONITOR_DELAY) final Long pollingDelay, final EventBus eventBus, + final AsyncTaskStatusMonitor monitor) { + super(context, scheduler, pollingDelay, eventBus); + this.taskMonitor = checkNotNull(monitor, "monitor"); + } + + @Override + public void awaitCompletion(final AsyncTask... tasks) { + awaitCompletion(taskMonitor, tasks); + } + + @Override + public void monitor(final AsyncTask... tasks) { + monitor(taskMonitor, tasks); + } + + @Override + public void awaitCompletion(final Long maxWait, final TimeUnit timeUnit, final AsyncTask... tasks) { + awaitCompletion(maxWait, timeUnit, taskMonitor, tasks); + } + + @Override + public void monitor(final Long maxWait, final TimeUnit timeUnit, final AsyncTask... tasks) { + monitor(maxWait, timeUnit, taskMonitor, tasks); + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/monitor/internal/BaseConversionMonitor.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/monitor/internal/BaseConversionMonitor.java new file mode 100644 index 0000000000..a7cff8e1b7 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/monitor/internal/BaseConversionMonitor.java @@ -0,0 +1,84 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.monitor.internal; + +import static com.google.common.base.Preconditions.checkNotNull; +import static org.jclouds.Constants.PROPERTY_SCHEDULER_THREADS; +import static org.jclouds.abiquo.config.AbiquoProperties.ASYNC_TASK_MONITOR_DELAY; + +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; + +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.domain.cloud.Conversion; +import org.jclouds.abiquo.internal.BaseMonitoringService; +import org.jclouds.abiquo.monitor.ConversionMonitor; +import org.jclouds.abiquo.monitor.functions.ConversionStatusMonitor; +import org.jclouds.rest.RestContext; + +import com.google.common.annotations.VisibleForTesting; +import com.google.common.eventbus.EventBus; + +/** + * Default monitor for {@link Conversion} objects. + * + * @author Sergi Castro + */ +@Singleton +public class BaseConversionMonitor extends BaseMonitoringService implements ConversionMonitor { + + @VisibleForTesting + protected ConversionStatusMonitor conversionMonitor; + + @Inject + public BaseConversionMonitor(final RestContext context, + @Named(PROPERTY_SCHEDULER_THREADS) final ScheduledExecutorService scheduler, + @Named(ASYNC_TASK_MONITOR_DELAY) final Long pollingDelay, final EventBus eventBus, + final ConversionStatusMonitor monitor) { + super(context, scheduler, pollingDelay, eventBus); + this.conversionMonitor = checkNotNull(monitor, "monitor"); + } + + @Override + public void awaitCompletion(final Conversion... conversions) { + awaitCompletion(conversionMonitor, conversions); + } + + @Override + public void monitor(final Conversion... conversions) { + monitor(conversionMonitor, conversions); + } + + @Override + public void awaitCompletion(final Long maxWait, final TimeUnit timeUnit, final Conversion... conversions) { + awaitCompletion(maxWait, timeUnit, conversionMonitor, conversions); + } + + @Override + public void monitor(final Long maxWait, final TimeUnit timeUnit, final Conversion... conversions) { + monitor(maxWait, timeUnit, conversionMonitor, conversions); + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/monitor/internal/BaseVirtualApplianceMonitor.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/monitor/internal/BaseVirtualApplianceMonitor.java new file mode 100644 index 0000000000..f2cd05b27e --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/monitor/internal/BaseVirtualApplianceMonitor.java @@ -0,0 +1,107 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.monitor.internal; + +import static com.google.common.base.Preconditions.checkNotNull; +import static org.jclouds.Constants.PROPERTY_SCHEDULER_THREADS; +import static org.jclouds.abiquo.config.AbiquoProperties.ASYNC_TASK_MONITOR_DELAY; + +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; + +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.domain.cloud.VirtualAppliance; +import org.jclouds.abiquo.internal.BaseMonitoringService; +import org.jclouds.abiquo.monitor.VirtualApplianceMonitor; +import org.jclouds.abiquo.monitor.functions.VirtualApplianceDeployMonitor; +import org.jclouds.abiquo.monitor.functions.VirtualApplianceUndeployMonitor; +import org.jclouds.rest.RestContext; + +import com.google.common.annotations.VisibleForTesting; +import com.google.common.eventbus.EventBus; + +/** + * Default monitor for {@link VirtualAppliance} objects. + * + * @author Ignasi Barrera + */ +@Singleton +public class BaseVirtualApplianceMonitor extends BaseMonitoringService implements VirtualApplianceMonitor { + @VisibleForTesting + protected VirtualApplianceDeployMonitor deployMonitor; + + @VisibleForTesting + protected VirtualApplianceUndeployMonitor undeployMonitor; + + @Inject + public BaseVirtualApplianceMonitor(final RestContext context, + @Named(PROPERTY_SCHEDULER_THREADS) final ScheduledExecutorService scheduler, + @Named(ASYNC_TASK_MONITOR_DELAY) final Long pollingDelay, final EventBus eventBus, + final VirtualApplianceDeployMonitor deployMonitor, final VirtualApplianceUndeployMonitor undeployMonitor) { + super(context, scheduler, pollingDelay, eventBus); + this.deployMonitor = checkNotNull(deployMonitor, "deployMonitor"); + this.undeployMonitor = checkNotNull(undeployMonitor, "undeployMonitor"); + } + + @Override + public void awaitCompletionDeploy(final VirtualAppliance... vapps) { + awaitCompletion(deployMonitor, vapps); + } + + @Override + public void monitorDeploy(final VirtualAppliance... vapps) { + monitor(deployMonitor, vapps); + } + + @Override + public void awaitCompletionDeploy(final Long maxWait, final TimeUnit timeUnit, final VirtualAppliance... vapps) { + awaitCompletion(maxWait, timeUnit, deployMonitor, vapps); + } + + @Override + public void monitorDeploy(final Long maxWait, final TimeUnit timeUnit, final VirtualAppliance... vapps) { + monitor(maxWait, timeUnit, deployMonitor, vapps); + } + + @Override + public void awaitCompletionUndeploy(final VirtualAppliance... vapps) { + awaitCompletion(undeployMonitor, vapps); + } + + @Override + public void monitorUndeploy(final VirtualAppliance... vapps) { + monitor(undeployMonitor, vapps); + } + + @Override + public void awaitCompletionUndeploy(final Long maxWait, final TimeUnit timeUnit, final VirtualAppliance... vapps) { + awaitCompletion(maxWait, timeUnit, undeployMonitor, vapps); + } + + @Override + public void monitorUndeploy(final Long maxWait, final TimeUnit timeUnit, final VirtualAppliance... vapps) { + monitor(maxWait, timeUnit, undeployMonitor, vapps); + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/monitor/internal/BaseVirtualMachineMonitor.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/monitor/internal/BaseVirtualMachineMonitor.java new file mode 100644 index 0000000000..e1bf8f41db --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/monitor/internal/BaseVirtualMachineMonitor.java @@ -0,0 +1,131 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.monitor.internal; + +import static com.google.common.base.Preconditions.checkNotNull; +import static org.jclouds.Constants.PROPERTY_SCHEDULER_THREADS; +import static org.jclouds.abiquo.config.AbiquoProperties.ASYNC_TASK_MONITOR_DELAY; + +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; + +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.domain.cloud.VirtualMachine; +import org.jclouds.abiquo.internal.BaseMonitoringService; +import org.jclouds.abiquo.monitor.VirtualMachineMonitor; +import org.jclouds.abiquo.monitor.functions.VirtualMachineDeployMonitor; +import org.jclouds.abiquo.monitor.functions.VirtualMachineStateMonitor; +import org.jclouds.abiquo.monitor.functions.VirtualMachineUndeployMonitor; +import org.jclouds.rest.RestContext; + +import com.abiquo.server.core.cloud.VirtualMachineState; +import com.google.common.annotations.VisibleForTesting; +import com.google.common.eventbus.EventBus; + +/** + * Default monitor for {@link VirtualMachine} objects. + * + * @author Ignasi Barrera + */ +@Singleton +public class BaseVirtualMachineMonitor extends BaseMonitoringService implements VirtualMachineMonitor { + @VisibleForTesting + protected VirtualMachineDeployMonitor deployMonitor; + + @VisibleForTesting + protected VirtualMachineUndeployMonitor undeployMonitor; + + @Inject + public BaseVirtualMachineMonitor(final RestContext context, + @Named(PROPERTY_SCHEDULER_THREADS) final ScheduledExecutorService scheduler, + @Named(ASYNC_TASK_MONITOR_DELAY) final Long pollingDelay, final EventBus eventBus, + final VirtualMachineDeployMonitor deployMonitor, final VirtualMachineUndeployMonitor undeployMonitor) { + super(context, scheduler, pollingDelay, eventBus); + this.deployMonitor = checkNotNull(deployMonitor, "deployMonitor"); + this.undeployMonitor = checkNotNull(undeployMonitor, "undeployMonitor"); + } + + @Override + public void awaitCompletionDeploy(final VirtualMachine... vms) { + awaitCompletion(deployMonitor, vms); + } + + @Override + public void monitorDeploy(final VirtualMachine... vms) { + monitor(deployMonitor, vms); + } + + @Override + public void awaitCompletionDeploy(final Long maxWait, final TimeUnit timeUnit, final VirtualMachine... vms) { + awaitCompletion(maxWait, timeUnit, deployMonitor, vms); + } + + @Override + public void monitorDeploy(final Long maxWait, final TimeUnit timeUnit, final VirtualMachine... vms) { + monitor(maxWait, timeUnit, deployMonitor, vms); + } + + @Override + public void awaitCompletionUndeploy(final VirtualMachine... vms) { + awaitCompletion(undeployMonitor, vms); + } + + @Override + public void monitorUndeploy(final VirtualMachine... vms) { + monitor(undeployMonitor, vms); + } + + @Override + public void awaitCompletionUndeploy(final Long maxWait, final TimeUnit timeUnit, final VirtualMachine... vms) { + awaitCompletion(maxWait, timeUnit, undeployMonitor, vms); + } + + @Override + public void monitorUndeploy(final Long maxWait, final TimeUnit timeUnit, final VirtualMachine... vms) { + monitor(maxWait, timeUnit, undeployMonitor, vms); + } + + @Override + public void awaitState(final VirtualMachineState state, final VirtualMachine... vms) { + awaitCompletion(new VirtualMachineStateMonitor(state), vms); + } + + @Override + public void monitorState(final VirtualMachineState state, final VirtualMachine... vms) { + monitor(new VirtualMachineStateMonitor(state), vms); + } + + @Override + public void awaitState(final Long maxWait, final TimeUnit timeUnit, final VirtualMachineState state, + final VirtualMachine... vms) { + awaitCompletion(maxWait, timeUnit, new VirtualMachineStateMonitor(state), vms); + } + + @Override + public void monitorState(final Long maxWait, final TimeUnit timeUnit, final VirtualMachineState state, + final VirtualMachine... vms) { + monitor(maxWait, timeUnit, new VirtualMachineStateMonitor(state), vms); + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/ErrorPredicates.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/ErrorPredicates.java new file mode 100644 index 0000000000..2a5f2c427b --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/ErrorPredicates.java @@ -0,0 +1,45 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.predicates; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.Arrays; + +import com.abiquo.model.transport.error.ErrorDto; +import com.google.common.base.Predicate; + +/** + * Container for {@link ErrorDto} filters. + * + * @author Ignasi Barrera + */ +public class ErrorPredicates { + public static Predicate code(final String... codes) { + checkNotNull(codes, "codes must be defined"); + + return new Predicate() { + @Override + public boolean apply(final ErrorDto error) { + return Arrays.asList(codes).contains(error.getCode()); + } + }; + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/LinkPredicates.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/LinkPredicates.java new file mode 100644 index 0000000000..bd512284ae --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/LinkPredicates.java @@ -0,0 +1,54 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.predicates; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.Arrays; + +import com.abiquo.model.rest.RESTLink; +import com.google.common.base.Predicate; + +/** + * Container for {@link RESTLink} filters. + * + * @author Ignasi Barrera + */ +public class LinkPredicates { + public static Predicate rel(final String... rels) { + checkNotNull(rels, "rels must be defined"); + + return new Predicate() { + @Override + public boolean apply(final RESTLink link) { + return Arrays.asList(rels).contains(link.getRel()); + } + }; + } + + public static Predicate isNic() { + return new Predicate() { + @Override + public boolean apply(final RESTLink link) { + return link.getRel().matches("^nic[0-9]+$"); + } + }; + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/cloud/ConversionPredicates.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/cloud/ConversionPredicates.java new file mode 100644 index 0000000000..14379d9cd7 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/cloud/ConversionPredicates.java @@ -0,0 +1,85 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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.abiquo.predicates.cloud; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.Arrays; + +import org.jclouds.abiquo.domain.cloud.Conversion; +import org.jclouds.abiquo.domain.cloud.VirtualMachineTemplate; + +import com.abiquo.model.enumerator.ConversionState; +import com.abiquo.model.enumerator.DiskFormatType; +import com.abiquo.model.enumerator.HypervisorType; +import com.google.common.base.Predicate; + +/** + * Container for {@link VirtualMachineTemplate} filters. + * + * @author Francesc Montserrat + */ +public class ConversionPredicates { + + public static Predicate sourceFormat(final DiskFormatType... formats) { + checkNotNull(formats, "formats must be defined"); + + return new Predicate() { + @Override + public boolean apply(final Conversion conversion) { + return Arrays.asList(formats).contains(conversion.getSourceFormat()); + } + }; + } + + public static Predicate targetFormat(final DiskFormatType... formats) { + checkNotNull(formats, "formats must be defined"); + + return new Predicate() { + @Override + public boolean apply(final Conversion conversion) { + return Arrays.asList(formats).contains(conversion.getTargetFormat()); + } + }; + } + + public static Predicate state(final ConversionState... states) { + checkNotNull(states, "states must be defined"); + + return new Predicate() { + @Override + public boolean apply(final Conversion conversion) { + return Arrays.asList(states).contains(conversion.getState()); + } + }; + } + + public static Predicate compatible(final HypervisorType type) { + checkNotNull(type, "type must be defined"); + + return new Predicate() { + @Override + public boolean apply(final Conversion conversion) { + return type.isCompatible(conversion.getTargetFormat()); + } + }; + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/cloud/VirtualAppliancePredicates.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/cloud/VirtualAppliancePredicates.java new file mode 100644 index 0000000000..35b5cba0b6 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/cloud/VirtualAppliancePredicates.java @@ -0,0 +1,58 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.predicates.cloud; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.Arrays; + +import org.jclouds.abiquo.domain.cloud.VirtualAppliance; + +import com.abiquo.server.core.cloud.VirtualApplianceState; +import com.google.common.base.Predicate; + +/** + * Container for {@link VirtualAppliance} filters. + * + * @author Serafín Sedano + */ +public class VirtualAppliancePredicates { + public static Predicate name(final String... names) { + checkNotNull(names, "names must be defined"); + + return new Predicate() { + @Override + public boolean apply(final VirtualAppliance virtualAppliance) { + return Arrays.asList(names).contains(virtualAppliance.getName()); + } + }; + } + + public static Predicate state(final VirtualApplianceState... states) { + checkNotNull(states, "states must be defined"); + + return new Predicate() { + @Override + public boolean apply(final VirtualAppliance virtualAppliance) { + return Arrays.asList(states).contains(virtualAppliance.getState()); + } + }; + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/cloud/VirtualDatacenterPredicates.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/cloud/VirtualDatacenterPredicates.java new file mode 100644 index 0000000000..81f3b4956a --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/cloud/VirtualDatacenterPredicates.java @@ -0,0 +1,117 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.predicates.cloud; + +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.collect.Iterables.transform; + +import java.util.Arrays; +import java.util.List; + +import org.jclouds.abiquo.domain.cloud.Conversion; +import org.jclouds.abiquo.domain.cloud.VirtualDatacenter; +import org.jclouds.abiquo.domain.cloud.VirtualMachineTemplate; +import org.jclouds.abiquo.domain.infrastructure.Datacenter; +import org.jclouds.abiquo.reference.ValidationErrors; +import org.jclouds.abiquo.reference.rest.ParentLinkName; + +import com.abiquo.model.enumerator.ConversionState; +import com.abiquo.model.enumerator.HypervisorType; +import com.google.common.base.Function; +import com.google.common.base.Predicate; +import com.google.common.collect.Lists; + +/** + * Container for {@link VirtualDatacenter} filters. + * + * @author Ignasi Barrera + */ +public class VirtualDatacenterPredicates { + public static Predicate name(final String... names) { + checkNotNull(names, "names must be defined"); + + return new Predicate() { + @Override + public boolean apply(final VirtualDatacenter virtualDatacenter) { + return Arrays.asList(names).contains(virtualDatacenter.getName()); + } + }; + } + + public static Predicate type(final HypervisorType... types) { + checkNotNull(types, "types must be defined"); + + return new Predicate() { + @Override + public boolean apply(final VirtualDatacenter virtualDatacenter) { + return Arrays.asList(types).contains(virtualDatacenter.getHypervisorType()); + } + }; + } + + public static Predicate datacenter(final Datacenter... datacenters) { + checkNotNull(datacenters, "datacenters must be defined"); + + final List ids = Lists.newArrayList(transform(Arrays.asList(datacenters), + new Function() { + @Override + public Integer apply(final Datacenter input) { + return input.getId(); + } + })); + + return new Predicate() { + @Override + public boolean apply(final VirtualDatacenter virtualDatacenter) { + // Avoid using the getDatacenter() method since it will generate an + // unnecessary API + // call. We can get the ID from the datacenter link. + Integer datacenterId = checkNotNull(virtualDatacenter.unwrap().getIdFromLink(ParentLinkName.DATACENTER), + ValidationErrors.MISSING_REQUIRED_LINK); + + return ids.contains(datacenterId); + } + }; + } + + /** + * Check if the given template type is compatible with the given virtual + * datacenter type taking into account the conversions of the template. + * + * @param template + * The template to check. + * @return Predicate to check if the template or its conversions are + * compatibles with the given virtual datacenter. + */ + public static Predicate compatibleWithTemplateOrConversions(final VirtualMachineTemplate template) { + return new Predicate() { + @Override + public boolean apply(final VirtualDatacenter vdc) { + HypervisorType type = vdc.getHypervisorType(); + boolean compatible = type.isCompatible(template.getDiskFormatType()); + if (!compatible) { + List compatibleConversions = template.listConversions(type, ConversionState.FINISHED); + compatible = compatibleConversions != null && !compatibleConversions.isEmpty(); + } + return compatible; + } + }; + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/cloud/VirtualMachinePredicates.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/cloud/VirtualMachinePredicates.java new file mode 100644 index 0000000000..bc2c95e17e --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/cloud/VirtualMachinePredicates.java @@ -0,0 +1,70 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.predicates.cloud; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.Arrays; + +import org.jclouds.abiquo.domain.cloud.VirtualMachine; + +import com.abiquo.server.core.cloud.VirtualMachineState; +import com.google.common.base.Predicate; + +/** + * Container for {@link VirtualMachine} filters. + * + * @author Ignasi Barrera + */ +public class VirtualMachinePredicates { + public static Predicate internalName(final String... internalName) { + checkNotNull(internalName, "names must be defined"); + + return new Predicate() { + @Override + public boolean apply(final VirtualMachine virtualMachine) { + return Arrays.asList(internalName).contains(virtualMachine.getInternalName()); + } + }; + } + + public static Predicate nameLabel(final String... nameLabels) { + checkNotNull(nameLabels, "names must be defined"); + + return new Predicate() { + @Override + public boolean apply(final VirtualMachine virtualMachine) { + return Arrays.asList(nameLabels).contains(virtualMachine.getNameLabel()); + } + }; + } + + public static Predicate state(final VirtualMachineState... states) { + checkNotNull(states, "states must be defined"); + + return new Predicate() { + @Override + public boolean apply(final VirtualMachine virtualMachine) { + // The getState() method will generate an API call + return Arrays.asList(states).contains(virtualMachine.getState()); + } + }; + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/cloud/VirtualMachineTemplatePredicates.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/cloud/VirtualMachineTemplatePredicates.java new file mode 100644 index 0000000000..c3277da44b --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/cloud/VirtualMachineTemplatePredicates.java @@ -0,0 +1,99 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.predicates.cloud; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.Arrays; + +import org.jclouds.abiquo.domain.cloud.VirtualMachineTemplate; + +import com.abiquo.model.enumerator.DiskFormatType; +import com.abiquo.model.enumerator.HypervisorType; +import com.google.common.base.Predicate; + +/** + * Container for {@link VirtualMachineTemplate} filters. + * + * @author Francesc Montserrat + */ +public class VirtualMachineTemplatePredicates { + public static Predicate id(final Integer... ids) { + checkNotNull(ids, "ids must be defined"); + + return new Predicate() { + @Override + public boolean apply(final VirtualMachineTemplate template) { + return Arrays.asList(ids).contains(template.getId()); + } + }; + } + + public static Predicate name(final String... names) { + checkNotNull(names, "names must be defined"); + + return new Predicate() { + @Override + public boolean apply(final VirtualMachineTemplate template) { + return Arrays.asList(names).contains(template.getName()); + } + }; + } + + public static Predicate diskFormat(final DiskFormatType... formats) { + checkNotNull(formats, "formats must be defined"); + + return new Predicate() { + @Override + public boolean apply(final VirtualMachineTemplate template) { + return Arrays.asList(formats).contains(template.getDiskFormatType()); + } + }; + } + + public static Predicate compatible(final HypervisorType type) { + checkNotNull(type, "type must be defined"); + + return new Predicate() { + @Override + public boolean apply(final VirtualMachineTemplate template) { + return type.isCompatible(template.getDiskFormatType()); + } + }; + } + + public static Predicate isShared() { + return new Predicate() { + @Override + public boolean apply(final VirtualMachineTemplate input) { + return input.unwrap().isShared(); + } + }; + } + + public static Predicate isInstance() { + return new Predicate() { + @Override + public boolean apply(final VirtualMachineTemplate input) { + return input.unwrap().searchLink("master") != null; + } + }; + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/cloud/VolumePredicates.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/cloud/VolumePredicates.java new file mode 100644 index 0000000000..0b012a664b --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/cloud/VolumePredicates.java @@ -0,0 +1,89 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.predicates.cloud; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.Arrays; + +import org.jclouds.abiquo.domain.cloud.Volume; + +import com.abiquo.model.enumerator.VolumeState; +import com.google.common.base.Predicate; +import com.google.common.base.Predicates; + +/** + * Container for {@link Volume} filters. + * + * @author Ignasi Barrera + */ +public class VolumePredicates { + public static Predicate name(final String... names) { + checkNotNull(names, "names must be defined"); + + return new Predicate() { + @Override + public boolean apply(final Volume volume) { + return Arrays.asList(names).contains(volume.getName()); + } + }; + } + + public static Predicate greaterThan(final long sizeInMb) { + checkNotNull(sizeInMb, "sizeInMb must be defined"); + + return new Predicate() { + @Override + public boolean apply(final Volume volume) { + return volume.getSizeInMB() > sizeInMb; + } + }; + } + + public static Predicate greaterThanOrEqual(final long sizeInMb) { + checkNotNull(sizeInMb, "sizeInMb must be defined"); + + return new Predicate() { + @Override + public boolean apply(final Volume volume) { + return volume.getSizeInMB() >= sizeInMb; + } + }; + } + + public static Predicate lesserThan(final long sizeInMb) { + return Predicates.not(greaterThanOrEqual(sizeInMb)); + } + + public static Predicate lesserThanOrEquals(final long sizeInMb) { + return Predicates.not(greaterThan(sizeInMb)); + } + + public static Predicate state(final VolumeState... states) { + checkNotNull(states, "states must be defined"); + + return new Predicate() { + @Override + public boolean apply(final Volume volume) { + return Arrays.asList(states).contains(VolumeState.valueOf(volume.getState())); + } + }; + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/config/CategoryPredicates.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/config/CategoryPredicates.java new file mode 100644 index 0000000000..0d172a4970 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/config/CategoryPredicates.java @@ -0,0 +1,48 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.predicates.config; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.Arrays; + +import org.jclouds.abiquo.domain.config.Category; + +import com.google.common.base.Predicate; + +/** + * Container for {@link Category} filters. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +public class CategoryPredicates { + public static Predicate name(final String... names) { + checkNotNull(names, "names must be defined"); + + return new Predicate() { + @Override + public boolean apply(final Category category) { + return Arrays.asList(names).contains(category.getName()); + } + }; + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/config/LicensePredicates.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/config/LicensePredicates.java new file mode 100644 index 0000000000..a845cc26be --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/config/LicensePredicates.java @@ -0,0 +1,57 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.predicates.config; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.Arrays; + +import org.jclouds.abiquo.domain.config.License; + +import com.google.common.base.Predicate; + +/** + * Container for {@link License} filters. + * + * @author Ignasi Barrera + */ +public class LicensePredicates { + public static Predicate customer(final String... customerIds) { + checkNotNull(customerIds, "customers must be defined"); + + return new Predicate() { + @Override + public boolean apply(final License license) { + return Arrays.asList(customerIds).contains(license.getCustomerId()); + } + }; + } + + public static Predicate code(final String... codes) { + checkNotNull(codes, "customers must be defined"); + + return new Predicate() { + @Override + public boolean apply(final License license) { + return Arrays.asList(codes).contains(license.getCode()); + } + }; + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/config/PricingPredicates.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/config/PricingPredicates.java new file mode 100644 index 0000000000..cbeda4c360 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/config/PricingPredicates.java @@ -0,0 +1,71 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.predicates.config; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.Arrays; + +import org.jclouds.abiquo.domain.config.CostCode; +import org.jclouds.abiquo.domain.config.Currency; +import org.jclouds.abiquo.domain.config.PricingTemplate; + +import com.google.common.base.Predicate; + +/** + * Container for pricing related filters. + * + * @author Ignasi Barrera + * @author Susana Acedo + */ +public class PricingPredicates { + public static Predicate currency(final String... names) { + checkNotNull(names, "names must be defined"); + + return new Predicate() { + @Override + public boolean apply(final Currency currency) { + return Arrays.asList(names).contains(currency.getName()); + } + }; + } + + public static Predicate costCode(final String... names) { + checkNotNull(names, "names must be defined"); + + return new Predicate() { + @Override + public boolean apply(final CostCode costcode) { + return Arrays.asList(names).contains(costcode.getName()); + } + }; + } + + public static Predicate pricingTemplate(final String... names) { + checkNotNull(names, "names must be defined"); + + return new Predicate() { + @Override + public boolean apply(final PricingTemplate pricingTemplate) { + return Arrays.asList(names).contains(pricingTemplate.getName()); + } + }; + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/config/PrivilegePredicates.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/config/PrivilegePredicates.java new file mode 100644 index 0000000000..93e4510915 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/config/PrivilegePredicates.java @@ -0,0 +1,47 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.predicates.config; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.Arrays; + +import org.jclouds.abiquo.domain.config.Privilege; + +import com.google.common.base.Predicate; + +/** + * Container for {@link Privilege} filters. + * + * @author Ignasi Barrera + */ +public class PrivilegePredicates { + public static Predicate name(final String... names) { + checkNotNull(names, "names must be defined"); + + return new Predicate() { + @Override + public boolean apply(final Privilege privilege) { + return Arrays.asList(names).contains(privilege.getName()); + } + }; + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/config/SystemPropertyPredicates.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/config/SystemPropertyPredicates.java new file mode 100644 index 0000000000..b0b04aaa5d --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/config/SystemPropertyPredicates.java @@ -0,0 +1,48 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.predicates.config; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.Arrays; + +import org.jclouds.abiquo.domain.config.SystemProperty; + +import com.google.common.base.Predicate; + +/** + * Container for {@link SystemProperty} filters. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +public class SystemPropertyPredicates { + public static Predicate name(final String... names) { + checkNotNull(names, "names must be defined"); + + return new Predicate() { + @Override + public boolean apply(final SystemProperty property) { + return Arrays.asList(names).contains(property.getName()); + } + }; + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/enterprise/EnterprisePredicates.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/enterprise/EnterprisePredicates.java new file mode 100644 index 0000000000..b7eaf33234 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/enterprise/EnterprisePredicates.java @@ -0,0 +1,46 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.predicates.enterprise; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.Arrays; + +import org.jclouds.abiquo.domain.enterprise.Enterprise; + +import com.google.common.base.Predicate; + +/** + * Container for {@link Enterprise} filters. + * + * @author Ignasi Barrera + */ +public class EnterprisePredicates { + public static Predicate name(final String... names) { + checkNotNull(names, "names must be defined"); + + return new Predicate() { + @Override + public boolean apply(final Enterprise enterprise) { + return Arrays.asList(names).contains(enterprise.getName()); + } + }; + } +} diff --git a/antcontrib/samples/javaoverssh/src/TestClass.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/enterprise/RolePredicates.java similarity index 53% rename from antcontrib/samples/javaoverssh/src/TestClass.java rename to labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/enterprise/RolePredicates.java index eb5481dc46..0226f12263 100644 --- a/antcontrib/samples/javaoverssh/src/TestClass.java +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/enterprise/RolePredicates.java @@ -7,7 +7,7 @@ * "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 + * 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 @@ -16,19 +16,31 @@ * specific language governing permissions and limitations * under the License. */ -import java.io.File; + +package org.jclouds.abiquo.predicates.enterprise; + +import static com.google.common.base.Preconditions.checkNotNull; + import java.util.Arrays; -public class TestClass { - public static void main(String... args) { - File cwd = new File(System.getProperty("user.dir")); - System.out.println("children:"); - for (File child : cwd.listFiles()) - System.out.println(" " + child); - System.out.println("what you wrote:"); - System.out.println(Arrays.asList(args)); - System.err.println("this is the error stream"); - System.out.println("will exit 3:"); - System.exit(3); +import org.jclouds.abiquo.domain.enterprise.Role; + +import com.google.common.base.Predicate; + +/** + * Container for {@link Role} filters. + * + * @author Ignasi Barrera + */ +public class RolePredicates { + public static Predicate name(final String... names) { + checkNotNull(names, "names must be defined"); + + return new Predicate() { + @Override + public boolean apply(final Role role) { + return Arrays.asList(names).contains(role.getName()); + } + }; } } diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/enterprise/TemplateDefinitionListPredicates.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/enterprise/TemplateDefinitionListPredicates.java new file mode 100644 index 0000000000..5cd228a3c2 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/enterprise/TemplateDefinitionListPredicates.java @@ -0,0 +1,47 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.predicates.enterprise; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.Arrays; + +import org.jclouds.abiquo.domain.enterprise.TemplateDefinitionList; + +import com.google.common.base.Predicate; + +/** + * Container for {@link TemplateDefinitionList} filters. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +public class TemplateDefinitionListPredicates { + public static Predicate name(final String... names) { + checkNotNull(names, "names must be defined"); + + return new Predicate() { + @Override + public boolean apply(final TemplateDefinitionList templateList) { + return Arrays.asList(names).contains(templateList.getName()); + } + }; + } +} diff --git a/antcontrib/src/test/java/org/jclouds/tools/ant/TestClass.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/enterprise/UserPredicates.java similarity index 53% rename from antcontrib/src/test/java/org/jclouds/tools/ant/TestClass.java rename to labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/enterprise/UserPredicates.java index 3a8a994513..d910d345c0 100644 --- a/antcontrib/src/test/java/org/jclouds/tools/ant/TestClass.java +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/enterprise/UserPredicates.java @@ -7,7 +7,7 @@ * "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 + * 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 @@ -16,23 +16,31 @@ * specific language governing permissions and limitations * under the License. */ -package org.jclouds.tools.ant; -import java.io.File; +package org.jclouds.abiquo.predicates.enterprise; + +import static com.google.common.base.Preconditions.checkNotNull; + import java.util.Arrays; -public class TestClass { - public static void main(String... args) { - System.out.println("env:"); - System.out.println(System.getenv(args[0])); - File cwd = new File(System.getProperty("user.dir")); - System.out.println("children:"); - for (File child : cwd.listFiles()) - System.out.println(" " + child); - System.out.println("what you wrote:"); - System.out.println(Arrays.asList(args)); - System.err.println("this is the error stream"); - System.out.println("will exit 3:"); - System.exit(3); +import org.jclouds.abiquo.domain.enterprise.User; + +import com.google.common.base.Predicate; + +/** + * Container for {@link User} filters. + * + * @author Ignasi Barrera + */ +public class UserPredicates { + public static Predicate nick(final String... nicks) { + checkNotNull(nicks, "nicks must be defined"); + + return new Predicate() { + @Override + public boolean apply(final User user) { + return Arrays.asList(nicks).contains(user.getNick()); + } + }; } -} \ No newline at end of file +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/infrastructure/BladePredicates.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/infrastructure/BladePredicates.java new file mode 100644 index 0000000000..5e857b2f5a --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/infrastructure/BladePredicates.java @@ -0,0 +1,62 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.predicates.infrastructure; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.Arrays; + +import org.jclouds.abiquo.domain.infrastructure.Blade; + +import com.google.common.base.Predicate; + +/** + * Container for {@link Blade} filters. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +public class BladePredicates { + public static Predicate name(final String... names) { + checkNotNull(names, "name must be defined"); + + return new Predicate() { + @Override + public boolean apply(final Blade machine) { + return Arrays.asList(names).contains(machine.getName()); + } + }; + } + + public static Predicate ip(final String ip) { + return ips(checkNotNull(ip, "ip must be defined")); + } + + public static Predicate ips(final String... ips) { + checkNotNull(ips, "ips must be defined"); + + return new Predicate() { + @Override + public boolean apply(final Blade machine) { + return Arrays.asList(ips).contains(machine.getIp()); + } + }; + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/infrastructure/DatacenterPredicates.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/infrastructure/DatacenterPredicates.java new file mode 100644 index 0000000000..f68b40d325 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/infrastructure/DatacenterPredicates.java @@ -0,0 +1,68 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.predicates.infrastructure; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.Arrays; + +import org.jclouds.abiquo.domain.infrastructure.Datacenter; + +import com.google.common.base.Predicate; + +/** + * Container for {@link Datacenter} filters. + * + * @author Ignasi Barrera + */ +public class DatacenterPredicates { + public static Predicate id(final Integer... ids) { + checkNotNull(ids, "ids must be defined"); + + return new Predicate() { + @Override + public boolean apply(final Datacenter datacenter) { + return Arrays.asList(ids).contains(datacenter.getId()); + } + }; + } + + public static Predicate name(final String... names) { + checkNotNull(names, "names must be defined"); + + return new Predicate() { + @Override + public boolean apply(final Datacenter datacenter) { + return Arrays.asList(names).contains(datacenter.getName()); + } + }; + } + + public static Predicate location(final String... locations) { + checkNotNull(locations, "locations must be defined"); + + return new Predicate() { + @Override + public boolean apply(final Datacenter datacenter) { + return Arrays.asList(locations).contains(datacenter.getLocation()); + } + }; + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/infrastructure/DatastorePredicates.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/infrastructure/DatastorePredicates.java new file mode 100644 index 0000000000..ff135d7494 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/infrastructure/DatastorePredicates.java @@ -0,0 +1,46 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.predicates.infrastructure; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.Arrays; + +import org.jclouds.abiquo.domain.infrastructure.Datastore; + +import com.google.common.base.Predicate; + +/** + * Container for {@link Datastore} filters. + * + * @author Ignasi Barrera + */ +public class DatastorePredicates { + public static Predicate name(final String... names) { + checkNotNull(names, "names must be defined"); + + return new Predicate() { + @Override + public boolean apply(final Datastore datastore) { + return Arrays.asList(names).contains(datastore.getName()); + } + }; + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/infrastructure/HypervisorPredicates.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/infrastructure/HypervisorPredicates.java new file mode 100644 index 0000000000..07cbca22fc --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/infrastructure/HypervisorPredicates.java @@ -0,0 +1,46 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.predicates.infrastructure; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.Arrays; + +import com.abiquo.model.enumerator.HypervisorType; +import com.google.common.base.Predicate; + +/** + * Container for {@link HypervisorType} filters. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +public class HypervisorPredicates { + public static Predicate type(final HypervisorType... types) { + checkNotNull(types, "types must be defined"); + + return new Predicate() { + @Override + public boolean apply(final HypervisorType type) { + return Arrays.asList(types).contains(type); + } + }; + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/infrastructure/LogicServerPredicates.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/infrastructure/LogicServerPredicates.java new file mode 100644 index 0000000000..d185b08283 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/infrastructure/LogicServerPredicates.java @@ -0,0 +1,46 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.predicates.infrastructure; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.Arrays; + +import org.jclouds.abiquo.domain.infrastructure.LogicServer; + +import com.google.common.base.Predicate; + +/** + * Container for {@link LogicServer} filters. + * + * @author Francesc Montserrat + */ +public class LogicServerPredicates { + public static Predicate name(final String... names) { + checkNotNull(names, "names must be defined"); + + return new Predicate() { + @Override + public boolean apply(final LogicServer logicServer) { + return Arrays.asList(names).contains(logicServer.getName()); + } + }; + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/infrastructure/MachinePredicates.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/infrastructure/MachinePredicates.java new file mode 100644 index 0000000000..f7bfb3add7 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/infrastructure/MachinePredicates.java @@ -0,0 +1,62 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.predicates.infrastructure; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.Arrays; + +import org.jclouds.abiquo.domain.infrastructure.Machine; + +import com.google.common.base.Predicate; + +/** + * Container for {@link Machine} filters. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +public class MachinePredicates { + public static Predicate name(final String... names) { + checkNotNull(names, "name must be defined"); + + return new Predicate() { + @Override + public boolean apply(final Machine machine) { + return Arrays.asList(names).contains(machine.getName()); + } + }; + } + + public static Predicate ip(final String ip) { + return ips(checkNotNull(ip, "ip must be defined")); + } + + public static Predicate ips(final String... ips) { + checkNotNull(ips, "ips must be defined"); + + return new Predicate() { + @Override + public boolean apply(final Machine machine) { + return Arrays.asList(ips).contains(machine.getIp()); + } + }; + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/infrastructure/ManagedRackPredicates.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/infrastructure/ManagedRackPredicates.java new file mode 100644 index 0000000000..51b6771cb2 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/infrastructure/ManagedRackPredicates.java @@ -0,0 +1,47 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.predicates.infrastructure; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.Arrays; + +import org.jclouds.abiquo.domain.infrastructure.ManagedRack; + +import com.google.common.base.Predicate; + +/** + * Container for {@link ManagedRack} filters. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +public class ManagedRackPredicates { + public static Predicate name(final String... names) { + checkNotNull(names, "names must be defined"); + + return new Predicate() { + @Override + public boolean apply(final ManagedRack rack) { + return Arrays.asList(names).contains(rack.getName()); + } + }; + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/infrastructure/RackPredicates.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/infrastructure/RackPredicates.java new file mode 100644 index 0000000000..9b418632bf --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/infrastructure/RackPredicates.java @@ -0,0 +1,47 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.predicates.infrastructure; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.Arrays; + +import org.jclouds.abiquo.domain.infrastructure.Rack; + +import com.google.common.base.Predicate; + +/** + * Container for {@link Rack} filters. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +public class RackPredicates { + public static Predicate name(final String... names) { + checkNotNull(names, "names must be defined"); + + return new Predicate() { + @Override + public boolean apply(final Rack rack) { + return Arrays.asList(names).contains(rack.getName()); + } + }; + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/infrastructure/RemoteServicePredicates.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/infrastructure/RemoteServicePredicates.java new file mode 100644 index 0000000000..8b7cf7daaa --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/infrastructure/RemoteServicePredicates.java @@ -0,0 +1,48 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.predicates.infrastructure; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.Arrays; + +import org.jclouds.abiquo.domain.infrastructure.RemoteService; + +import com.abiquo.model.enumerator.RemoteServiceType; +import com.google.common.base.Predicate; + +/** + * Container for {@link RemoteService} filters. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +public class RemoteServicePredicates { + public static Predicate type(final RemoteServiceType... types) { + checkNotNull(types, "types must be defined"); + + return new Predicate() { + @Override + public boolean apply(final RemoteService remoteService) { + return Arrays.asList(types).contains(remoteService.getType()); + } + }; + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/infrastructure/StorageDeviceMetadataPredicates.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/infrastructure/StorageDeviceMetadataPredicates.java new file mode 100644 index 0000000000..52ce2106e4 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/infrastructure/StorageDeviceMetadataPredicates.java @@ -0,0 +1,47 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.predicates.infrastructure; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.Arrays; + +import org.jclouds.abiquo.domain.infrastructure.StorageDeviceMetadata; + +import com.google.common.base.Predicate; + +/** + * Container for {@link StorageDeviceMetadata} filters. + * + * @author Ignasi Barrera + */ +public class StorageDeviceMetadataPredicates { + + public static Predicate type(final String... types) { + checkNotNull(types, "types must be defined"); + + return new Predicate() { + @Override + public boolean apply(final StorageDeviceMetadata metadata) { + return Arrays.asList(types).contains(metadata.getType()); + } + }; + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/infrastructure/StorageDevicePredicates.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/infrastructure/StorageDevicePredicates.java new file mode 100644 index 0000000000..e957057205 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/infrastructure/StorageDevicePredicates.java @@ -0,0 +1,69 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.predicates.infrastructure; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.Arrays; + +import org.jclouds.abiquo.domain.infrastructure.StorageDevice; + +import com.google.common.base.Predicate; + +/** + * Container for {@link StorageDevice} filters. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +public class StorageDevicePredicates { + public static Predicate name(final String... names) { + checkNotNull(names, "names must be defined"); + + return new Predicate() { + @Override + public boolean apply(final StorageDevice storageDevice) { + return Arrays.asList(names).contains(storageDevice.getName()); + } + }; + } + + public static Predicate managementIp(final String... ips) { + checkNotNull(ips, "managementIps must be defined"); + + return new Predicate() { + @Override + public boolean apply(final StorageDevice storageDevice) { + return Arrays.asList(ips).contains(storageDevice.getManagementIp()); + } + }; + } + + public static Predicate type(final String... types) { + checkNotNull(types, "types must be defined"); + + return new Predicate() { + @Override + public boolean apply(final StorageDevice storageDevice) { + return Arrays.asList(types).contains(storageDevice.getType()); + } + }; + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/infrastructure/StoragePoolPredicates.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/infrastructure/StoragePoolPredicates.java new file mode 100644 index 0000000000..7cfc033c5e --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/infrastructure/StoragePoolPredicates.java @@ -0,0 +1,47 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.predicates.infrastructure; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.Arrays; + +import org.jclouds.abiquo.domain.infrastructure.StoragePool; + +import com.google.common.base.Predicate; + +/** + * Container for {@link StoragePool} filters. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +public class StoragePoolPredicates { + public static Predicate name(final String... names) { + checkNotNull(names, "names must be defined"); + + return new Predicate() { + @Override + public boolean apply(final StoragePool storagePool) { + return Arrays.asList(names).contains(storagePool.getName()); + } + }; + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/infrastructure/TierPredicates.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/infrastructure/TierPredicates.java new file mode 100644 index 0000000000..7ae1047b47 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/infrastructure/TierPredicates.java @@ -0,0 +1,47 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.predicates.infrastructure; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.Arrays; + +import org.jclouds.abiquo.domain.infrastructure.Tier; + +import com.google.common.base.Predicate; + +/** + * Container for {@link Tier} filters. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +public class TierPredicates { + public static Predicate name(final String... names) { + checkNotNull(names, "names must be defined"); + + return new Predicate() { + @Override + public boolean apply(final Tier tier) { + return Arrays.asList(names).contains(tier.getName()); + } + }; + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/network/IpPredicates.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/network/IpPredicates.java new file mode 100644 index 0000000000..38aa9f2393 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/network/IpPredicates.java @@ -0,0 +1,77 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.predicates.network; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.Arrays; + +import org.jclouds.abiquo.domain.network.AbstractPublicIp; +import org.jclouds.abiquo.domain.network.Ip; +import org.jclouds.abiquo.domain.network.Network; + +import com.google.common.base.Predicate; + +/** + * Container for {@link Network} filters. + * + * @author Francesc Montserrat + */ +public class IpPredicates { + public static > Predicate name(final String... names) { + checkNotNull(names, "names must be defined"); + + return new Predicate() { + @Override + public boolean apply(final T address) { + return Arrays.asList(names).contains(address.getName()); + } + }; + } + + public static > Predicate address(final String... addresses) { + checkNotNull(addresses, "addresses must be defined"); + + return new Predicate() { + @Override + public boolean apply(final T address) { + return Arrays.asList(addresses).contains(address.getIp()); + } + }; + } + + public static > Predicate available() { + return new Predicate() { + @Override + public boolean apply(final T address) { + return address.isAvailable(); + } + }; + } + + public static > Predicate notUsed() { + return new Predicate() { + @Override + public boolean apply(final T address) { + return address.unwrap().searchLink("virtualmachine") == null; + } + }; + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/network/NetworkPredicates.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/network/NetworkPredicates.java new file mode 100644 index 0000000000..440d829c73 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/network/NetworkPredicates.java @@ -0,0 +1,47 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.predicates.network; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.Arrays; + +import org.jclouds.abiquo.domain.network.Ip; +import org.jclouds.abiquo.domain.network.Network; + +import com.google.common.base.Predicate; + +/** + * Container for {@link Network} filters. + * + * @author Francesc Montserrat + */ +public class NetworkPredicates { + public static > Predicate> name(final String... names) { + checkNotNull(names, "names must be defined"); + + return new Predicate>() { + @Override + public boolean apply(final Network network) { + return Arrays.asList(names).contains(network.getName()); + } + }; + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/network/NicPredicates.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/network/NicPredicates.java new file mode 100644 index 0000000000..35477fb91f --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/network/NicPredicates.java @@ -0,0 +1,57 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.predicates.network; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.Arrays; + +import org.jclouds.abiquo.domain.network.Nic; + +import com.google.common.base.Predicate; + +/** + * Container for {@link Nic} filters. + * + * @author Francesc Montserrat + */ +public class NicPredicates { + public static Predicate ip(final String... ips) { + checkNotNull(ips, "ips must be defined"); + + return new Predicate() { + @Override + public boolean apply(final Nic nic) { + return Arrays.asList(ips).contains(nic.getIp()); + } + }; + } + + public static Predicate mac(final String... macs) { + checkNotNull(macs, "macs must be defined"); + + return new Predicate() { + @Override + public boolean apply(final Nic nic) { + return Arrays.asList(macs).contains(nic.getMac()); + } + }; + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/task/AsyncTaskPredicates.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/task/AsyncTaskPredicates.java new file mode 100644 index 0000000000..73c74f0711 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/predicates/task/AsyncTaskPredicates.java @@ -0,0 +1,47 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.predicates.task; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.Arrays; + +import org.jclouds.abiquo.domain.task.AsyncTask; + +import com.abiquo.server.core.task.enums.TaskState; +import com.google.common.base.Predicate; + +/** + * Container for {@link AsyncTask} filters. + * + * @author Ignasi Barrera + */ +public class AsyncTaskPredicates { + public static Predicate state(final TaskState... states) { + checkNotNull(states, "states must be defined"); + + return new Predicate() { + @Override + public boolean apply(final AsyncTask task) { + return Arrays.asList(states).contains(task.getState()); + } + }; + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/reference/ValidationErrors.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/reference/ValidationErrors.java new file mode 100644 index 0000000000..7b04c84a25 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/reference/ValidationErrors.java @@ -0,0 +1,36 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.reference; + +/** + * Error constants. + * + * @author Francesc Montserrat + */ +public class ValidationErrors { + public static final String NULL_RESOURCE = "The resource should be assigned to a "; + + public static final String MISSING_REQUIRED_FIELD = "Missing required field "; + + public static final String MISSING_REQUIRED_LINK = "Missing required link "; + + public static final String INVALID_NETWORK_TYPE = "Invalid network type "; + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/reference/annotations/EnterpriseEdition.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/reference/annotations/EnterpriseEdition.java new file mode 100644 index 0000000000..4513c0ffd2 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/reference/annotations/EnterpriseEdition.java @@ -0,0 +1,34 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.reference.annotations; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +/** + * Indicates that the annotated element will access Abiquo Enterprise Edition + * functionallity. If the target Abiquo Cloud platform is a Community Edition + * version, the invocation of the method may have unexpected results. + * + * @author Ignasi Barrera + */ +@Retention(RetentionPolicy.RUNTIME) +public @interface EnterpriseEdition { +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/reference/rest/ParentLinkName.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/reference/rest/ParentLinkName.java new file mode 100644 index 0000000000..416b6d690f --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/reference/rest/ParentLinkName.java @@ -0,0 +1,65 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.reference.rest; + +/** + * Names of the "rel" attribute of the links that point to parent objects. + * + * @author Francesc Montserrat + */ +public class ParentLinkName { + public final static String RACK = "rack"; + + public final static String DATACENTER = "datacenter"; + + public final static String ENTERPRISE = "enterprise"; + + public final static String ROLE = "role"; + + public final static String TIER = "tier"; + + public final static String STORAGE_DEVICE = "device"; + + public final static String VIRTUAL_DATACENTER = "virtualdatacenter"; + + public final static String VIRTUAL_APPLIANCE = "virtualappliance"; + + public final static String VIRTUAL_MACHINE_TEMPLATE = "virtualmachinetemplate"; + + public final static String DATACENTER_REPOSITORY = "datacenterrepository"; + + public final static String COST_CODE = "costcode"; + + public final static String CATEGORY = "category"; + + public final static String ICON = "icon"; + + public final static String PRIVATE_NETWORK = "privatenetwork"; + + public final static String PUBLIC_NETWORK = "publicnetwork"; + + public final static String EXTERNAL_NETWORK = "externalnetwork"; + + public final static String UNMANAGED_NETWORK = "unmanagednetwork"; + + public final static String NETWORK_CONFIGURATIONS = "configurations"; + + public final static String NETWORK_GATEWAY = "network_configuration"; +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/rest/annotations/EndpointLink.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/rest/annotations/EndpointLink.java new file mode 100644 index 0000000000..d87b2315da --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/rest/annotations/EndpointLink.java @@ -0,0 +1,40 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.rest.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Indicates the link to be used to generate the enpoind for the request. + * + * @author Ignasi Barrera + */ +@Target({ ElementType.PARAMETER }) +@Retention(RetentionPolicy.RUNTIME) +public @interface EndpointLink { + + /** + * The name of the link that will be used to generate the request endpoint. + */ + String value(); +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/rest/internal/AbiquoHttpAsyncClient.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/rest/internal/AbiquoHttpAsyncClient.java new file mode 100644 index 0000000000..16da2e5f4b --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/rest/internal/AbiquoHttpAsyncClient.java @@ -0,0 +1,49 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.rest.internal; + +import javax.ws.rs.GET; + +import org.jclouds.abiquo.binders.BindLinkToPathAndAcceptHeader; +import org.jclouds.abiquo.http.filters.AbiquoAuthentication; +import org.jclouds.abiquo.http.filters.AppendApiVersionToMediaType; +import org.jclouds.http.HttpResponse; +import org.jclouds.rest.annotations.BinderParam; +import org.jclouds.rest.annotations.ExceptionParser; +import org.jclouds.rest.annotations.RequestFilters; +import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; + +import com.abiquo.model.rest.RESTLink; +import com.google.common.util.concurrent.ListenableFuture; + +/** + * Custom Rest methods to work with the Abiquo Api. + * + * @author Ignasi Barrera + */ +@RequestFilters({ AbiquoAuthentication.class, AppendApiVersionToMediaType.class }) +public interface AbiquoHttpAsyncClient { + /** + * @see AbiquoHttpClient#get(RESTLink) + */ + @GET + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + public ListenableFuture get(@BinderParam(BindLinkToPathAndAcceptHeader.class) final RESTLink link); +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/rest/internal/AbiquoHttpClient.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/rest/internal/AbiquoHttpClient.java new file mode 100644 index 0000000000..9b42778976 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/rest/internal/AbiquoHttpClient.java @@ -0,0 +1,44 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.rest.internal; + +import java.util.concurrent.TimeUnit; + +import org.jclouds.concurrent.Timeout; +import org.jclouds.http.HttpResponse; + +import com.abiquo.model.rest.RESTLink; + +/** + * Custom Rest methods to work with the Abiquo Api. + * + * @author Ignasi Barrera + */ +@Timeout(duration = 30, timeUnit = TimeUnit.SECONDS) +public interface AbiquoHttpClient { + /** + * Perform a GET request to the given link. + * + * @param link + * The link to get. + * @return The response. + */ + public HttpResponse get(final RESTLink link); +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/rest/internal/ExtendedUtils.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/rest/internal/ExtendedUtils.java new file mode 100644 index 0000000000..6dc4bff595 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/rest/internal/ExtendedUtils.java @@ -0,0 +1,78 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.rest.internal; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.Map; +import java.util.concurrent.ExecutorService; + +import javax.inject.Inject; +import javax.inject.Named; + +import org.jclouds.Constants; +import org.jclouds.crypto.Crypto; +import org.jclouds.date.DateService; +import org.jclouds.domain.Credentials; +import org.jclouds.json.Json; +import org.jclouds.logging.Logger.LoggerFactory; +import org.jclouds.rest.HttpAsyncClient; +import org.jclouds.rest.HttpClient; +import org.jclouds.rest.Utils; +import org.jclouds.rest.internal.UtilsImpl; +import org.jclouds.xml.XMLParser; + +import com.google.common.eventbus.EventBus; +import com.google.inject.Injector; +import com.google.inject.Singleton; + +/** + * Custom utility methods. + * + * @author Ignasi Barrera + */ +@Singleton +public class ExtendedUtils extends UtilsImpl implements Utils { + private AbiquoHttpClient abiquoHttpClient; + + private AbiquoHttpAsyncClient abiquoHttpAsyncApi; + + @Inject + public ExtendedUtils(final Injector injector, final Json json, final XMLParser xml, final HttpClient simpleApi, + final HttpAsyncClient simpleAsyncApi, final Crypto encryption, final DateService date, + @Named(Constants.PROPERTY_USER_THREADS) final ExecutorService userThreads, + @Named(Constants.PROPERTY_IO_WORKER_THREADS) final ExecutorService ioThreads, final EventBus eventBus, + final Map credentialStore, final LoggerFactory loggerFactory, + final AbiquoHttpClient abiquoHttpClient, final AbiquoHttpAsyncClient abiquoHttpAsyncApi) { + super(injector, json, xml, simpleApi, simpleAsyncApi, encryption, date, userThreads, ioThreads, eventBus, + credentialStore, loggerFactory); + this.abiquoHttpClient = checkNotNull(abiquoHttpClient, "abiquoHttpClient"); + this.abiquoHttpAsyncApi = checkNotNull(abiquoHttpAsyncApi, "abiquoHttpAsyncApi"); + } + + public AbiquoHttpClient getAbiquoHttpClient() { + return abiquoHttpClient; + } + + public AbiquoHttpAsyncClient getAbiquoHttpAsyncClient() { + return abiquoHttpAsyncApi; + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/ListEntities.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/ListEntities.java new file mode 100644 index 0000000000..2606517d02 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/ListEntities.java @@ -0,0 +1,35 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.strategy; + +import org.jclouds.abiquo.domain.DomainWrapper; + +import com.google.common.base.Predicate; + +/** + * List all entities of the given type. + * + * @author Ignasi Barrera + */ +public interface ListEntities, P extends DomainWrapper> { + Iterable execute(P parent); + + Iterable execute(P parent, Predicate selector); +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/ListRootEntities.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/ListRootEntities.java new file mode 100644 index 0000000000..255eb2f08d --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/ListRootEntities.java @@ -0,0 +1,35 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.strategy; + +import org.jclouds.abiquo.domain.DomainWrapper; + +import com.google.common.base.Predicate; + +/** + * List all entities of the given type. + * + * @author Ignasi Barrera + */ +public interface ListRootEntities> { + Iterable execute(); + + Iterable execute(Predicate selector); +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/admin/ListRoles.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/admin/ListRoles.java new file mode 100644 index 0000000000..3ff98c1c7a --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/admin/ListRoles.java @@ -0,0 +1,36 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.strategy.admin; + +import org.jclouds.abiquo.domain.enterprise.Role; +import org.jclouds.abiquo.strategy.ListRootEntities; +import org.jclouds.abiquo.strategy.admin.internal.ListRolesImpl; + +import com.google.inject.ImplementedBy; + +/** + * List roles. + * + * @author Ignasi Barrera + */ +@ImplementedBy(ListRolesImpl.class) +public interface ListRoles extends ListRootEntities { + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/admin/internal/ListRolesImpl.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/admin/internal/ListRolesImpl.java new file mode 100644 index 0000000000..0e6d5f0bf4 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/admin/internal/ListRolesImpl.java @@ -0,0 +1,67 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.strategy.admin.internal; + +import static com.google.common.collect.Iterables.filter; +import static org.jclouds.abiquo.domain.DomainWrapper.wrap; + +import javax.inject.Singleton; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.domain.enterprise.Role; +import org.jclouds.abiquo.strategy.admin.ListRoles; +import org.jclouds.rest.RestContext; + +import com.abiquo.server.core.enterprise.RolesDto; +import com.google.common.base.Predicate; +import com.google.inject.Inject; + +/** + * List enterprises. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +@Singleton +public class ListRolesImpl implements ListRoles { + // This strategy does not have still an Executor instance because the current + // methods call + // single api methods + + protected final RestContext context; + + @Inject + ListRolesImpl(final RestContext context) { + this.context = context; + } + + @Override + public Iterable execute() { + RolesDto result = context.getApi().getAdminApi().listRoles(); + return wrap(context, Role.class, result.getCollection()); + } + + @Override + public Iterable execute(final Predicate selector) { + return filter(execute(), selector); + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/cloud/ListAttachedNics.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/cloud/ListAttachedNics.java new file mode 100644 index 0000000000..81e7aa4d95 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/cloud/ListAttachedNics.java @@ -0,0 +1,37 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.strategy.cloud; + +import org.jclouds.abiquo.domain.cloud.VirtualMachine; +import org.jclouds.abiquo.domain.network.Ip; +import org.jclouds.abiquo.strategy.ListEntities; +import org.jclouds.abiquo.strategy.cloud.internal.ListAttachedNicsImpl; + +import com.google.inject.ImplementedBy; + +/** + * List all NICs attached to a given virtual machine. + * + * @author Ignasi Barrera + */ +@ImplementedBy(ListAttachedNicsImpl.class) +public interface ListAttachedNics extends ListEntities, VirtualMachine> { + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/cloud/ListVirtualAppliances.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/cloud/ListVirtualAppliances.java new file mode 100644 index 0000000000..7d286175df --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/cloud/ListVirtualAppliances.java @@ -0,0 +1,36 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.strategy.cloud; + +import org.jclouds.abiquo.domain.cloud.VirtualAppliance; +import org.jclouds.abiquo.strategy.ListRootEntities; +import org.jclouds.abiquo.strategy.cloud.internal.ListVirtualAppliancesImpl; + +import com.google.inject.ImplementedBy; + +/** + * List virtual appliances in each virtual datacenter. + * + * @author Ignasi Barrera + */ +@ImplementedBy(ListVirtualAppliancesImpl.class) +public interface ListVirtualAppliances extends ListRootEntities { + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/cloud/ListVirtualDatacenters.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/cloud/ListVirtualDatacenters.java new file mode 100644 index 0000000000..88596af86b --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/cloud/ListVirtualDatacenters.java @@ -0,0 +1,46 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.strategy.cloud; + +import java.util.List; + +import org.jclouds.abiquo.domain.cloud.VirtualDatacenter; +import org.jclouds.abiquo.domain.cloud.options.VirtualDatacenterOptions; +import org.jclouds.abiquo.strategy.ListRootEntities; +import org.jclouds.abiquo.strategy.cloud.internal.ListVirtualDatacentersImpl; + +import com.google.common.base.Predicate; +import com.google.inject.ImplementedBy; + +/** + * List virtual datacenters. + * + * @author Ignasi Barrera + */ +@ImplementedBy(ListVirtualDatacentersImpl.class) +public interface ListVirtualDatacenters extends ListRootEntities { + Iterable execute(VirtualDatacenterOptions virtualDatacenterOptions); + + Iterable execute(List virtualDatacenterIds); + + Iterable execute(Predicate selector, + VirtualDatacenterOptions virtualDatacenterOptions); + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/cloud/ListVirtualMachines.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/cloud/ListVirtualMachines.java new file mode 100644 index 0000000000..9cdea47224 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/cloud/ListVirtualMachines.java @@ -0,0 +1,37 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.strategy.cloud; + +import org.jclouds.abiquo.domain.cloud.VirtualMachine; +import org.jclouds.abiquo.domain.cloud.options.VirtualMachineOptions; +import org.jclouds.abiquo.strategy.ListRootEntities; +import org.jclouds.abiquo.strategy.cloud.internal.ListVirtualMachinesImpl; + +import com.google.inject.ImplementedBy; + +/** + * List virtual machines in each virtual datacenter and each virtual appliance. + * + * @author Ignasi Barrera + */ +@ImplementedBy(ListVirtualMachinesImpl.class) +public interface ListVirtualMachines extends ListRootEntities { + Iterable execute(VirtualMachineOptions options); +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/cloud/internal/ListAttachedNicsImpl.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/cloud/internal/ListAttachedNicsImpl.java new file mode 100644 index 0000000000..b577339fd8 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/cloud/internal/ListAttachedNicsImpl.java @@ -0,0 +1,116 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.strategy.cloud.internal; + +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.collect.Iterables.filter; +import static com.google.common.collect.Iterables.transform; +import static org.jclouds.abiquo.domain.DomainWrapper.wrap; + +import javax.inject.Singleton; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.domain.cloud.VirtualMachine; +import org.jclouds.abiquo.domain.network.ExternalIp; +import org.jclouds.abiquo.domain.network.Ip; +import org.jclouds.abiquo.domain.network.PrivateIp; +import org.jclouds.abiquo.domain.network.PublicIp; +import org.jclouds.abiquo.domain.network.UnmanagedIp; +import org.jclouds.abiquo.domain.util.LinkUtils; +import org.jclouds.abiquo.rest.internal.ExtendedUtils; +import org.jclouds.abiquo.strategy.cloud.ListAttachedNics; +import org.jclouds.http.HttpResponse; +import org.jclouds.http.functions.ParseXMLWithJAXB; +import org.jclouds.rest.RestContext; + +import com.abiquo.model.rest.RESTLink; +import com.abiquo.server.core.infrastructure.network.ExternalIpDto; +import com.abiquo.server.core.infrastructure.network.PrivateIpDto; +import com.abiquo.server.core.infrastructure.network.PublicIpDto; +import com.abiquo.server.core.infrastructure.network.UnmanagedIpDto; +import com.google.common.base.Function; +import com.google.common.base.Predicate; +import com.google.inject.Inject; +import com.google.inject.TypeLiteral; + +/** + * List all NICs attached to a given virtual machine. + * + * @author Ignasi Barrera + */ +@Singleton +public class ListAttachedNicsImpl implements ListAttachedNics { + protected final RestContext context; + + protected final ExtendedUtils extendedUtils; + + @Inject + public ListAttachedNicsImpl(final RestContext context, final ExtendedUtils extendedUtils) { + this.context = checkNotNull(context, "context"); + this.extendedUtils = checkNotNull(extendedUtils, "extendedUtils"); + } + + @Override + public Iterable> execute(final VirtualMachine parent) { + parent.refresh(); + Iterable nicLinks = LinkUtils.filterNicLinks(parent.unwrap().getLinks()); + return listIps(nicLinks); + } + + @Override + public Iterable> execute(final VirtualMachine parent, final Predicate> selector) { + return filter(execute(parent), selector); + } + + private Iterable> listIps(final Iterable nicLinks) { + return transform(nicLinks, new Function>() { + @Override + public Ip apply(final RESTLink input) { + HttpResponse response = extendedUtils.getAbiquoHttpClient().get(input); + + if (input.getType().equals(PrivateIpDto.BASE_MEDIA_TYPE)) { + ParseXMLWithJAXB parser = new ParseXMLWithJAXB(extendedUtils.getXml(), + TypeLiteral.get(PrivateIpDto.class)); + + return wrap(context, PrivateIp.class, parser.apply(response)); + } else if (input.getType().equals(PublicIpDto.BASE_MEDIA_TYPE)) { + ParseXMLWithJAXB parser = new ParseXMLWithJAXB(extendedUtils.getXml(), + TypeLiteral.get(PublicIpDto.class)); + + return wrap(context, PublicIp.class, parser.apply(response)); + } else if (input.getType().equals(ExternalIpDto.BASE_MEDIA_TYPE)) { + ParseXMLWithJAXB parser = new ParseXMLWithJAXB(extendedUtils.getXml(), + TypeLiteral.get(ExternalIpDto.class)); + + return wrap(context, ExternalIp.class, parser.apply(response)); + } else if (input.getType().equals(UnmanagedIpDto.BASE_MEDIA_TYPE)) { + ParseXMLWithJAXB parser = new ParseXMLWithJAXB(extendedUtils.getXml(), + TypeLiteral.get(UnmanagedIpDto.class)); + + return wrap(context, UnmanagedIp.class, parser.apply(response)); + } else { + throw new IllegalArgumentException("Unsupported media type: " + input.getType()); + } + } + }); + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/cloud/internal/ListVirtualAppliancesImpl.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/cloud/internal/ListVirtualAppliancesImpl.java new file mode 100644 index 0000000000..1d6025ed7f --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/cloud/internal/ListVirtualAppliancesImpl.java @@ -0,0 +1,106 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.strategy.cloud.internal; + +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.collect.Iterables.filter; +import static org.jclouds.abiquo.domain.DomainWrapper.wrap; +import static org.jclouds.concurrent.FutureIterables.transformParallel; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; + +import javax.annotation.Resource; +import javax.inject.Named; +import javax.inject.Singleton; + +import org.jclouds.Constants; +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.domain.DomainWrapper; +import org.jclouds.abiquo.domain.cloud.VirtualAppliance; +import org.jclouds.abiquo.domain.cloud.VirtualDatacenter; +import org.jclouds.abiquo.strategy.cloud.ListVirtualAppliances; +import org.jclouds.abiquo.strategy.cloud.ListVirtualDatacenters; +import org.jclouds.logging.Logger; +import org.jclouds.rest.RestContext; + +import com.abiquo.server.core.cloud.VirtualApplianceDto; +import com.abiquo.server.core.cloud.VirtualAppliancesDto; +import com.google.common.base.Function; +import com.google.common.base.Predicate; +import com.google.inject.Inject; + +/** + * List virtual appliance in each virtual datacenter. + * + * @author Ignasi Barrera + */ +@Singleton +public class ListVirtualAppliancesImpl implements ListVirtualAppliances { + protected final RestContext context; + + protected final ListVirtualDatacenters listVirtualDatacenters; + + protected final ExecutorService userExecutor; + + @Resource + protected Logger logger = Logger.NULL; + + @Inject(optional = true) + @Named(Constants.PROPERTY_REQUEST_TIMEOUT) + protected Long maxTime; + + @Inject + ListVirtualAppliancesImpl(final RestContext context, + @Named(Constants.PROPERTY_USER_THREADS) final ExecutorService userExecutor, + final ListVirtualDatacenters listVirtualDatacenters) { + this.context = checkNotNull(context, "context"); + this.listVirtualDatacenters = checkNotNull(listVirtualDatacenters, "listVirtualDatacenters"); + this.userExecutor = checkNotNull(userExecutor, "userExecutor"); + } + + @Override + public Iterable execute() { + // Find virtual appliances in concurrent requests + Iterable vdcs = listVirtualDatacenters.execute(); + Iterable vapps = listConcurrentVirtualAppliances(vdcs); + + return wrap(context, VirtualAppliance.class, vapps); + } + + @Override + public Iterable execute(final Predicate selector) { + return filter(execute(), selector); + } + + private Iterable listConcurrentVirtualAppliances(final Iterable vdcs) { + Iterable vapps = transformParallel(vdcs, + new Function>() { + @Override + public Future apply(final VirtualDatacenter input) { + return context.getAsyncApi().getCloudApi().listVirtualAppliances(input.unwrap()); + } + }, userExecutor, maxTime, logger, "getting virtual appliances"); + + return DomainWrapper.join(vapps); + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/cloud/internal/ListVirtualDatacentersImpl.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/cloud/internal/ListVirtualDatacentersImpl.java new file mode 100644 index 0000000000..50f775c337 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/cloud/internal/ListVirtualDatacentersImpl.java @@ -0,0 +1,119 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.strategy.cloud.internal; + +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.collect.Iterables.filter; +import static org.jclouds.abiquo.domain.DomainWrapper.wrap; +import static org.jclouds.concurrent.FutureIterables.transformParallel; + +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; + +import javax.annotation.Resource; +import javax.inject.Named; +import javax.inject.Singleton; + +import org.jclouds.Constants; +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.domain.DomainWrapper; +import org.jclouds.abiquo.domain.cloud.VirtualDatacenter; +import org.jclouds.abiquo.domain.cloud.options.VirtualDatacenterOptions; +import org.jclouds.abiquo.strategy.cloud.ListVirtualDatacenters; +import org.jclouds.logging.Logger; +import org.jclouds.rest.RestContext; + +import com.abiquo.server.core.cloud.VirtualDatacenterDto; +import com.abiquo.server.core.cloud.VirtualDatacentersDto; +import com.google.common.base.Function; +import com.google.common.base.Predicate; +import com.google.common.collect.Lists; +import com.google.inject.Inject; + +/** + * List virtual datacenters. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +@Singleton +public class ListVirtualDatacentersImpl implements ListVirtualDatacenters { + protected final RestContext context; + + protected final ExecutorService userExecutor; + + @Resource + protected Logger logger = Logger.NULL; + + @Inject(optional = true) + @Named(Constants.PROPERTY_REQUEST_TIMEOUT) + protected Long maxTime; + + @Inject + ListVirtualDatacentersImpl(final RestContext context, + @Named(Constants.PROPERTY_USER_THREADS) final ExecutorService userExecutor) { + this.context = checkNotNull(context, "context"); + this.userExecutor = checkNotNull(userExecutor, "userExecutor"); + } + + @Override + public Iterable execute() { + VirtualDatacenterOptions virtualDatacenterOptions = VirtualDatacenterOptions.builder().build(); + + return execute(virtualDatacenterOptions); + } + + @Override + public Iterable execute(final Predicate selector) { + return filter(execute(), selector); + } + + @Override + public Iterable execute(final VirtualDatacenterOptions virtualDatacenterOptions) { + VirtualDatacentersDto result = context.getApi().getCloudApi().listVirtualDatacenters(virtualDatacenterOptions); + return wrap(context, VirtualDatacenter.class, result.getCollection()); + } + + @Override + public Iterable execute(final Predicate selector, + final VirtualDatacenterOptions virtualDatacenterOptions) { + return filter(execute(virtualDatacenterOptions), selector); + } + + @Override + public Iterable execute(final List virtualDatacenterIds) { + // Find virtual datacenters in concurrent requests + return listConcurrentVirtualDatacenters(virtualDatacenterIds); + } + + private Iterable listConcurrentVirtualDatacenters(final List ids) { + Iterable vdcs = transformParallel(ids, + new Function>() { + @Override + public Future apply(final Integer input) { + return context.getAsyncApi().getCloudApi().getVirtualDatacenter(input); + } + }, userExecutor, maxTime, logger, "getting virtual datacenters"); + + return DomainWrapper.wrap(context, VirtualDatacenter.class, Lists.newArrayList(vdcs)); + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/cloud/internal/ListVirtualMachinesImpl.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/cloud/internal/ListVirtualMachinesImpl.java new file mode 100644 index 0000000000..d094fb9545 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/cloud/internal/ListVirtualMachinesImpl.java @@ -0,0 +1,114 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.strategy.cloud.internal; + +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.collect.Iterables.filter; +import static org.jclouds.abiquo.domain.DomainWrapper.wrap; +import static org.jclouds.concurrent.FutureIterables.transformParallel; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; + +import javax.annotation.Resource; +import javax.inject.Named; +import javax.inject.Singleton; + +import org.jclouds.Constants; +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.domain.DomainWrapper; +import org.jclouds.abiquo.domain.cloud.VirtualAppliance; +import org.jclouds.abiquo.domain.cloud.VirtualMachine; +import org.jclouds.abiquo.domain.cloud.options.VirtualMachineOptions; +import org.jclouds.abiquo.strategy.cloud.ListVirtualAppliances; +import org.jclouds.abiquo.strategy.cloud.ListVirtualMachines; +import org.jclouds.logging.Logger; +import org.jclouds.rest.RestContext; + +import com.abiquo.server.core.cloud.VirtualMachineWithNodeExtendedDto; +import com.abiquo.server.core.cloud.VirtualMachinesWithNodeExtendedDto; +import com.google.common.base.Function; +import com.google.common.base.Predicate; +import com.google.inject.Inject; + +/** + * List virtual machines in each virtual datacenter and each virtual appliance. + * + * @author Ignasi Barrera + */ +@Singleton +public class ListVirtualMachinesImpl implements ListVirtualMachines { + protected final RestContext context; + + protected final ExecutorService userExecutor; + + protected final ListVirtualAppliances listVirtualAppliances; + + @Resource + protected Logger logger = Logger.NULL; + + @Inject(optional = true) + @Named(Constants.PROPERTY_REQUEST_TIMEOUT) + protected Long maxTime; + + @Inject + ListVirtualMachinesImpl(final RestContext context, + @Named(Constants.PROPERTY_USER_THREADS) final ExecutorService userExecutor, + final ListVirtualAppliances listVirtualAppliances) { + super(); + this.context = checkNotNull(context, "context"); + this.listVirtualAppliances = checkNotNull(listVirtualAppliances, "listVirtualAppliances"); + this.userExecutor = checkNotNull(userExecutor, "userExecutor"); + } + + @Override + public Iterable execute() { + return execute(VirtualMachineOptions.builder().disablePagination().build()); + } + + @Override + public Iterable execute(final VirtualMachineOptions options) { + // Find virtual machines in concurrent requests + Iterable vapps = listVirtualAppliances.execute(); + Iterable vms = listConcurrentVirtualMachines(vapps, options); + + return wrap(context, VirtualMachine.class, vms); + } + + @Override + public Iterable execute(final Predicate selector) { + return filter(execute(), selector); + } + + private Iterable listConcurrentVirtualMachines( + final Iterable vapps, final VirtualMachineOptions options) { + Iterable vms = transformParallel(vapps, + new Function>() { + @Override + public Future apply(final VirtualAppliance input) { + return context.getAsyncApi().getCloudApi().listVirtualMachines(input.unwrap(), options); + } + }, userExecutor, maxTime, logger, "getting virtual machines"); + + return DomainWrapper.join(vms); + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/config/ListCategories.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/config/ListCategories.java new file mode 100644 index 0000000000..61314cdbba --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/config/ListCategories.java @@ -0,0 +1,35 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.strategy.config; + +import org.jclouds.abiquo.domain.config.Category; +import org.jclouds.abiquo.strategy.ListRootEntities; +import org.jclouds.abiquo.strategy.config.internal.ListCategoriesImpl; + +import com.google.inject.ImplementedBy; + +/** + * List privileges. + * + * @author Ignasi Barrera + */ +@ImplementedBy(ListCategoriesImpl.class) +public interface ListCategories extends ListRootEntities { +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/config/ListCostCodes.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/config/ListCostCodes.java new file mode 100644 index 0000000000..8a4ff4aa8a --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/config/ListCostCodes.java @@ -0,0 +1,36 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.strategy.config; + +import org.jclouds.abiquo.domain.config.CostCode; +import org.jclouds.abiquo.strategy.ListRootEntities; +import org.jclouds.abiquo.strategy.config.internal.ListCostCodesImpl; + +import com.google.inject.ImplementedBy; + +/** + * List cost codes + * + * @author Susana Acedo + */ +@ImplementedBy(ListCostCodesImpl.class) +public interface ListCostCodes extends ListRootEntities { + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/config/ListCurrencies.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/config/ListCurrencies.java new file mode 100644 index 0000000000..2b4ce779ab --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/config/ListCurrencies.java @@ -0,0 +1,36 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.strategy.config; + +import org.jclouds.abiquo.domain.config.Currency; +import org.jclouds.abiquo.strategy.ListRootEntities; +import org.jclouds.abiquo.strategy.config.internal.ListCurrenciesImpl; + +import com.google.inject.ImplementedBy; + +/** + * List currencies + * + * @author Susana Acedo + */ +@ImplementedBy(ListCurrenciesImpl.class) +public interface ListCurrencies extends ListRootEntities { + +} diff --git a/demos/tweetstore/gae-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/reference/TwitterConstants.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/config/ListLicenses.java similarity index 56% rename from demos/tweetstore/gae-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/reference/TwitterConstants.java rename to labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/config/ListLicenses.java index dc8b97915f..027e2e788c 100644 --- a/demos/tweetstore/gae-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/reference/TwitterConstants.java +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/config/ListLicenses.java @@ -7,7 +7,7 @@ * "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 + * 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 @@ -16,16 +16,22 @@ * specific language governing permissions and limitations * under the License. */ -package org.jclouds.demo.tweetstore.reference; + +package org.jclouds.abiquo.strategy.config; + +import org.jclouds.abiquo.domain.config.License; +import org.jclouds.abiquo.domain.config.options.LicenseOptions; +import org.jclouds.abiquo.strategy.ListRootEntities; +import org.jclouds.abiquo.strategy.config.internal.ListLicensesImpl; + +import com.google.inject.ImplementedBy; /** - * Configuration properties and constants used in Twitter connections. + * List licenses. * - * @author Andrew Phillips + * @author Ignasi Barrera */ -public interface TwitterConstants { - static final String PROPERTY_TWITTER_CONSUMER_KEY = "twitter.consumer.identity"; - static final String PROPERTY_TWITTER_CONSUMER_SECRET = "twitter.consumer.credential"; - static final String PROPERTY_TWITTER_ACCESSTOKEN = "twitter.access.identity"; - static final String PROPERTY_TWITTER_ACCESSTOKEN_SECRET = "twitter.access.credential"; +@ImplementedBy(ListLicensesImpl.class) +public interface ListLicenses extends ListRootEntities { + public Iterable execute(LicenseOptions options); } diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/config/ListPricingTemplates.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/config/ListPricingTemplates.java new file mode 100644 index 0000000000..87c0eb4f36 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/config/ListPricingTemplates.java @@ -0,0 +1,36 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.strategy.config; + +import org.jclouds.abiquo.domain.config.PricingTemplate; +import org.jclouds.abiquo.strategy.ListRootEntities; +import org.jclouds.abiquo.strategy.config.internal.ListPricingTemplatesImpl; + +import com.google.inject.ImplementedBy; + +/** + * List pricing templates + * + * @author Susana Acedo + */ +@ImplementedBy(ListPricingTemplatesImpl.class) +public interface ListPricingTemplates extends ListRootEntities { + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/config/ListPrivileges.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/config/ListPrivileges.java new file mode 100644 index 0000000000..874d860c98 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/config/ListPrivileges.java @@ -0,0 +1,35 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.strategy.config; + +import org.jclouds.abiquo.domain.config.Privilege; +import org.jclouds.abiquo.strategy.ListRootEntities; +import org.jclouds.abiquo.strategy.config.internal.ListPrivilegesImpl; + +import com.google.inject.ImplementedBy; + +/** + * List privileges. + * + * @author Ignasi Barrera + */ +@ImplementedBy(ListPrivilegesImpl.class) +public interface ListPrivileges extends ListRootEntities { +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/config/ListProperties.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/config/ListProperties.java new file mode 100644 index 0000000000..fa54a9deb9 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/config/ListProperties.java @@ -0,0 +1,37 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.strategy.config; + +import org.jclouds.abiquo.domain.config.SystemProperty; +import org.jclouds.abiquo.domain.config.options.PropertyOptions; +import org.jclouds.abiquo.strategy.ListRootEntities; +import org.jclouds.abiquo.strategy.config.internal.ListPropertiesImpl; + +import com.google.inject.ImplementedBy; + +/** + * List system properties. + * + * @author Francesc Montserrat + */ +@ImplementedBy(ListPropertiesImpl.class) +public interface ListProperties extends ListRootEntities { + public Iterable execute(PropertyOptions options); +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/config/internal/ListCategoriesImpl.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/config/internal/ListCategoriesImpl.java new file mode 100644 index 0000000000..8fc5ed3bed --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/config/internal/ListCategoriesImpl.java @@ -0,0 +1,67 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.strategy.config.internal; + +import static com.google.common.collect.Iterables.filter; +import static org.jclouds.abiquo.domain.DomainWrapper.wrap; + +import javax.inject.Singleton; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.domain.config.Category; +import org.jclouds.abiquo.strategy.config.ListCategories; +import org.jclouds.rest.RestContext; + +import com.abiquo.server.core.appslibrary.CategoriesDto; +import com.google.common.base.Predicate; +import com.google.inject.Inject; + +/** + * List categories. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +@Singleton +public class ListCategoriesImpl implements ListCategories { + // This strategy does not have still an Executor instance because the current + // methods call + // single api methods + + protected final RestContext context; + + @Inject + ListCategoriesImpl(final RestContext context) { + this.context = context; + } + + @Override + public Iterable execute() { + CategoriesDto result = context.getApi().getConfigApi().listCategories(); + return wrap(context, Category.class, result.getCollection()); + } + + @Override + public Iterable execute(final Predicate selector) { + return filter(execute(), selector); + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/config/internal/ListCostCodesImpl.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/config/internal/ListCostCodesImpl.java new file mode 100644 index 0000000000..2187ce1838 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/config/internal/ListCostCodesImpl.java @@ -0,0 +1,67 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.strategy.config.internal; + +import static com.google.common.collect.Iterables.filter; +import static org.jclouds.abiquo.domain.DomainWrapper.wrap; + +import javax.inject.Singleton; + +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.domain.config.CostCode; +import org.jclouds.abiquo.strategy.config.ListCostCodes; +import org.jclouds.rest.RestContext; + +import com.abiquo.server.core.pricing.CostCodesDto; +import com.google.common.base.Predicate; +import com.google.inject.Inject; + +/** + * List cost codes + * + * @author Ignasi Barrera + * @author Susana Acedo + */ +@Singleton +public class ListCostCodesImpl implements ListCostCodes { + // This strategy does not have still an Executor instance because the current + // methods call + // single api methods + + protected final RestContext context; + + @Inject + ListCostCodesImpl(final RestContext context) { + this.context = context; + } + + @Override + public Iterable execute() { + CostCodesDto result = context.getApi().getPricingApi().listCostCodes(); + return wrap(context, CostCode.class, result.getCollection()); + } + + @Override + public Iterable execute(final Predicate selector) { + return filter(execute(), selector); + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/config/internal/ListCurrenciesImpl.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/config/internal/ListCurrenciesImpl.java new file mode 100644 index 0000000000..9ac1380f57 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/config/internal/ListCurrenciesImpl.java @@ -0,0 +1,67 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.strategy.config.internal; + +import static com.google.common.collect.Iterables.filter; +import static org.jclouds.abiquo.domain.DomainWrapper.wrap; + +import javax.inject.Singleton; + +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.domain.config.Currency; +import org.jclouds.abiquo.strategy.config.ListCurrencies; +import org.jclouds.rest.RestContext; + +import com.abiquo.server.core.pricing.CurrenciesDto; +import com.google.common.base.Predicate; +import com.google.inject.Inject; + +/** + * List currencies + * + * @author Ignasi Barrera + * @author Susana Acedo + */ +@Singleton +public class ListCurrenciesImpl implements ListCurrencies { + // This strategy does not have still an Executor instance because the current + // methods call + // single api methods + + protected final RestContext context; + + @Inject + ListCurrenciesImpl(final RestContext context) { + this.context = context; + } + + @Override + public Iterable execute() { + CurrenciesDto result = context.getApi().getPricingApi().listCurrencies(); + return wrap(context, Currency.class, result.getCollection()); + } + + @Override + public Iterable execute(final Predicate selector) { + return filter(execute(), selector); + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/config/internal/ListLicensesImpl.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/config/internal/ListLicensesImpl.java new file mode 100644 index 0000000000..ab28472b06 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/config/internal/ListLicensesImpl.java @@ -0,0 +1,74 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.strategy.config.internal; + +import static com.google.common.collect.Iterables.filter; +import static org.jclouds.abiquo.domain.DomainWrapper.wrap; + +import javax.inject.Singleton; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.domain.config.License; +import org.jclouds.abiquo.domain.config.options.LicenseOptions; +import org.jclouds.abiquo.strategy.config.ListLicenses; +import org.jclouds.rest.RestContext; + +import com.abiquo.server.core.config.LicensesDto; +import com.google.common.base.Predicate; +import com.google.inject.Inject; + +/** + * List licenses. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +@Singleton +public class ListLicensesImpl implements ListLicenses { + // This strategy does not have still an Executor instance because the current + // methods call + // single api methods + + protected final RestContext context; + + @Inject + ListLicensesImpl(final RestContext context) { + this.context = context; + } + + @Override + public Iterable execute() { + LicensesDto result = context.getApi().getConfigApi().listLicenses(); + return wrap(context, License.class, result.getCollection()); + } + + @Override + public Iterable execute(final LicenseOptions options) { + LicensesDto result = context.getApi().getConfigApi().listLicenses(options); + return wrap(context, License.class, result.getCollection()); + } + + @Override + public Iterable execute(final Predicate selector) { + return filter(execute(), selector); + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/config/internal/ListPricingTemplatesImpl.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/config/internal/ListPricingTemplatesImpl.java new file mode 100644 index 0000000000..8d9ac4045e --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/config/internal/ListPricingTemplatesImpl.java @@ -0,0 +1,67 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.strategy.config.internal; + +import static com.google.common.collect.Iterables.filter; +import static org.jclouds.abiquo.domain.DomainWrapper.wrap; + +import javax.inject.Singleton; + +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.domain.config.PricingTemplate; +import org.jclouds.abiquo.strategy.config.ListPricingTemplates; +import org.jclouds.rest.RestContext; + +import com.abiquo.server.core.pricing.PricingTemplatesDto; +import com.google.common.base.Predicate; +import com.google.inject.Inject; + +/** + * List pricing templates + * + * @author Ignasi Barrera + * @author Susana Acedo + */ +@Singleton +public class ListPricingTemplatesImpl implements ListPricingTemplates { + // This strategy does not have still an Executor instance because the current + // methods call + // single api methods + + protected final RestContext context; + + @Inject + ListPricingTemplatesImpl(final RestContext context) { + this.context = context; + } + + @Override + public Iterable execute() { + PricingTemplatesDto result = context.getApi().getPricingApi().listPricingTemplates(); + return wrap(context, PricingTemplate.class, result.getCollection()); + } + + @Override + public Iterable execute(final Predicate selector) { + return filter(execute(), selector); + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/config/internal/ListPrivilegesImpl.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/config/internal/ListPrivilegesImpl.java new file mode 100644 index 0000000000..6a16511abf --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/config/internal/ListPrivilegesImpl.java @@ -0,0 +1,67 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.strategy.config.internal; + +import static com.google.common.collect.Iterables.filter; +import static org.jclouds.abiquo.domain.DomainWrapper.wrap; + +import javax.inject.Singleton; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.domain.config.Privilege; +import org.jclouds.abiquo.strategy.config.ListPrivileges; +import org.jclouds.rest.RestContext; + +import com.abiquo.server.core.enterprise.PrivilegesDto; +import com.google.common.base.Predicate; +import com.google.inject.Inject; + +/** + * List licenses. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +@Singleton +public class ListPrivilegesImpl implements ListPrivileges { + // This strategy does not have still an Executor instance because the current + // methods call + // single api methods + + protected final RestContext context; + + @Inject + ListPrivilegesImpl(final RestContext context) { + this.context = context; + } + + @Override + public Iterable execute() { + PrivilegesDto result = context.getApi().getConfigApi().listPrivileges(); + return wrap(context, Privilege.class, result.getCollection()); + } + + @Override + public Iterable execute(final Predicate selector) { + return filter(execute(), selector); + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/config/internal/ListPropertiesImpl.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/config/internal/ListPropertiesImpl.java new file mode 100644 index 0000000000..07eaab416b --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/config/internal/ListPropertiesImpl.java @@ -0,0 +1,73 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.strategy.config.internal; + +import static com.google.common.collect.Iterables.filter; +import static org.jclouds.abiquo.domain.DomainWrapper.wrap; + +import javax.inject.Singleton; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.domain.config.SystemProperty; +import org.jclouds.abiquo.domain.config.options.PropertyOptions; +import org.jclouds.abiquo.strategy.config.ListProperties; +import org.jclouds.rest.RestContext; + +import com.abiquo.server.core.config.SystemPropertiesDto; +import com.google.common.base.Predicate; +import com.google.inject.Inject; + +/** + * List properties. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +@Singleton +public class ListPropertiesImpl implements ListProperties { + // This strategy does not have still an Executor instance because the current + // methods call + // single api methods + + protected final RestContext context; + + @Inject + ListPropertiesImpl(final RestContext context) { + this.context = context; + } + + @Override + public Iterable execute() { + SystemPropertiesDto result = context.getApi().getConfigApi().listSystemProperties(); + return wrap(context, SystemProperty.class, result.getCollection()); + } + + @Override + public Iterable execute(final Predicate selector) { + return filter(execute(), selector); + } + + @Override + public Iterable execute(final PropertyOptions options) { + SystemPropertiesDto result = context.getApi().getConfigApi().listSystemProperties(options); + return wrap(context, SystemProperty.class, result.getCollection()); + } +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/enterprise/ListEnterprises.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/enterprise/ListEnterprises.java new file mode 100644 index 0000000000..1e0ba94eb6 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/enterprise/ListEnterprises.java @@ -0,0 +1,36 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.strategy.enterprise; + +import org.jclouds.abiquo.domain.enterprise.Enterprise; +import org.jclouds.abiquo.strategy.ListRootEntities; +import org.jclouds.abiquo.strategy.enterprise.internal.ListEnterprisesImpl; + +import com.google.inject.ImplementedBy; + +/** + * List enterprises. + * + * @author Ignasi Barrera + */ +@ImplementedBy(ListEnterprisesImpl.class) +public interface ListEnterprises extends ListRootEntities { + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/enterprise/ListVirtualMachineTemplates.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/enterprise/ListVirtualMachineTemplates.java new file mode 100644 index 0000000000..29136bf778 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/enterprise/ListVirtualMachineTemplates.java @@ -0,0 +1,37 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.strategy.enterprise; + +import org.jclouds.abiquo.domain.cloud.VirtualMachineTemplate; +import org.jclouds.abiquo.domain.enterprise.Enterprise; +import org.jclouds.abiquo.strategy.ListEntities; +import org.jclouds.abiquo.strategy.enterprise.internal.ListVirtualMachineTemplatesImpl; + +import com.google.inject.ImplementedBy; + +/** + * List all virtual machine templates available to an enterprise. + * + * @author Ignasi Barrera + */ +@ImplementedBy(ListVirtualMachineTemplatesImpl.class) +public interface ListVirtualMachineTemplates extends ListEntities { + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/enterprise/internal/ListEnterprisesImpl.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/enterprise/internal/ListEnterprisesImpl.java new file mode 100644 index 0000000000..ee401b4e0e --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/enterprise/internal/ListEnterprisesImpl.java @@ -0,0 +1,67 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.strategy.enterprise.internal; + +import static com.google.common.collect.Iterables.filter; +import static org.jclouds.abiquo.domain.DomainWrapper.wrap; + +import javax.inject.Singleton; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.domain.enterprise.Enterprise; +import org.jclouds.abiquo.strategy.enterprise.ListEnterprises; +import org.jclouds.rest.RestContext; + +import com.abiquo.server.core.enterprise.EnterprisesDto; +import com.google.common.base.Predicate; +import com.google.inject.Inject; + +/** + * List enterprises. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +@Singleton +public class ListEnterprisesImpl implements ListEnterprises { + // This strategy does not have still an Executor instance because the current + // methods call + // single api methods + + protected final RestContext context; + + @Inject + ListEnterprisesImpl(final RestContext context) { + this.context = context; + } + + @Override + public Iterable execute() { + EnterprisesDto result = context.getApi().getEnterpriseApi().listEnterprises(); + return wrap(context, Enterprise.class, result.getCollection()); + } + + @Override + public Iterable execute(final Predicate selector) { + return filter(execute(), selector); + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/enterprise/internal/ListVirtualMachineTemplatesImpl.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/enterprise/internal/ListVirtualMachineTemplatesImpl.java new file mode 100644 index 0000000000..29209ad5c5 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/enterprise/internal/ListVirtualMachineTemplatesImpl.java @@ -0,0 +1,106 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.strategy.enterprise.internal; + +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.collect.Iterables.filter; +import static org.jclouds.abiquo.domain.DomainWrapper.wrap; +import static org.jclouds.concurrent.FutureIterables.transformParallel; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; + +import javax.annotation.Resource; +import javax.inject.Named; +import javax.inject.Singleton; + +import org.jclouds.Constants; +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.domain.DomainWrapper; +import org.jclouds.abiquo.domain.cloud.VirtualMachineTemplate; +import org.jclouds.abiquo.domain.enterprise.Enterprise; +import org.jclouds.abiquo.domain.infrastructure.Datacenter; +import org.jclouds.abiquo.strategy.enterprise.ListVirtualMachineTemplates; +import org.jclouds.logging.Logger; +import org.jclouds.rest.RestContext; + +import com.abiquo.server.core.appslibrary.VirtualMachineTemplateDto; +import com.abiquo.server.core.appslibrary.VirtualMachineTemplatesDto; +import com.google.common.base.Function; +import com.google.common.base.Predicate; +import com.google.inject.Inject; + +/** + * List all virtual machine templates available to an enterprise. + * + * @author Ignasi Barrera + */ +@Singleton +public class ListVirtualMachineTemplatesImpl implements ListVirtualMachineTemplates { + protected final RestContext context; + + protected final ExecutorService userExecutor; + + @Resource + protected Logger logger = Logger.NULL; + + @Inject(optional = true) + @Named(Constants.PROPERTY_REQUEST_TIMEOUT) + protected Long maxTime; + + @Inject + ListVirtualMachineTemplatesImpl(final RestContext context, + @Named(Constants.PROPERTY_USER_THREADS) final ExecutorService userExecutor) { + super(); + this.context = checkNotNull(context, "context"); + this.userExecutor = checkNotNull(userExecutor, "userExecutor"); + } + + @Override + public Iterable execute(final Enterprise parent) { + // Find virtual machine templates in concurrent requests + Iterable dcs = parent.listAllowedDatacenters(); + Iterable templates = listConcurrentTemplates(parent, dcs); + + return wrap(context, VirtualMachineTemplate.class, templates); + } + + @Override + public Iterable execute(final Enterprise parent, + final Predicate selector) { + return filter(execute(parent), selector); + } + + private Iterable listConcurrentTemplates(final Enterprise parent, + final Iterable dcs) { + Iterable templates = transformParallel(dcs, + new Function>() { + @Override + public Future apply(final Datacenter input) { + return context.getAsyncApi().getVirtualMachineTemplateApi() + .listVirtualMachineTemplates(parent.getId(), input.getId()); + } + }, userExecutor, maxTime, logger, "getting virtual machine templates"); + + return DomainWrapper.join(templates); + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/event/ListEvents.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/event/ListEvents.java new file mode 100644 index 0000000000..083991599d --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/event/ListEvents.java @@ -0,0 +1,37 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.strategy.event; + +import org.jclouds.abiquo.domain.event.Event; +import org.jclouds.abiquo.domain.event.options.EventOptions; +import org.jclouds.abiquo.strategy.ListRootEntities; +import org.jclouds.abiquo.strategy.event.internal.ListEventsImpl; + +import com.google.inject.ImplementedBy; + +/** + * List events. + * + * @author Vivien Mahé + */ +@ImplementedBy(ListEventsImpl.class) +public interface ListEvents extends ListRootEntities { + Iterable execute(EventOptions options); +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/event/internal/ListEventsImpl.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/event/internal/ListEventsImpl.java new file mode 100644 index 0000000000..ed1da35236 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/event/internal/ListEventsImpl.java @@ -0,0 +1,65 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.strategy.event.internal; + +import static com.google.common.collect.Iterables.filter; +import static org.jclouds.abiquo.domain.DomainWrapper.wrap; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.domain.event.Event; +import org.jclouds.abiquo.domain.event.options.EventOptions; +import org.jclouds.abiquo.strategy.event.ListEvents; +import org.jclouds.rest.RestContext; + +import com.abiquo.server.core.event.EventsDto; +import com.google.common.base.Predicate; +import com.google.inject.Inject; + +public class ListEventsImpl implements ListEvents { + // This strategy does not have still an Executor instance because the current + // methods call + // single api methods + + protected final RestContext context; + + @Inject + ListEventsImpl(final RestContext context) { + this.context = context; + } + + @Override + public Iterable execute() { + EventsDto result = context.getApi().getEventApi().listEvents(); + return wrap(context, Event.class, result.getCollection()); + } + + @Override + public Iterable execute(final EventOptions options) { + EventsDto result = context.getApi().getEventApi().listEvents(options); + return wrap(context, Event.class, result.getCollection()); + } + + @Override + public Iterable execute(final Predicate selector) { + return filter(execute(), selector); + } + +} diff --git a/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/reference/TwitterConstants.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/infrastructure/ListDatacenters.java similarity index 56% rename from demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/reference/TwitterConstants.java rename to labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/infrastructure/ListDatacenters.java index dc8b97915f..99a67bfaaa 100644 --- a/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/tweetstore/reference/TwitterConstants.java +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/infrastructure/ListDatacenters.java @@ -7,7 +7,7 @@ * "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 + * 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 @@ -16,16 +16,23 @@ * specific language governing permissions and limitations * under the License. */ -package org.jclouds.demo.tweetstore.reference; + +package org.jclouds.abiquo.strategy.infrastructure; + +import java.util.List; + +import org.jclouds.abiquo.domain.infrastructure.Datacenter; +import org.jclouds.abiquo.strategy.ListRootEntities; +import org.jclouds.abiquo.strategy.infrastructure.internal.ListDatacentersImpl; + +import com.google.inject.ImplementedBy; /** - * Configuration properties and constants used in Twitter connections. + * List datacenters. * - * @author Andrew Phillips + * @author Ignasi Barrera */ -public interface TwitterConstants { - static final String PROPERTY_TWITTER_CONSUMER_KEY = "twitter.consumer.identity"; - static final String PROPERTY_TWITTER_CONSUMER_SECRET = "twitter.consumer.credential"; - static final String PROPERTY_TWITTER_ACCESSTOKEN = "twitter.access.identity"; - static final String PROPERTY_TWITTER_ACCESSTOKEN_SECRET = "twitter.access.credential"; +@ImplementedBy(ListDatacentersImpl.class) +public interface ListDatacenters extends ListRootEntities { + Iterable execute(List datacenterIds); } diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/infrastructure/ListMachines.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/infrastructure/ListMachines.java new file mode 100644 index 0000000000..d14d3c613e --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/infrastructure/ListMachines.java @@ -0,0 +1,36 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.strategy.infrastructure; + +import org.jclouds.abiquo.domain.infrastructure.Machine; +import org.jclouds.abiquo.strategy.ListRootEntities; +import org.jclouds.abiquo.strategy.infrastructure.internal.ListMachinesImpl; + +import com.google.inject.ImplementedBy; + +/** + * List machines in each datacenter and rack. + * + * @author Ignasi Barrera + */ +@ImplementedBy(ListMachinesImpl.class) +public interface ListMachines extends ListRootEntities { + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/infrastructure/internal/ListDatacentersImpl.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/infrastructure/internal/ListDatacentersImpl.java new file mode 100644 index 0000000000..fad587620f --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/infrastructure/internal/ListDatacentersImpl.java @@ -0,0 +1,106 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.strategy.infrastructure.internal; + +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.collect.Iterables.filter; +import static org.jclouds.abiquo.domain.DomainWrapper.wrap; +import static org.jclouds.concurrent.FutureIterables.transformParallel; + +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; + +import javax.annotation.Resource; +import javax.inject.Named; +import javax.inject.Singleton; + +import org.jclouds.Constants; +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.domain.DomainWrapper; +import org.jclouds.abiquo.domain.infrastructure.Datacenter; +import org.jclouds.abiquo.strategy.infrastructure.ListDatacenters; +import org.jclouds.logging.Logger; +import org.jclouds.rest.RestContext; + +import com.abiquo.server.core.infrastructure.DatacenterDto; +import com.abiquo.server.core.infrastructure.DatacentersDto; +import com.google.common.base.Function; +import com.google.common.base.Predicate; +import com.google.common.collect.Lists; +import com.google.inject.Inject; + +/** + * List datacenters. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +@Singleton +public class ListDatacentersImpl implements ListDatacenters { + + protected final RestContext context; + + protected final ExecutorService userExecutor; + + @Resource + protected Logger logger = Logger.NULL; + + @Inject(optional = true) + @Named(Constants.PROPERTY_REQUEST_TIMEOUT) + protected Long maxTime; + + @Inject + ListDatacentersImpl(final RestContext context, + @Named(Constants.PROPERTY_USER_THREADS) final ExecutorService userExecutor) { + this.context = context; + this.userExecutor = checkNotNull(userExecutor, "userExecutor"); + } + + @Override + public Iterable execute() { + DatacentersDto result = context.getApi().getInfrastructureApi().listDatacenters(); + return wrap(context, Datacenter.class, result.getCollection()); + } + + @Override + public Iterable execute(final Predicate selector) { + return filter(execute(), selector); + } + + @Override + public Iterable execute(final List datacenterIds) { + // Find virtual datacenters in concurrent requests + return listConcurrentDatacenters(datacenterIds); + } + + private Iterable listConcurrentDatacenters(final List ids) { + Iterable dcs = transformParallel(ids, new Function>() { + @Override + public Future apply(final Integer input) { + return context.getAsyncApi().getInfrastructureApi().getDatacenter(input); + } + }, userExecutor, maxTime, logger, "getting datacenters"); + + return DomainWrapper.wrap(context, Datacenter.class, Lists.newArrayList(dcs)); + } + +} diff --git a/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/infrastructure/internal/ListMachinesImpl.java b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/infrastructure/internal/ListMachinesImpl.java new file mode 100644 index 0000000000..326d5febb4 --- /dev/null +++ b/labs/abiquo/src/main/java/org/jclouds/abiquo/strategy/infrastructure/internal/ListMachinesImpl.java @@ -0,0 +1,120 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.strategy.infrastructure.internal; + +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.collect.Iterables.filter; +import static org.jclouds.abiquo.domain.DomainWrapper.wrap; +import static org.jclouds.concurrent.FutureIterables.transformParallel; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; + +import javax.annotation.Resource; +import javax.inject.Named; +import javax.inject.Singleton; + +import org.jclouds.Constants; +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.domain.DomainWrapper; +import org.jclouds.abiquo.domain.infrastructure.Datacenter; +import org.jclouds.abiquo.domain.infrastructure.Machine; +import org.jclouds.abiquo.strategy.infrastructure.ListDatacenters; +import org.jclouds.abiquo.strategy.infrastructure.ListMachines; +import org.jclouds.logging.Logger; +import org.jclouds.rest.RestContext; + +import com.abiquo.server.core.infrastructure.MachineDto; +import com.abiquo.server.core.infrastructure.MachinesDto; +import com.abiquo.server.core.infrastructure.RackDto; +import com.abiquo.server.core.infrastructure.RacksDto; +import com.google.common.base.Function; +import com.google.common.base.Predicate; +import com.google.inject.Inject; + +/** + * List machines in each datacenter and rack. + * + * @author Ignasi Barrera + */ +@Singleton +public class ListMachinesImpl implements ListMachines { + protected RestContext context; + + protected ListDatacenters listDatacenters; + + protected final ExecutorService userExecutor; + + @Resource + protected Logger logger = Logger.NULL; + + @Inject(optional = true) + @Named(Constants.PROPERTY_REQUEST_TIMEOUT) + protected Long maxTime; + + @Inject + ListMachinesImpl(final RestContext context, + @Named(Constants.PROPERTY_USER_THREADS) final ExecutorService userExecutor, + final ListDatacenters listDatacenters) { + super(); + this.context = checkNotNull(context, "context"); + this.listDatacenters = checkNotNull(listDatacenters, "listDatacenters"); + this.userExecutor = checkNotNull(userExecutor, "userExecutor"); + } + + @Override + public Iterable execute() { + // Find machines in concurrent requests + Iterable datacenters = listDatacenters.execute(); + Iterable racks = listConcurrentRacks(datacenters); + Iterable machines = listConcurrentMachines(racks); + + return wrap(context, Machine.class, machines); + } + + @Override + public Iterable execute(final Predicate selector) { + return filter(execute(), selector); + } + + private Iterable listConcurrentRacks(final Iterable datacenters) { + Iterable racks = transformParallel(datacenters, new Function>() { + @Override + public Future apply(final Datacenter input) { + return context.getAsyncApi().getInfrastructureApi().listRacks(input.unwrap()); + } + }, userExecutor, maxTime, logger, "getting racks"); + + return DomainWrapper.join(racks); + } + + private Iterable listConcurrentMachines(final Iterable racks) { + Iterable machines = transformParallel(racks, new Function>() { + @Override + public Future apply(final RackDto input) { + return context.getAsyncApi().getInfrastructureApi().listMachines(input); + } + }, userExecutor, maxTime, logger, "getting machines"); + + return DomainWrapper.join(machines); + } + +} diff --git a/labs/abiquo/src/main/resources/META-INF/services/org.jclouds.apis.ApiMetadata b/labs/abiquo/src/main/resources/META-INF/services/org.jclouds.apis.ApiMetadata new file mode 100644 index 0000000000..642f443f14 --- /dev/null +++ b/labs/abiquo/src/main/resources/META-INF/services/org.jclouds.apis.ApiMetadata @@ -0,0 +1 @@ +org.jclouds.abiquo.AbiquoApiMetadata \ No newline at end of file diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/AbiquoApiMetadataTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/AbiquoApiMetadataTest.java new file mode 100644 index 0000000000..018575b9c4 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/AbiquoApiMetadataTest.java @@ -0,0 +1,51 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertTrue; + +import org.jclouds.apis.ApiMetadata; +import org.jclouds.apis.Apis; +import org.jclouds.compute.internal.BaseComputeServiceApiMetadataTest; +import org.testng.annotations.Test; + +/** + * Unit tests for the {@link AbiquoApiMetadata} class. + * + * @author Ignasi Barrera + */ +@Test(groups = "unit", testName = "AbiquoApiMetadataTest") +public class AbiquoApiMetadataTest extends BaseComputeServiceApiMetadataTest { + + public AbiquoApiMetadataTest() { + super(new AbiquoApiMetadata()); + } + + public void testAbiquoApiRegistered() { + ApiMetadata api = Apis.withId("abiquo"); + + assertNotNull(api); + assertTrue(api instanceof AbiquoApiMetadata); + assertEquals(api.getId(), "abiquo"); + } + +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/AbiquoDelegateApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/AbiquoDelegateApiTest.java new file mode 100644 index 0000000000..50098a1773 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/AbiquoDelegateApiTest.java @@ -0,0 +1,86 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo; + +import static org.testng.Assert.assertNotNull; + +import java.io.IOException; +import java.util.concurrent.ExecutionException; + +import org.jclouds.abiquo.features.BaseAbiquoAsyncApiTest; +import org.jclouds.http.HttpRequest; +import org.jclouds.rest.internal.RestAnnotationProcessor; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import com.google.inject.TypeLiteral; + +/** + * Tests asynchronous and synchronous API delegates. + * + * @author Ignasi Barrera + */ +@Test(groups = "unit", testName = "AbiquoDelegateApiTest") +public class AbiquoDelegateApiTest extends BaseAbiquoAsyncApiTest { + private AbiquoAsyncApi asyncApi; + + private AbiquoApi syncApi; + + @BeforeClass + @Override + protected void setupFactory() throws IOException { + super.setupFactory(); + asyncApi = injector.getInstance(AbiquoAsyncApi.class); + syncApi = injector.getInstance(AbiquoApi.class); + } + + public void testSync() throws SecurityException, NoSuchMethodException, InterruptedException, ExecutionException { + assertNotNull(syncApi.getAdminApi()); + assertNotNull(syncApi.getConfigApi()); + assertNotNull(syncApi.getInfrastructureApi()); + assertNotNull(syncApi.getEnterpriseApi()); + assertNotNull(syncApi.getCloudApi()); + assertNotNull(syncApi.getVirtualMachineTemplateApi()); + assertNotNull(syncApi.getTaskApi()); + assertNotNull(syncApi.getPricingApi()); + } + + public void testAsync() throws SecurityException, NoSuchMethodException, InterruptedException, ExecutionException { + assertNotNull(asyncApi.getAdminApi()); + assertNotNull(asyncApi.getConfigApi()); + assertNotNull(asyncApi.getInfrastructureApi()); + assertNotNull(asyncApi.getEnterpriseApi()); + assertNotNull(asyncApi.getCloudApi()); + assertNotNull(asyncApi.getVirtualMachineTemplateApi()); + assertNotNull(asyncApi.getTaskApi()); + assertNotNull(asyncApi.getPricingApi()); + } + + @Override + protected TypeLiteral> createTypeLiteral() { + return new TypeLiteral>() { + }; + } + + @Override + protected void checkFilters(final HttpRequest request) { + + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/AppendToPathTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/AppendToPathTest.java new file mode 100644 index 0000000000..19ec5e2a10 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/AppendToPathTest.java @@ -0,0 +1,56 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.binders; + +import static org.testng.Assert.assertEquals; + +import java.net.URI; + +import org.jclouds.http.HttpRequest; +import org.testng.annotations.Test; + +/** + * Unit tests for the {@link AppendToPath} binder. + * + * @author Ignasi Barrera + */ +@Test(groups = "unit", testName = "AppendToPathTest") +public class AppendToPathTest { + @Test(expectedExceptions = NullPointerException.class) + public void testInvalidNullInput() { + AppendToPath binder = new AppendToPath(); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://localhost")).build(); + binder.bindToRequest(request, null); + } + + public void testBindString() { + AppendToPath binder = new AppendToPath(); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://localhost")).build(); + HttpRequest newRequest = binder.bindToRequest(request, "expanded/path"); + assertEquals(newRequest.getRequestLine(), "GET http://localhost/expanded/path HTTP/1.1"); + } + + public void testBindNumber() { + AppendToPath binder = new AppendToPath(); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://localhost")).build(); + HttpRequest newRequest = binder.bindToRequest(request, 57); + assertEquals(newRequest.getRequestLine(), "GET http://localhost/57 HTTP/1.1"); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/BindLinkToPathAndAcceptHeaderTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/BindLinkToPathAndAcceptHeaderTest.java new file mode 100644 index 0000000000..426ff9a0af --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/BindLinkToPathAndAcceptHeaderTest.java @@ -0,0 +1,57 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.binders; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; + +import java.net.URI; + +import javax.ws.rs.core.HttpHeaders; + +import org.jclouds.http.HttpRequest; +import org.testng.annotations.Test; + +/** + * Unit tests for the {@link BindLinkToPathAndAcceptHeader} class. + * + * @author Ignasi Barrera + */ +@Test(groups = "unit", testName = "BindLinkToPathAndAcceptHeaderTest") +public class BindLinkToPathAndAcceptHeaderTest { + @Test(expectedExceptions = NullPointerException.class) + public void testInvalidNullInput() { + BindLinkToPathAndAcceptHeader binder = new BindLinkToPathAndAcceptHeader(); + binder.addHeader(null, HttpHeaders.ACCEPT, null); + } + + public void testAddHeader() { + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://localhost")).build(); + + BindLinkToPathAndAcceptHeader binder = new BindLinkToPathAndAcceptHeader(); + HttpRequest updatedRequest = binder.addHeader(request, HttpHeaders.ACCEPT, + "application/vnd.abiquo.datacenters+xml"); + + String accept = updatedRequest.getFirstHeaderOrNull(HttpHeaders.ACCEPT); + + assertNotNull(accept); + assertEquals(accept, "application/vnd.abiquo.datacenters+xml"); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/BindLinkToPathTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/BindLinkToPathTest.java new file mode 100644 index 0000000000..b266696625 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/BindLinkToPathTest.java @@ -0,0 +1,51 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.binders; + +import static org.testng.Assert.assertEquals; + +import org.testng.annotations.Test; + +import com.abiquo.model.rest.RESTLink; + +/** + * Unit tests for the {@link BindLinkToPath} class. + * + * @author Ignasi Barrera + */ +@Test(groups = "unit", testName = "BindLinkToPathTest") +public class BindLinkToPathTest { + @Test(expectedExceptions = NullPointerException.class) + public void testGetNewEnpointNullInput() { + BindLinkToPath binder = new BindLinkToPath(); + binder.getNewEndpoint(null, null); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testGetNewEnpointInvalidInput() { + BindLinkToPath binder = new BindLinkToPath(); + binder.getNewEndpoint(null, new Object()); + } + + public void testGetNewEnpoint() { + BindLinkToPath binder = new BindLinkToPath(); + assertEquals(binder.getNewEndpoint(null, new RESTLink("edit", "http://foo/bar")), "http://foo/bar"); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/BindToPathTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/BindToPathTest.java new file mode 100644 index 0000000000..e1e5ba36ac --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/BindToPathTest.java @@ -0,0 +1,170 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.binders; + +import static org.testng.Assert.assertEquals; + +import java.lang.reflect.Method; +import java.net.URI; + +import javax.ws.rs.GET; +import javax.ws.rs.HttpMethod; +import javax.ws.rs.core.MediaType; + +import org.jclouds.abiquo.rest.annotations.EndpointLink; +import org.jclouds.http.HttpRequest; +import org.jclouds.rest.binders.BindException; +import org.jclouds.rest.internal.GeneratedHttpRequest; +import org.testng.annotations.Test; + +import com.abiquo.model.rest.RESTLink; +import com.abiquo.model.transport.SingleResourceTransportDto; +import com.google.common.collect.ImmutableList; + +/** + * Unit tests for the {@link BindToPath} binder. + * + * @author Ignasi Barrera + */ +@Test(groups = "unit", testName = "BindToPathTest") +public class BindToPathTest { + @Test(expectedExceptions = NullPointerException.class) + public void testInvalidNullRequest() throws SecurityException, NoSuchMethodException { + BindToPath binder = new BindToPath(); + binder.bindToRequest(null, new Object()); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testInvalidRequestType() throws SecurityException, NoSuchMethodException { + BindToPath binder = new BindToPath(); + binder.bindToRequest(HttpRequest.builder().method("m").endpoint("http://localhost").build(), new Object()); + } + + @Test(expectedExceptions = NullPointerException.class) + public void testInvalidNullInput() throws SecurityException, NoSuchMethodException { + Method withEndpointLink = TestEndpointLink.class.getMethod("withEndpointLink", TestDto.class); + GeneratedHttpRequest request = GeneratedHttpRequest.builder().declaring(TestEndpointLink.class) + .javaMethod(withEndpointLink).args(ImmutableList. of(new TestDto())).method(HttpMethod.GET) + .endpoint(URI.create("http://localhost")).build(); + + BindToPath binder = new BindToPath(); + binder.bindToRequest(request, null); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testInvalidInputType() throws SecurityException, NoSuchMethodException { + Method withEndpointLink = TestEndpointLink.class.getMethod("withEndpointLink", TestDto.class); + GeneratedHttpRequest request = GeneratedHttpRequest.builder().declaring(TestEndpointLink.class) + .javaMethod(withEndpointLink).args(ImmutableList. of(new TestDto())).method(HttpMethod.GET) + .endpoint(URI.create("http://localhost")).build(); + + BindToPath binder = new BindToPath(); + binder.bindToRequest(request, new Object()); + } + + @Test(expectedExceptions = BindException.class) + public void testAnnotationNotPresent() throws SecurityException, NoSuchMethodException { + TestDto dto = new TestDto(); + Method withoutEndpointLink = TestEndpointLink.class.getMethod("withoutEndpointLink", TestDto.class); + GeneratedHttpRequest request = GeneratedHttpRequest.builder().declaring(TestEndpointLink.class) + .javaMethod(withoutEndpointLink).args(ImmutableList. of(dto)).method(HttpMethod.GET) + .endpoint(URI.create("http://localhost")).build(); + + BindToPath binder = new BindToPath(); + binder.bindToRequest(request, dto); + } + + @Test(expectedExceptions = NullPointerException.class) + public void testLinkNotPresent() throws SecurityException, NoSuchMethodException { + TestDto dto = new TestDto(); + Method withUnexistingLink = TestEndpointLink.class.getMethod("withUnexistingLink", TestDto.class); + GeneratedHttpRequest request = GeneratedHttpRequest.builder().declaring(TestEndpointLink.class) + .javaMethod(withUnexistingLink).args(ImmutableList. of(dto)).method(HttpMethod.GET) + .endpoint(URI.create("http://localhost")).build(); + + BindToPath binder = new BindToPath(); + binder.bindToRequest(request, dto); + } + + public void testBindWithoutParameters() throws SecurityException, NoSuchMethodException { + TestDto dto = new TestDto(); + Method withEndpointLink = TestEndpointLink.class.getMethod("withEndpointLink", TestDto.class); + GeneratedHttpRequest request = GeneratedHttpRequest.builder().declaring(TestEndpointLink.class) + .javaMethod(withEndpointLink).args(ImmutableList. of(dto)).method(HttpMethod.GET) + .endpoint(URI.create("http://localhost")).build(); + + BindToPath binder = new BindToPath(); + GeneratedHttpRequest newRequest = binder.bindToRequest(request, dto); + assertEquals(newRequest.getRequestLine(), "GET http://linkuri HTTP/1.1"); + } + + public void testBindWithQueryParameters() throws SecurityException, NoSuchMethodException { + TestDto dto = new TestDto(); + Method withEndpointLink = TestEndpointLink.class.getMethod("withEndpointLink", TestDto.class); + GeneratedHttpRequest request = GeneratedHttpRequest.builder().declaring(TestEndpointLink.class) + .javaMethod(withEndpointLink).args(ImmutableList. of(dto)).method(HttpMethod.GET) + .endpoint(URI.create("http://localhost?param=value")).build(); + + BindToPath binder = new BindToPath(); + GeneratedHttpRequest newRequest = binder.bindToRequest(request, dto); + assertEquals(newRequest.getRequestLine(), "GET http://linkuri?param=value HTTP/1.1"); + } + + public void testBindWithQueryAndMatrixParameters() throws SecurityException, NoSuchMethodException { + TestDto dto = new TestDto(); + Method withEndpointLink = TestEndpointLink.class.getMethod("withEndpointLink", TestDto.class); + GeneratedHttpRequest request = GeneratedHttpRequest.builder().declaring(TestEndpointLink.class) + .javaMethod(withEndpointLink).args(ImmutableList. of(dto)).method(HttpMethod.GET) + .endpoint(URI.create("http://localhost?param=value;matrix=value2")).build(); + + BindToPath binder = new BindToPath(); + GeneratedHttpRequest newRequest = binder.bindToRequest(request, dto); + assertEquals(newRequest.getRequestLine(), "GET http://linkuri?param=value;matrix=value2 HTTP/1.1"); + } + + static interface TestEndpointLink { + @GET + void withEndpointLink(@EndpointLink("edit") TestDto dto); + + @GET + void withUnexistingLink(@EndpointLink("unexisting") TestDto dto); + + @GET + void withoutEndpointLink(TestDto dto); + } + + static class TestDto extends SingleResourceTransportDto { + private static final long serialVersionUID = 1L; + + public TestDto() { + addLink(new RESTLink("edit", "http://linkuri")); + } + + @Override + public String getMediaType() { + return MediaType.APPLICATION_XML; + } + + @Override + public String getBaseMediaType() { + return MediaType.APPLICATION_XML; + } + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/cloud/BindHardDiskRefsToPayloadTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/cloud/BindHardDiskRefsToPayloadTest.java new file mode 100644 index 0000000000..220fa363ba --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/cloud/BindHardDiskRefsToPayloadTest.java @@ -0,0 +1,82 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.binders.cloud; + +import static org.jclouds.abiquo.domain.DomainUtils.withHeader; +import static org.jclouds.abiquo.util.Assert.assertPayloadEquals; + +import java.io.IOException; +import java.net.URI; + +import org.jclouds.abiquo.domain.CloudResources; +import org.jclouds.http.HttpRequest; +import org.jclouds.xml.internal.JAXBParser; +import org.testng.annotations.Test; + +import com.abiquo.model.transport.LinksDto; +import com.abiquo.server.core.infrastructure.storage.DiskManagementDto; + +/** + * Unit tests for the {@link BindHardDiskRefsToPayload} binder. + * + * @author Ignasi Barrera + */ +@Test(groups = "unit", testName = "BindHardDiskRefsToPayloadTest") +public class BindHardDiskRefsToPayloadTest { + + @Test(expectedExceptions = NullPointerException.class) + public void testInvalidNullInput() { + BindHardDiskRefsToPayload binder = new BindHardDiskRefsToPayload(new JAXBParser("false")); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://localhost")).build(); + binder.bindToRequest(request, null); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testInvalidTypeInput() { + BindHardDiskRefsToPayload binder = new BindHardDiskRefsToPayload(new JAXBParser("false")); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://localhost")).build(); + binder.bindToRequest(request, new Object()); + } + + public void testBindEmptyArray() throws IOException { + BindHardDiskRefsToPayload binder = new BindHardDiskRefsToPayload(new JAXBParser("false")); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://localhost")).build(); + request = binder.bindToRequest(request, new DiskManagementDto[] {}); + assertPayloadEquals(request.getPayload(), withHeader(""), LinksDto.class); + } + + public void testBindSingleHardDisk() throws IOException { + DiskManagementDto hardDisk = CloudResources.hardDiskPut(); + BindHardDiskRefsToPayload binder = new BindHardDiskRefsToPayload(new JAXBParser("false")); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://localhost")).build(); + request = binder.bindToRequest(request, new DiskManagementDto[] { hardDisk }); + assertPayloadEquals(request.getPayload(), withHeader(""), LinksDto.class); + } + + public void testBindMultipleHardDisks() throws IOException { + DiskManagementDto hardDisk = CloudResources.hardDiskPut(); + BindHardDiskRefsToPayload binder = new BindHardDiskRefsToPayload(new JAXBParser("false")); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://localhost")).build(); + request = binder.bindToRequest(request, new DiskManagementDto[] { hardDisk, hardDisk }); + assertPayloadEquals(request.getPayload(), withHeader(""), LinksDto.class); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/cloud/BindIpRefToPayloadTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/cloud/BindIpRefToPayloadTest.java new file mode 100644 index 0000000000..b8649e106f --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/cloud/BindIpRefToPayloadTest.java @@ -0,0 +1,69 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.binders.cloud; + +import static org.jclouds.abiquo.domain.DomainUtils.withHeader; +import static org.jclouds.abiquo.util.Assert.assertPayloadEquals; + +import java.io.IOException; +import java.net.URI; + +import org.jclouds.abiquo.domain.NetworkResources; +import org.jclouds.http.HttpRequest; +import org.jclouds.xml.internal.JAXBParser; +import org.testng.annotations.Test; + +import com.abiquo.model.rest.RESTLink; +import com.abiquo.model.transport.LinksDto; +import com.abiquo.server.core.infrastructure.network.PrivateIpDto; + +/** + * Unit tests for the {@link BindIpRefToPayload} binder. + * + * @author Ignasi Barrera + */ +@Test(groups = "unit", testName = "BindIpRefToPayloadTest") +public class BindIpRefToPayloadTest { + + @Test(expectedExceptions = NullPointerException.class) + public void testInvalidNullInput() { + BindIpRefToPayload binder = new BindIpRefToPayload(new JAXBParser("false")); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://localhost")).build(); + binder.bindToRequest(request, null); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testInvalidTypeInput() { + BindIpRefToPayload binder = new BindIpRefToPayload(new JAXBParser("false")); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://localhost")).build(); + binder.bindToRequest(request, new Object()); + } + + public void testBindIpRef() throws IOException { + PrivateIpDto ip = NetworkResources.privateIpPut(); + RESTLink selfLink = ip.searchLink("self"); + BindIpRefToPayload binder = new BindIpRefToPayload(new JAXBParser("false")); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://localhost")).build(); + request = binder.bindToRequest(request, ip); + assertPayloadEquals(request.getPayload(), withHeader(""), LinksDto.class); + + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/cloud/BindIpRefsToPayloadTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/cloud/BindIpRefsToPayloadTest.java new file mode 100644 index 0000000000..dd907b043a --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/cloud/BindIpRefsToPayloadTest.java @@ -0,0 +1,83 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.binders.cloud; + +import static org.jclouds.abiquo.domain.DomainUtils.withHeader; +import static org.jclouds.abiquo.util.Assert.assertPayloadEquals; + +import java.io.IOException; +import java.net.URI; + +import org.jclouds.abiquo.domain.NetworkResources; +import org.jclouds.http.HttpRequest; +import org.jclouds.xml.internal.JAXBParser; +import org.testng.annotations.Test; + +import com.abiquo.model.transport.LinksDto; +import com.abiquo.server.core.infrastructure.network.AbstractIpDto; +import com.abiquo.server.core.infrastructure.network.PrivateIpDto; + +/** + * Unit tests for the {@link BindIpRefsToPayload} binder. + * + * @author Ignasi Barrera + */ +@Test(groups = "unit", testName = "BindIpRefsToPayloadTest") +public class BindIpRefsToPayloadTest { + + @Test(expectedExceptions = NullPointerException.class) + public void testInvalidNullInput() { + BindIpRefsToPayload binder = new BindIpRefsToPayload(new JAXBParser("false")); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://localhost")).build(); + binder.bindToRequest(request, null); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testInvalidTypeInput() { + BindIpRefsToPayload binder = new BindIpRefsToPayload(new JAXBParser("false")); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://localhost")).build(); + binder.bindToRequest(request, new Object()); + } + + public void testBindEmptyArray() throws IOException { + BindIpRefsToPayload binder = new BindIpRefsToPayload(new JAXBParser("false")); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://localhost")).build(); + request = binder.bindToRequest(request, new AbstractIpDto[] {}); + assertPayloadEquals(request.getPayload(), withHeader(""), LinksDto.class); + } + + public void testBindSingleIp() throws IOException { + PrivateIpDto ip = NetworkResources.privateIpPut(); + BindIpRefsToPayload binder = new BindIpRefsToPayload(new JAXBParser("false")); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://localhost")).build(); + request = binder.bindToRequest(request, new AbstractIpDto[] { ip }); + assertPayloadEquals(request.getPayload(), withHeader(""), LinksDto.class); + } + + public void testBindMultipleIps() throws IOException { + PrivateIpDto ip = NetworkResources.privateIpPut(); + BindIpRefsToPayload binder = new BindIpRefsToPayload(new JAXBParser("false")); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://localhost")).build(); + request = binder.bindToRequest(request, new AbstractIpDto[] { ip, ip }); + assertPayloadEquals(request.getPayload(), withHeader(""), LinksDto.class); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/cloud/BindMoveVolumeToPathTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/cloud/BindMoveVolumeToPathTest.java new file mode 100644 index 0000000000..c90b5ed504 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/cloud/BindMoveVolumeToPathTest.java @@ -0,0 +1,70 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.binders.cloud; + +import static org.testng.Assert.assertEquals; + +import java.lang.reflect.Method; +import java.net.URI; + +import javax.ws.rs.HttpMethod; + +import org.jclouds.abiquo.domain.CloudResources; +import org.jclouds.abiquo.features.CloudAsyncApi; +import org.jclouds.rest.internal.GeneratedHttpRequest; +import org.testng.annotations.Test; + +import com.abiquo.server.core.cloud.VirtualDatacenterDto; +import com.abiquo.server.core.infrastructure.storage.VolumeManagementDto; +import com.google.common.collect.ImmutableList; + +/** + * Unit tests for the {@link BindMoveVolumeToPath} binder. + * + * @author Ignasi Barrera + */ +@Test(groups = "unit", testName = "BindMoveVolumeToPathTest") +public class BindMoveVolumeToPathTest { + @Test(expectedExceptions = NullPointerException.class) + public void testInvalidNullInput() throws SecurityException, NoSuchMethodException { + BindMoveVolumeToPath binder = new BindMoveVolumeToPath(); + binder.getNewEndpoint(generatedHttpRequest(), null); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testInvalidInputType() throws SecurityException, NoSuchMethodException { + BindMoveVolumeToPath binder = new BindMoveVolumeToPath(); + binder.getNewEndpoint(generatedHttpRequest(), new Object()); + } + + public void testGetNewEndpoint() throws SecurityException, NoSuchMethodException { + BindMoveVolumeToPath binder = new BindMoveVolumeToPath(); + String newEndpoint = binder.getNewEndpoint(generatedHttpRequest(), CloudResources.volumePut()); + assertEquals(newEndpoint, "http://localhost/api/cloud/virtualdatacenters/1/volumes/1/action/move"); + } + + private static GeneratedHttpRequest generatedHttpRequest() throws SecurityException, NoSuchMethodException { + Method withEndpointLink = CloudAsyncApi.class.getMethod("moveVolume", VolumeManagementDto.class, + VirtualDatacenterDto.class); + return GeneratedHttpRequest.builder().declaring(CloudAsyncApi.class).javaMethod(withEndpointLink) + .args(ImmutableList. of(CloudResources.volumePut(), CloudResources.virtualDatacenterPut())) + .method(HttpMethod.POST).endpoint(URI.create("http://localhost")).build(); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/cloud/BindNetworkConfigurationRefToPayloadTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/cloud/BindNetworkConfigurationRefToPayloadTest.java new file mode 100644 index 0000000000..de436fa817 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/cloud/BindNetworkConfigurationRefToPayloadTest.java @@ -0,0 +1,130 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.binders.cloud; + +import static org.jclouds.abiquo.domain.DomainUtils.withHeader; +import static org.jclouds.abiquo.util.Assert.assertPayloadEquals; + +import java.io.IOException; +import java.lang.reflect.Method; +import java.net.URI; +import java.util.NoSuchElementException; + +import javax.ws.rs.GET; +import javax.ws.rs.HttpMethod; + +import org.jclouds.abiquo.domain.CloudResources; +import org.jclouds.abiquo.domain.NetworkResources; +import org.jclouds.http.HttpRequest; +import org.jclouds.rest.internal.GeneratedHttpRequest; +import org.jclouds.xml.internal.JAXBParser; +import org.testng.annotations.Test; + +import com.abiquo.model.transport.LinksDto; +import com.abiquo.server.core.cloud.VirtualMachineDto; +import com.abiquo.server.core.infrastructure.network.VLANNetworkDto; +import com.google.common.collect.ImmutableList; + +/** + * Unit tests for the {@link BindNetworkConfigurationRefToPayload} binder. + * + * @author Ignasi Barrera + */ +@Test(groups = "unit", testName = "BindNetworkConfigurationRefToPayloadTest") +public class BindNetworkConfigurationRefToPayloadTest { + @Test(expectedExceptions = NullPointerException.class) + public void testInvalidNullRequest() throws SecurityException, NoSuchMethodException { + BindNetworkConfigurationRefToPayload binder = new BindNetworkConfigurationRefToPayload(new JAXBParser("false")); + binder.bindToRequest(null, new Object()); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testInvalidRequestType() throws SecurityException, NoSuchMethodException { + BindNetworkConfigurationRefToPayload binder = new BindNetworkConfigurationRefToPayload(new JAXBParser("false")); + + binder.bindToRequest(HttpRequest.builder().method("m").endpoint("http://localhost").build(), new Object()); + } + + @Test(expectedExceptions = NullPointerException.class) + public void testInvalidNullInput() throws SecurityException, NoSuchMethodException { + VirtualMachineDto vm = CloudResources.virtualMachinePut(); + + Method method = TestNetworkConfig.class.getMethod("withAll", VirtualMachineDto.class, VLANNetworkDto.class); + GeneratedHttpRequest request = GeneratedHttpRequest.builder().declaring(TestNetworkConfig.class) + .javaMethod(method).args(ImmutableList. of(vm, null)).method(HttpMethod.GET) + .endpoint(URI.create("http://localhost")).build(); + + BindNetworkConfigurationRefToPayload binder = new BindNetworkConfigurationRefToPayload(new JAXBParser("false")); + binder.bindToRequest(request, null); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testInvalidTypeInput() throws SecurityException, NoSuchMethodException { + VirtualMachineDto vm = CloudResources.virtualMachinePut(); + Object network = new Object(); + + Method method = TestNetworkConfig.class.getMethod("withAll", VirtualMachineDto.class, VLANNetworkDto.class); + GeneratedHttpRequest request = GeneratedHttpRequest.builder().declaring(TestNetworkConfig.class) + .javaMethod(method).args(ImmutableList. of(vm, network)).method(HttpMethod.GET) + .endpoint(URI.create("http://localhost")).build(); + + BindNetworkConfigurationRefToPayload binder = new BindNetworkConfigurationRefToPayload(new JAXBParser("false")); + binder.bindToRequest(request, network); + } + + @Test(expectedExceptions = NoSuchElementException.class) + public void testBindNetworkConfigurationRefWithoutVirtualMachine() throws SecurityException, NoSuchMethodException { + VLANNetworkDto network = NetworkResources.privateNetworkPut(); + + Method method = TestNetworkConfig.class.getMethod("withoutVirtualMachine", VLANNetworkDto.class); + GeneratedHttpRequest request = GeneratedHttpRequest.builder().declaring(TestNetworkConfig.class) + .javaMethod(method).args(ImmutableList. of(network)).method(HttpMethod.GET) + .endpoint(URI.create("http://localhost")).build(); + + BindNetworkConfigurationRefToPayload binder = new BindNetworkConfigurationRefToPayload(new JAXBParser("false")); + binder.bindToRequest(request, network); + } + + public void testBindNetworkConfigurationRef() throws SecurityException, NoSuchMethodException, IOException { + VirtualMachineDto vm = CloudResources.virtualMachinePut(); + VLANNetworkDto network = NetworkResources.privateNetworkPut(); + + Method method = TestNetworkConfig.class.getMethod("withAll", VirtualMachineDto.class, VLANNetworkDto.class); + GeneratedHttpRequest request = GeneratedHttpRequest.builder().declaring(TestNetworkConfig.class) + .javaMethod(method).args(ImmutableList. of(vm, network)).method(HttpMethod.GET) + .endpoint(URI.create("http://localhost")).build(); + + BindNetworkConfigurationRefToPayload binder = new BindNetworkConfigurationRefToPayload(new JAXBParser("false")); + + String configLink = vm.searchLink("configurations").getHref() + "/" + network.getId(); + + GeneratedHttpRequest newRequest = binder.bindToRequest(request, network); + assertPayloadEquals(newRequest.getPayload(), withHeader(""), LinksDto.class); + } + + static interface TestNetworkConfig { + @GET + void withoutVirtualMachine(VLANNetworkDto network); + + @GET + void withAll(VirtualMachineDto virtualMachine, VLANNetworkDto network); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/cloud/BindNetworkRefToPayloadTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/cloud/BindNetworkRefToPayloadTest.java new file mode 100644 index 0000000000..94af9f24ca --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/cloud/BindNetworkRefToPayloadTest.java @@ -0,0 +1,66 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.binders.cloud; + +import static org.jclouds.abiquo.domain.DomainUtils.withHeader; +import static org.jclouds.abiquo.util.Assert.assertPayloadEquals; + +import java.io.IOException; +import java.net.URI; + +import org.jclouds.abiquo.domain.NetworkResources; +import org.jclouds.http.HttpRequest; +import org.jclouds.xml.internal.JAXBParser; +import org.testng.annotations.Test; + +import com.abiquo.model.transport.LinksDto; +import com.abiquo.server.core.infrastructure.network.VLANNetworkDto; + +/** + * Unit tests for the {@link BindNetworkRefToPayload} binder. + * + * @author Ignasi Barrera + */ +@Test(groups = "unit", testName = "BindNetworkRefToPayloadTest") +public class BindNetworkRefToPayloadTest { + + @Test(expectedExceptions = NullPointerException.class) + public void testInvalidNullInput() { + BindNetworkRefToPayload binder = new BindNetworkRefToPayload(new JAXBParser("false")); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://localhost")).build(); + binder.bindToRequest(request, null); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testInvalidTypeInput() { + BindNetworkRefToPayload binder = new BindNetworkRefToPayload(new JAXBParser("false")); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://localhost")).build(); + binder.bindToRequest(request, new Object()); + } + + public void testBindNetworkRef() throws IOException { + VLANNetworkDto network = NetworkResources.privateNetworkPut(); + BindNetworkRefToPayload binder = new BindNetworkRefToPayload(new JAXBParser("false")); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://localhost")).build(); + request = binder.bindToRequest(request, network); + assertPayloadEquals(request.getPayload(), withHeader(""), LinksDto.class); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/cloud/BindUnmanagedIpRefToPayloadTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/cloud/BindUnmanagedIpRefToPayloadTest.java new file mode 100644 index 0000000000..f29a5d4a83 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/cloud/BindUnmanagedIpRefToPayloadTest.java @@ -0,0 +1,68 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.binders.cloud; + +import static org.jclouds.abiquo.domain.DomainUtils.withHeader; +import static org.jclouds.abiquo.util.Assert.assertPayloadEquals; + +import java.io.IOException; +import java.net.URI; + +import org.jclouds.abiquo.domain.NetworkResources; +import org.jclouds.http.HttpRequest; +import org.jclouds.xml.internal.JAXBParser; +import org.testng.annotations.Test; + +import com.abiquo.model.rest.RESTLink; +import com.abiquo.model.transport.LinksDto; +import com.abiquo.server.core.infrastructure.network.VLANNetworkDto; + +/** + * Unit tests for the {@link BindUnmanagedIpRefToPayload} binder. + * + * @author Ignasi Barrera + */ +@Test(groups = "unit", testName = "BindUnmanagedIpRefToPayloadTest") +public class BindUnmanagedIpRefToPayloadTest { + + @Test(expectedExceptions = NullPointerException.class) + public void testInvalidNullInput() { + BindUnmanagedIpRefToPayload binder = new BindUnmanagedIpRefToPayload(new JAXBParser("false")); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://localhost")).build(); + binder.bindToRequest(request, null); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testInvalidTypeInput() { + BindUnmanagedIpRefToPayload binder = new BindUnmanagedIpRefToPayload(new JAXBParser("false")); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://localhost")).build(); + binder.bindToRequest(request, new Object()); + } + + public void testBindUnmanagedNetworkIpRef() throws IOException { + VLANNetworkDto network = NetworkResources.unmanagedNetworkPut(); + RESTLink ipsLink = network.searchLink("ips"); + BindUnmanagedIpRefToPayload binder = new BindUnmanagedIpRefToPayload(new JAXBParser("false")); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://localhost")).build(); + request = binder.bindToRequest(request, network); + assertPayloadEquals(request.getPayload(), withHeader(""), LinksDto.class); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/cloud/BindVirtualDatacenterRefToPayloadTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/cloud/BindVirtualDatacenterRefToPayloadTest.java new file mode 100644 index 0000000000..ff66ae3e42 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/cloud/BindVirtualDatacenterRefToPayloadTest.java @@ -0,0 +1,66 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.binders.cloud; + +import static org.jclouds.abiquo.domain.DomainUtils.withHeader; +import static org.jclouds.abiquo.util.Assert.assertPayloadEquals; + +import java.io.IOException; +import java.net.URI; + +import org.jclouds.abiquo.domain.CloudResources; +import org.jclouds.http.HttpRequest; +import org.jclouds.xml.internal.JAXBParser; +import org.testng.annotations.Test; + +import com.abiquo.model.transport.LinksDto; +import com.abiquo.server.core.cloud.VirtualDatacenterDto; + +/** + * Unit tests for the {@link BindVirtualDatacenterRefToPayload} binder. + * + * @author Ignasi Barrera + */ +@Test(groups = "unit", testName = "BindVirtualDatacenterRefToPayloadTest") +public class BindVirtualDatacenterRefToPayloadTest { + + @Test(expectedExceptions = NullPointerException.class) + public void testInvalidNullInput() { + BindVirtualDatacenterRefToPayload binder = new BindVirtualDatacenterRefToPayload(new JAXBParser("false")); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://localhost")).build(); + binder.bindToRequest(request, null); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testInvalidTypeInput() { + BindVirtualDatacenterRefToPayload binder = new BindVirtualDatacenterRefToPayload(new JAXBParser("false")); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://localhost")).build(); + binder.bindToRequest(request, new Object()); + } + + public void testBindSingleVolume() throws IOException { + VirtualDatacenterDto vdc = CloudResources.virtualDatacenterPut(); + BindVirtualDatacenterRefToPayload binder = new BindVirtualDatacenterRefToPayload(new JAXBParser("false")); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://localhost")).build(); + request = binder.bindToRequest(request, vdc); + assertPayloadEquals(request.getPayload(), withHeader(""), LinksDto.class); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/cloud/BindVolumeRefsToPayloadTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/cloud/BindVolumeRefsToPayloadTest.java new file mode 100644 index 0000000000..67dfc0e5cf --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/cloud/BindVolumeRefsToPayloadTest.java @@ -0,0 +1,82 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.binders.cloud; + +import static org.jclouds.abiquo.domain.DomainUtils.withHeader; +import static org.jclouds.abiquo.util.Assert.assertPayloadEquals; + +import java.io.IOException; +import java.net.URI; + +import org.jclouds.abiquo.domain.CloudResources; +import org.jclouds.http.HttpRequest; +import org.jclouds.xml.internal.JAXBParser; +import org.testng.annotations.Test; + +import com.abiquo.model.transport.LinksDto; +import com.abiquo.server.core.infrastructure.storage.VolumeManagementDto; + +/** + * Unit tests for the {@link BindVolumeRefsToPayload} binder. + * + * @author Ignasi Barrera + */ +@Test(groups = "unit", testName = "BindVolumeRefsToPayloadTest") +public class BindVolumeRefsToPayloadTest { + + @Test(expectedExceptions = NullPointerException.class) + public void testInvalidNullInput() { + BindVolumeRefsToPayload binder = new BindVolumeRefsToPayload(new JAXBParser("false")); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://localhost")).build(); + binder.bindToRequest(request, null); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testInvalidTypeInput() { + BindVolumeRefsToPayload binder = new BindVolumeRefsToPayload(new JAXBParser("false")); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://localhost")).build(); + binder.bindToRequest(request, new Object()); + } + + public void testBindEmptyArray() throws IOException { + BindVolumeRefsToPayload binder = new BindVolumeRefsToPayload(new JAXBParser("false")); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://localhost")).build(); + request = binder.bindToRequest(request, new VolumeManagementDto[] {}); + assertPayloadEquals(request.getPayload(), withHeader(""), LinksDto.class); + } + + public void testBindSingleVolume() throws IOException { + VolumeManagementDto volume = CloudResources.volumePut(); + BindVolumeRefsToPayload binder = new BindVolumeRefsToPayload(new JAXBParser("false")); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://localhost")).build(); + request = binder.bindToRequest(request, new VolumeManagementDto[] { volume }); + assertPayloadEquals(request.getPayload(), withHeader(""), LinksDto.class); + } + + public void testBindMultipleVolumes() throws IOException { + VolumeManagementDto volume = CloudResources.volumePut(); + BindVolumeRefsToPayload binder = new BindVolumeRefsToPayload(new JAXBParser("false")); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://localhost")).build(); + request = binder.bindToRequest(request, new VolumeManagementDto[] { volume, volume }); + assertPayloadEquals(request.getPayload(), withHeader(""), LinksDto.class); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/infrastructure/AppendMachineIdToPathTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/infrastructure/AppendMachineIdToPathTest.java new file mode 100644 index 0000000000..8a85c3c032 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/infrastructure/AppendMachineIdToPathTest.java @@ -0,0 +1,61 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.binders.infrastructure; + +import static org.testng.Assert.assertEquals; + +import java.net.URI; + +import org.jclouds.abiquo.functions.infrastructure.ParseMachineId; +import org.jclouds.http.HttpRequest; +import org.testng.annotations.Test; + +import com.abiquo.server.core.infrastructure.MachineDto; + +/** + * Unit tests for the {@link AppendMachineIdToPath} binder. + * + * @author Ignasi Barrera + */ +@Test(groups = "unit", testName = "AppendMachineIdToPathTest") +public class AppendMachineIdToPathTest { + @Test(expectedExceptions = NullPointerException.class) + public void testGetValueWithNullInput() { + AppendMachineIdToPath binder = new AppendMachineIdToPath(new ParseMachineId()); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://localhost")).build(); + binder.getValue(request, null); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testGetValueWithInvalidInput() { + AppendMachineIdToPath binder = new AppendMachineIdToPath(new ParseMachineId()); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://localhost")).build(); + binder.getValue(request, new Object()); + } + + public void testGetValue() { + AppendMachineIdToPath binder = new AppendMachineIdToPath(new ParseMachineId()); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://localhost")).build(); + + MachineDto machine = new MachineDto(); + machine.setId(5); + assertEquals(binder.getValue(request, machine), "5"); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/infrastructure/AppendRemoteServiceTypeToPathTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/infrastructure/AppendRemoteServiceTypeToPathTest.java new file mode 100644 index 0000000000..a0b1f52d65 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/infrastructure/AppendRemoteServiceTypeToPathTest.java @@ -0,0 +1,59 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.binders.infrastructure; + +import static org.testng.Assert.assertEquals; + +import java.net.URI; + +import org.jclouds.abiquo.functions.infrastructure.ParseRemoteServiceType; +import org.jclouds.http.HttpRequest; +import org.testng.annotations.Test; + +import com.abiquo.model.enumerator.RemoteServiceType; + +/** + * Unit tests for the {@link AppendRemoteServiceTypeToPath} binder. + * + * @author Ignasi Barrera + */ +@Test(groups = "unit", testName = "AppendRemoteServiceTypeToPathTest") +public class AppendRemoteServiceTypeToPathTest { + @Test(expectedExceptions = NullPointerException.class) + public void testGetValueWithNullInput() { + AppendRemoteServiceTypeToPath binder = new AppendRemoteServiceTypeToPath(new ParseRemoteServiceType()); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://localhost")).build(); + binder.getValue(request, null); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testGetValueWithInvalidInput() { + AppendRemoteServiceTypeToPath binder = new AppendRemoteServiceTypeToPath(new ParseRemoteServiceType()); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://localhost")).build(); + binder.getValue(request, new Object()); + } + + public void testGetValue() { + AppendRemoteServiceTypeToPath binder = new AppendRemoteServiceTypeToPath(new ParseRemoteServiceType()); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://localhost")).build(); + + assertEquals(binder.getValue(request, RemoteServiceType.VIRTUAL_SYSTEM_MONITOR), "virtualsystemmonitor"); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/infrastructure/BindSupportedDevicesLinkToPathTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/infrastructure/BindSupportedDevicesLinkToPathTest.java new file mode 100644 index 0000000000..204b34e20d --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/infrastructure/BindSupportedDevicesLinkToPathTest.java @@ -0,0 +1,87 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.binders.infrastructure; + +import static org.testng.Assert.assertEquals; + +import java.lang.reflect.Method; +import java.net.URI; + +import javax.ws.rs.HttpMethod; + +import org.jclouds.abiquo.features.InfrastructureAsyncApi; +import org.jclouds.rest.internal.GeneratedHttpRequest; +import org.testng.annotations.Test; + +import com.abiquo.model.rest.RESTLink; +import com.abiquo.server.core.infrastructure.DatacenterDto; +import com.google.common.collect.ImmutableList; + +/** + * Unit tests for the {@link BindSupportedDevicesLinkToPath} class. + * + * @author Ignasi Barrera + */ +@Test(groups = "unit", testName = "BindSupportedDevicesLinkToPathTest") +public class BindSupportedDevicesLinkToPathTest { + @Test(expectedExceptions = NullPointerException.class) + public void testGetNewEnpointNullInput() { + BindSupportedDevicesLinkToPath binder = new BindSupportedDevicesLinkToPath(); + binder.getNewEndpoint(null, null); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testGetNewEnpointInvalidInput() { + BindSupportedDevicesLinkToPath binder = new BindSupportedDevicesLinkToPath(); + binder.getNewEndpoint(null, new Object()); + } + + public void testGetNewEnpoint() throws Exception { + DatacenterDto datacenter = new DatacenterDto(); + datacenter.addLink(new RESTLink("devices", "http://foo/bar")); + + BindSupportedDevicesLinkToPath binder = new BindSupportedDevicesLinkToPath(); + + Method withEndpointLink = InfrastructureAsyncApi.class.getMethod("listSupportedStorageDevices", + DatacenterDto.class); + + GeneratedHttpRequest request = GeneratedHttpRequest.builder().declaring(InfrastructureAsyncApi.class) + .javaMethod(withEndpointLink).args(ImmutableList. of(datacenter)).method(HttpMethod.GET) + .endpoint(URI.create("http://foo/bar")).build(); + + assertEquals(binder.getNewEndpoint(request, datacenter), "http://foo/bar/action/supported"); + } + + @Test(expectedExceptions = NullPointerException.class) + public void testGetNewEnpointWithoutLink() throws Exception { + DatacenterDto datacenter = new DatacenterDto(); + + BindSupportedDevicesLinkToPath binder = new BindSupportedDevicesLinkToPath(); + + Method withEndpointLink = InfrastructureAsyncApi.class.getMethod("listSupportedStorageDevices", + DatacenterDto.class); + + GeneratedHttpRequest request = GeneratedHttpRequest.builder().declaring(InfrastructureAsyncApi.class) + .javaMethod(withEndpointLink).args(ImmutableList. of(datacenter)).method(HttpMethod.GET) + .endpoint(URI.create("http://foo/bar")).build(); + + assertEquals(binder.getNewEndpoint(request, datacenter), "http://foo/bar/action/supported"); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/infrastructure/ucs/BindLogicServerParametersTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/infrastructure/ucs/BindLogicServerParametersTest.java new file mode 100644 index 0000000000..0ef5089bbc --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/infrastructure/ucs/BindLogicServerParametersTest.java @@ -0,0 +1,68 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.binders.infrastructure.ucs; + +import static org.testng.Assert.assertEquals; + +import java.net.URI; + +import org.jclouds.http.HttpRequest; +import org.testng.annotations.Test; + +import com.abiquo.server.core.infrastructure.LogicServerDto; + +/** + * Unit tests for the {@link BindLogicServerParameters} binder. + * + * @author Francesc Montserrat + */ +@Test(groups = "unit", testName = "BindLogicServerParametersTest") +public class BindLogicServerParametersTest { + @Test(expectedExceptions = NullPointerException.class) + public void testInvalidNullInput() { + BindLogicServerParameters binder = new BindLogicServerParameters(); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://localhost")).build(); + binder.bindToRequest(request, null); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testInvalidTypeInput() { + BindLogicServerParameters binder = new BindLogicServerParameters(); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://localhost")).build(); + binder.bindToRequest(request, new Object()); + } + + @Test(expectedExceptions = NullPointerException.class) + public void testBindLogicServerWithEmptyName() { + BindLogicServerParameters binder = new BindLogicServerParameters(); + LogicServerDto dto = new LogicServerDto(); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://localhost")).build(); + binder.bindToRequest(request, dto); + } + + public void testBindLogicServer() { + BindLogicServerParameters binder = new BindLogicServerParameters(); + LogicServerDto dto = new LogicServerDto(); + dto.setName("name"); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://localhost")).build(); + HttpRequest newRequest = binder.bindToRequest(request, dto); + assertEquals(newRequest.getRequestLine(), "GET http://localhost?lsName=name HTTP/1.1"); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/infrastructure/ucs/BindOrganizationParametersTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/infrastructure/ucs/BindOrganizationParametersTest.java new file mode 100644 index 0000000000..753d7e4f9b --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/binders/infrastructure/ucs/BindOrganizationParametersTest.java @@ -0,0 +1,68 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.binders.infrastructure.ucs; + +import static org.testng.Assert.assertEquals; + +import java.net.URI; + +import org.jclouds.http.HttpRequest; +import org.testng.annotations.Test; + +import com.abiquo.server.core.infrastructure.OrganizationDto; + +/** + * Unit tests for the {@link BindOrganizationParameters} binder. + * + * @author Francesc Montserrat + */ +@Test(groups = "unit", testName = "BindOrganizationParametersTest") +public class BindOrganizationParametersTest { + @Test(expectedExceptions = NullPointerException.class) + public void testInvalidNullInput() { + BindOrganizationParameters binder = new BindOrganizationParameters(); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://localhost")).build(); + binder.bindToRequest(request, null); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testInvalidTypeInput() { + BindOrganizationParameters binder = new BindOrganizationParameters(); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://localhost")).build(); + binder.bindToRequest(request, new Object()); + } + + @Test(expectedExceptions = NullPointerException.class) + public void testBindLogicServerWithEmptyName() { + BindOrganizationParameters binder = new BindOrganizationParameters(); + OrganizationDto dto = new OrganizationDto(); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://localhost")).build(); + binder.bindToRequest(request, dto); + } + + public void testBindLogicServer() { + BindOrganizationParameters binder = new BindOrganizationParameters(); + OrganizationDto dto = new OrganizationDto(); + dto.setDn("org"); + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://localhost")).build(); + HttpRequest newRequest = binder.bindToRequest(request, dto); + assertEquals(newRequest.getRequestLine(), "GET http://localhost?org=org HTTP/1.1"); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/compute/AbiquoComputeServiceLiveTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/compute/AbiquoComputeServiceLiveTest.java new file mode 100644 index 0000000000..853f55fd54 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/compute/AbiquoComputeServiceLiveTest.java @@ -0,0 +1,126 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.compute; + +import static org.jclouds.compute.util.ComputeServiceUtils.getCores; +import static org.testng.Assert.assertEquals; + +import java.util.Properties; + +import org.jclouds.Constants; +import org.jclouds.compute.domain.ComputeType; +import org.jclouds.compute.domain.ExecResponse; +import org.jclouds.compute.domain.Hardware; +import org.jclouds.compute.domain.NodeMetadata; +import org.jclouds.compute.internal.BaseComputeServiceLiveTest; +import org.jclouds.logging.config.LoggingModule; +import org.jclouds.logging.slf4j.config.SLF4JLoggingModule; +import org.jclouds.sshj.config.SshjSshClientModule; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; +import com.google.inject.Module; + +/** + * Live tests for the Abiquo ComputeService. + * + * @author Ignasi Barrera + */ +@Test(groups = "live", testName = "AbiquoComputeServiceLiveTest", singleThreaded = true) +// Made abstract to avoid executing tests. Since the base class has test +// configuration, even if we +// disable tests here, or comment them out, the ones in the base class will be +// executed +public class AbiquoComputeServiceLiveTest extends BaseComputeServiceLiveTest { + public AbiquoComputeServiceLiveTest() { + provider = "abiquo"; + } + + @Override + public void setServiceDefaults() { + System.setProperty("test.abiquo.template", + "imageNameMatches=ubuntu_server_ssh_iptables,loginUser=user:abiquo,authenticateSudo=true"); + } + + @Override + protected Properties setupProperties() { + Properties overrides = super.setupProperties(); + overrides.put(Constants.PROPERTY_MAX_RETRIES, "0"); + overrides.put(Constants.PROPERTY_MAX_REDIRECTS, "0"); + overrides.put("jclouds.timeouts.CloudApi.listVirtualMachines", "60000"); + return overrides; + } + + @Override + protected void initializeContext() { + super.initializeContext(); + String templateId = buildTemplate(client.templateBuilder()).getImage().getId(); + view.getUtils().getCredentialStore().put("image#" + templateId, loginCredentials); + } + + @Override + protected LoggingModule getLoggingModule() { + return new SLF4JLoggingModule(); + } + + @Override + protected Module getSshModule() { + return new SshjSshClientModule(); + } + + @Override + public void testListSizes() throws Exception { + for (Hardware hardware : client.listHardwareProfiles()) { + assert hardware.getProviderId() != null : hardware; + assert getCores(hardware) > 0 : hardware; + assert hardware.getVolumes().size() >= 0 : hardware; + // There are some small images in Abiquo that have less than 1GB of RAM + // assert hardware.getRam() > 0 : hardware; + assertEquals(hardware.getType(), ComputeType.HARDWARE); + } + } + + @Override + public void testOptionToNotBlock() throws Exception { + // By default the provider blocks until the node is running + } + + // Abiquo does not set the hostname + @Override + protected void checkResponseEqualsHostname(final ExecResponse execResponse, final NodeMetadata node) { + assert node.getHostname() == null : node + " with hostname: " + node.getHostname(); + } + + // Abiquo does not support metadata + @Override + protected void checkUserMetadataInNodeEquals(final NodeMetadata node, final ImmutableMap userMetadata) { + assert node.getUserMetadata().equals(ImmutableMap. of()) : String.format( + "node userMetadata did not match %s %s", userMetadata, node); + } + + // Abiquo does not support tags + @Override + protected void checkTagsInNodeEquals(final NodeMetadata node, final ImmutableSet tags) { + assert node.getTags().equals(ImmutableSet. of()) : String.format("node tags did not match %s %s", tags, + node); + } + +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/compute/functions/DatacenterToLocationTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/compute/functions/DatacenterToLocationTest.java new file mode 100644 index 0000000000..715af5cdb5 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/compute/functions/DatacenterToLocationTest.java @@ -0,0 +1,52 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.compute.functions; + +import static org.testng.Assert.assertEquals; + +import org.easymock.EasyMock; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.domain.infrastructure.Datacenter; +import org.jclouds.domain.Location; +import org.jclouds.domain.LocationScope; +import org.jclouds.rest.RestContext; +import org.testng.annotations.Test; + +/** + * Unit tests for the {@link DatacenterToLocation} function. + * + * @author Ignasi Barrera + */ +@Test(groups = "unit", testName = "DatacenterToLocationTest") +public class DatacenterToLocationTest { + @SuppressWarnings("unchecked") + public void testDatacenterToLocation() { + RestContext context = EasyMock.createMock(RestContext.class); + DatacenterToLocation function = new DatacenterToLocation(); + + Datacenter datacenter = Datacenter.builder(context).name("dc").location("New York").build(); + datacenter.unwrap().setId(5); + Location location = function.apply(datacenter); + + assertEquals(location.getId(), "5"); + assertEquals(location.getScope(), LocationScope.REGION); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/compute/functions/VirtualDatacenterToLocationTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/compute/functions/VirtualDatacenterToLocationTest.java new file mode 100644 index 0000000000..644eb11eda --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/compute/functions/VirtualDatacenterToLocationTest.java @@ -0,0 +1,99 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.compute.functions; + +import static org.easymock.EasyMock.anyObject; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; +import static org.testng.Assert.assertEquals; + +import java.util.Collections; +import java.util.Map; + +import org.easymock.EasyMock; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.domain.cloud.VirtualDatacenter; +import org.jclouds.abiquo.domain.enterprise.Enterprise; +import org.jclouds.abiquo.domain.infrastructure.Datacenter; +import org.jclouds.abiquo.domain.network.PrivateNetwork; +import org.jclouds.domain.Location; +import org.jclouds.domain.LocationScope; +import org.jclouds.rest.RestContext; +import org.testng.annotations.Test; + +import com.google.common.base.Function; +import com.google.common.base.Supplier; + +/** + * Unit tests for the {@link VirtualDatacenterToLocation} function. + * + * @author Ignasi Barrera + */ +@Test(groups = "unit", testName = "VirtualDatacenterToLocationTest") +public class VirtualDatacenterToLocationTest { + public void testVirtualDatacenterToLocation() { + Function dcToLocation = mockDatacenterToLocation(); + Supplier> regionMap = mockRegionMap(); + VirtualDatacenterToLocation function = new VirtualDatacenterToLocation(dcToLocation, regionMap); + + VirtualDatacenter vdc = mockVirtualDatacenter(); + + Location location = function.apply(vdc); + + verify(regionMap); + verify(dcToLocation); + + assertEquals(location.getId(), "5"); + assertEquals(location.getScope(), LocationScope.ZONE); + } + + @SuppressWarnings("unchecked") + private static VirtualDatacenter mockVirtualDatacenter() { + RestContext context = EasyMock.createMock(RestContext.class); + Datacenter datacenter = EasyMock.createMock(Datacenter.class); + Enterprise enterprise = EasyMock.createMock(Enterprise.class); + PrivateNetwork network = EasyMock.createMock(PrivateNetwork.class); + + VirtualDatacenter vdc = VirtualDatacenter.builder(context, datacenter, enterprise) // + .network(network) // + .name("mock").build(); + vdc.unwrap().setId(5); + + return vdc; + } + + @SuppressWarnings("unchecked") + private static Function mockDatacenterToLocation() { + Function mock = EasyMock.createMock(Function.class); + expect(mock.apply(anyObject(Datacenter.class))).andReturn(null); + replay(mock); + return mock; + } + + @SuppressWarnings("unchecked") + private static Supplier> mockRegionMap() { + Supplier> mock = EasyMock.createMock(Supplier.class); + expect(mock.get()).andReturn(Collections.EMPTY_MAP); + replay(mock); + return mock; + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/compute/functions/VirtualMachineStateToNodeStateTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/compute/functions/VirtualMachineStateToNodeStateTest.java new file mode 100644 index 0000000000..c5c210677d --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/compute/functions/VirtualMachineStateToNodeStateTest.java @@ -0,0 +1,48 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.compute.functions; + +import static org.testng.Assert.assertEquals; + +import org.jclouds.compute.domain.NodeMetadata.Status; +import org.testng.annotations.Test; + +import com.abiquo.server.core.cloud.VirtualMachineState; + +/** + * Unit tests for the {@link VirtualMachineStateToNodeState} function. + * + * @author Ignasi Barrera + */ +@Test(groups = "unit", testName = "VirtualMachineStateToNodeStateTest") +public class VirtualMachineStateToNodeStateTest { + public void testVirtualMachineStateToNodeState() { + VirtualMachineStateToNodeState function = new VirtualMachineStateToNodeState(); + + assertEquals(function.apply(VirtualMachineState.ALLOCATED), Status.PENDING); + assertEquals(function.apply(VirtualMachineState.LOCKED), Status.PENDING); + assertEquals(function.apply(VirtualMachineState.CONFIGURED), Status.PENDING); + assertEquals(function.apply(VirtualMachineState.ON), Status.RUNNING); + assertEquals(function.apply(VirtualMachineState.OFF), Status.SUSPENDED); + assertEquals(function.apply(VirtualMachineState.PAUSED), Status.SUSPENDED); + assertEquals(function.apply(VirtualMachineState.NOT_ALLOCATED), Status.PENDING); + assertEquals(function.apply(VirtualMachineState.UNKNOWN), Status.UNRECOGNIZED); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/compute/functions/VirtualMachineTemplateInVirtualDatacenterToHardwareTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/compute/functions/VirtualMachineTemplateInVirtualDatacenterToHardwareTest.java new file mode 100644 index 0000000000..6ede999c5c --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/compute/functions/VirtualMachineTemplateInVirtualDatacenterToHardwareTest.java @@ -0,0 +1,236 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.compute.functions; + +import static org.easymock.EasyMock.anyObject; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; +import static org.jclouds.abiquo.domain.DomainWrapper.wrap; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNull; + +import java.net.URI; + +import org.easymock.EasyMock; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.domain.cloud.VirtualDatacenter; +import org.jclouds.abiquo.domain.cloud.VirtualMachineTemplate; +import org.jclouds.abiquo.domain.cloud.VirtualMachineTemplateInVirtualDatacenter; +import org.jclouds.compute.domain.Hardware; +import org.jclouds.compute.domain.Volume; +import org.jclouds.domain.Location; +import org.jclouds.rest.RestContext; +import org.testng.annotations.Test; + +import com.abiquo.model.enumerator.HypervisorType; +import com.abiquo.model.rest.RESTLink; +import com.abiquo.server.core.appslibrary.VirtualMachineTemplateDto; +import com.abiquo.server.core.cloud.VirtualDatacenterDto; +import com.google.common.base.Function; + +/** + * Unit tests for the + * {@link VirtualMachineTemplateInVirtualDatacenterToHardware} function. + * + * @author Ignasi Barrera + */ +@Test(groups = "unit", testName = "VirtualMachineTemplateInVirtualDatacenterToHardwareTest") +public class VirtualMachineTemplateInVirtualDatacenterToHardwareTest { + @SuppressWarnings("unchecked") + public void testVirtualMachineTemplateToHardware() { + RestContext context = EasyMock.createMock(RestContext.class); + Function vdcToLocation = mockVirtualDatacenterToLocation(); + VirtualMachineTemplateInVirtualDatacenterToHardware function = new VirtualMachineTemplateInVirtualDatacenterToHardware( + vdcToLocation); + + VirtualMachineTemplateDto dto = new VirtualMachineTemplateDto(); + dto.setId(5); + dto.setName("Template"); + dto.setDescription("Template description"); + dto.setHdRequired(50L * 1024 * 1024 * 1024); // 50 GB + dto.setCpuRequired(5); + dto.setRamRequired(2048); + dto.addLink(new RESTLink("edit", "http://foo/bar")); + VirtualMachineTemplate template = wrap(context, VirtualMachineTemplate.class, dto); + + VirtualDatacenterDto vdcDto = new VirtualDatacenterDto(); + vdcDto.setId(6); + vdcDto.setHypervisorType(HypervisorType.VMX_04); + VirtualDatacenter vdc = wrap(context, VirtualDatacenter.class, vdcDto); + + Hardware hardware = function.apply(new VirtualMachineTemplateInVirtualDatacenter(template, vdc)); + + verify(vdcToLocation); + + assertEquals(hardware.getProviderId(), template.getId().toString()); + assertEquals(hardware.getId(), template.getId() + "/" + vdc.getId()); + assertEquals(hardware.getName(), template.getName()); + assertEquals(hardware.getUri(), URI.create("http://foo/bar")); + + assertEquals(hardware.getRam(), template.getRamRequired()); + assertEquals(hardware.getProcessors().size(), 1); + assertEquals(hardware.getProcessors().get(0).getCores(), (double) template.getCpuRequired()); + assertEquals(hardware.getProcessors().get(0).getSpeed(), + VirtualMachineTemplateInVirtualDatacenterToHardware.DEFAULT_CORE_SPEED); + + assertEquals(hardware.getVolumes().size(), 1); + assertEquals(hardware.getVolumes().get(0).getSize(), 50F); + assertEquals(hardware.getVolumes().get(0).getType(), Volume.Type.LOCAL); + assertEquals(hardware.getVolumes().get(0).isBootDevice(), true); + assertEquals(hardware.getVolumes().get(0).isDurable(), false); + } + + @SuppressWarnings("unchecked") + public void testConvertWithoutEditLink() { + RestContext context = EasyMock.createMock(RestContext.class); + Function vdcToLocation = mockVirtualDatacenterToLocation(); + VirtualMachineTemplateInVirtualDatacenterToHardware function = new VirtualMachineTemplateInVirtualDatacenterToHardware( + vdcToLocation); + + VirtualMachineTemplateDto dto = new VirtualMachineTemplateDto(); + dto.setId(5); + dto.setName("Template"); + dto.setDescription("Template description"); + dto.setHdRequired(50L * 1024 * 1024 * 1024); // 50 GB + dto.setCpuRequired(5); + dto.setRamRequired(2048); + VirtualMachineTemplate template = wrap(context, VirtualMachineTemplate.class, dto); + + VirtualDatacenterDto vdcDto = new VirtualDatacenterDto(); + vdcDto.setId(6); + vdcDto.setHypervisorType(HypervisorType.VMX_04); + VirtualDatacenter vdc = wrap(context, VirtualDatacenter.class, vdcDto); + + Hardware hardware = function.apply(new VirtualMachineTemplateInVirtualDatacenter(template, vdc)); + + verify(vdcToLocation); + + assertNull(hardware.getUri()); + } + + @SuppressWarnings("unchecked") + @Test(expectedExceptions = NullPointerException.class) + public void testConvertWithoutId() { + RestContext context = EasyMock.createMock(RestContext.class); + Function vdcToLocation = mockVirtualDatacenterToLocation(); + VirtualMachineTemplateInVirtualDatacenterToHardware function = new VirtualMachineTemplateInVirtualDatacenterToHardware( + vdcToLocation); + + VirtualMachineTemplate template = wrap(context, VirtualMachineTemplate.class, new VirtualMachineTemplateDto()); + VirtualDatacenter vdc = wrap(context, VirtualDatacenter.class, new VirtualDatacenterDto()); + + function.apply(new VirtualMachineTemplateInVirtualDatacenter(template, vdc)); + } + + @SuppressWarnings("unchecked") + public void testConvertWithoutCpu() { + RestContext context = EasyMock.createMock(RestContext.class); + Function vdcToLocation = mockVirtualDatacenterToLocation(); + VirtualMachineTemplateInVirtualDatacenterToHardware function = new VirtualMachineTemplateInVirtualDatacenterToHardware( + vdcToLocation); + + VirtualMachineTemplateDto dto = new VirtualMachineTemplateDto(); + dto.setId(5); + dto.setName("Template"); + dto.setDescription("Template description"); + dto.setHdRequired(50L * 1024 * 1024 * 1024); // 50 GB + dto.setRamRequired(2048); + VirtualMachineTemplate template = wrap(context, VirtualMachineTemplate.class, dto); + + VirtualDatacenterDto vdcDto = new VirtualDatacenterDto(); + vdcDto.setId(6); + vdcDto.setHypervisorType(HypervisorType.VMX_04); + VirtualDatacenter vdc = wrap(context, VirtualDatacenter.class, vdcDto); + + Hardware hardware = function.apply(new VirtualMachineTemplateInVirtualDatacenter(template, vdc)); + + verify(vdcToLocation); + + assertEquals(hardware.getProcessors().size(), 1); + assertEquals(hardware.getProcessors().get(0).getCores(), 0D); + } + + @SuppressWarnings("unchecked") + public void testConvertWithoutRam() { + RestContext context = EasyMock.createMock(RestContext.class); + Function vdcToLocation = mockVirtualDatacenterToLocation(); + VirtualMachineTemplateInVirtualDatacenterToHardware function = new VirtualMachineTemplateInVirtualDatacenterToHardware( + vdcToLocation); + + VirtualMachineTemplateDto dto = new VirtualMachineTemplateDto(); + dto.setId(5); + dto.setName("Template"); + dto.setDescription("Template description"); + dto.setHdRequired(50L * 1024 * 1024 * 1024); // 50 GB + dto.setCpuRequired(5); + VirtualMachineTemplate template = wrap(context, VirtualMachineTemplate.class, dto); + + VirtualDatacenterDto vdcDto = new VirtualDatacenterDto(); + vdcDto.setId(6); + vdcDto.setHypervisorType(HypervisorType.VMX_04); + VirtualDatacenter vdc = wrap(context, VirtualDatacenter.class, vdcDto); + + Hardware hardware = function.apply(new VirtualMachineTemplateInVirtualDatacenter(template, vdc)); + + verify(vdcToLocation); + + assertEquals(hardware.getRam(), 0); + } + + @SuppressWarnings("unchecked") + public void testConvertWithoutHd() { + RestContext context = EasyMock.createMock(RestContext.class); + Function vdcToLocation = mockVirtualDatacenterToLocation(); + VirtualMachineTemplateInVirtualDatacenterToHardware function = new VirtualMachineTemplateInVirtualDatacenterToHardware( + vdcToLocation); + + // VirtualMachineTemplate domain object does not have a builder, it is + // read only + VirtualMachineTemplateDto dto = new VirtualMachineTemplateDto(); + dto.setId(5); + dto.setName("Template"); + dto.setDescription("Template description"); + dto.setCpuRequired(5); + dto.setRamRequired(2048); + VirtualMachineTemplate template = wrap(context, VirtualMachineTemplate.class, dto); + + VirtualDatacenterDto vdcDto = new VirtualDatacenterDto(); + vdcDto.setId(6); + vdcDto.setHypervisorType(HypervisorType.VMX_04); + VirtualDatacenter vdc = wrap(context, VirtualDatacenter.class, vdcDto); + + Hardware hardware = function.apply(new VirtualMachineTemplateInVirtualDatacenter(template, vdc)); + + verify(vdcToLocation); + + assertEquals(hardware.getVolumes().size(), 1); + assertEquals(hardware.getVolumes().get(0).getSize(), 0F); + } + + @SuppressWarnings("unchecked") + private static Function mockVirtualDatacenterToLocation() { + Function mock = EasyMock.createMock(Function.class); + expect(mock.apply(anyObject(VirtualDatacenter.class))).andReturn(null); + replay(mock); + return mock; + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/compute/functions/VirtualMachineTemplateToImageTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/compute/functions/VirtualMachineTemplateToImageTest.java new file mode 100644 index 0000000000..8ca7319609 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/compute/functions/VirtualMachineTemplateToImageTest.java @@ -0,0 +1,131 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.compute.functions; + +import static org.easymock.EasyMock.anyObject; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; +import static org.jclouds.abiquo.domain.DomainWrapper.wrap; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNull; + +import java.net.URI; +import java.util.Collections; +import java.util.Map; + +import org.easymock.EasyMock; +import org.jclouds.abiquo.AbiquoApi; +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.domain.cloud.VirtualMachineTemplate; +import org.jclouds.abiquo.domain.infrastructure.Datacenter; +import org.jclouds.compute.domain.Image; +import org.jclouds.compute.domain.OperatingSystem; +import org.jclouds.domain.Location; +import org.jclouds.rest.RestContext; +import org.testng.annotations.Test; + +import com.abiquo.model.rest.RESTLink; +import com.abiquo.server.core.appslibrary.VirtualMachineTemplateDto; +import com.google.common.base.Function; +import com.google.common.base.Supplier; + +/** + * Unit tests for the {@link VirtualMachineTemplateToImage} class. + * + * @author Ignasi Barrera + */ +@Test(groups = "unit", testName = "VirtualMachineTemplateToImageTest") +public class VirtualMachineTemplateToImageTest { + @SuppressWarnings("unchecked") + public void testVirtualMachineTemplateToImage() { + RestContext context = EasyMock.createMock(RestContext.class); + Function dcToLocation = mockDatacenterToLocation(); + Supplier> regionMap = mockRegionMap(); + VirtualMachineTemplateToImage function = new VirtualMachineTemplateToImage(dcToLocation, regionMap); + + VirtualMachineTemplateDto dto = new VirtualMachineTemplateDto(); + dto.setId(5); + dto.setName("Template"); + dto.setDescription("Template description"); + dto.addLink(new RESTLink("diskfile", "http://foo/bar")); + dto.addLink(new RESTLink("datacenter", "http://foo/bar/4")); + + Image image = function.apply(wrap(context, VirtualMachineTemplate.class, dto)); + + verify(regionMap); + verify(dcToLocation); + + assertEquals(image.getId(), dto.getId().toString()); + assertEquals(image.getName(), dto.getName()); + assertEquals(image.getDescription(), dto.getDescription()); + assertEquals(image.getUri(), URI.create("http://foo/bar")); + assertEquals(image.getOperatingSystem(), OperatingSystem.builder().description(dto.getName()).build()); + } + + @SuppressWarnings("unchecked") + public void testConvertWithoutDownloadLink() { + RestContext context = EasyMock.createMock(RestContext.class); + Function dcToLocation = mockDatacenterToLocation(); + Supplier> regionMap = mockRegionMap(); + VirtualMachineTemplateToImage function = new VirtualMachineTemplateToImage(dcToLocation, regionMap); + + VirtualMachineTemplateDto dto = new VirtualMachineTemplateDto(); + dto.setId(5); + dto.setName("Template"); + dto.setDescription("Template description"); + dto.addLink(new RESTLink("datacenter", "http://foo/bar/4")); + + Image image = function.apply(wrap(context, VirtualMachineTemplate.class, dto)); + + verify(regionMap); + verify(dcToLocation); + + assertNull(image.getUri()); + } + + @SuppressWarnings("unchecked") + @Test(expectedExceptions = NullPointerException.class) + public void testConvertWithoutId() { + RestContext context = EasyMock.createMock(RestContext.class); + Function dcToLocation = mockDatacenterToLocation(); + Supplier> regionMap = mockRegionMap(); + VirtualMachineTemplateToImage function = new VirtualMachineTemplateToImage(dcToLocation, regionMap); + + VirtualMachineTemplateDto dto = new VirtualMachineTemplateDto(); + function.apply(wrap(context, VirtualMachineTemplate.class, dto)); + } + + @SuppressWarnings("unchecked") + private static Function mockDatacenterToLocation() { + Function mock = EasyMock.createMock(Function.class); + expect(mock.apply(anyObject(Datacenter.class))).andReturn(null); + replay(mock); + return mock; + } + + @SuppressWarnings("unchecked") + private static Supplier> mockRegionMap() { + Supplier> mock = EasyMock.createMock(Supplier.class); + expect(mock.get()).andReturn(Collections.EMPTY_MAP); + replay(mock); + return mock; + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/compute/functions/VirtualMachineToNodeMetadataTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/compute/functions/VirtualMachineToNodeMetadataTest.java new file mode 100644 index 0000000000..0a24831924 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/compute/functions/VirtualMachineToNodeMetadataTest.java @@ -0,0 +1,223 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.compute.functions; + +import static org.easymock.EasyMock.anyObject; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; +import static org.jclouds.abiquo.domain.DomainWrapper.wrap; +import static org.testng.Assert.assertEquals; + +import java.net.URI; + +import org.easymock.EasyMock; +import org.jclouds.abiquo.domain.cloud.VirtualAppliance; +import org.jclouds.abiquo.domain.cloud.VirtualDatacenter; +import org.jclouds.abiquo.domain.cloud.VirtualMachine; +import org.jclouds.abiquo.domain.cloud.VirtualMachineTemplate; +import org.jclouds.abiquo.domain.cloud.VirtualMachineTemplateInVirtualDatacenter; +import org.jclouds.abiquo.domain.network.ExternalIp; +import org.jclouds.abiquo.domain.network.Ip; +import org.jclouds.abiquo.domain.network.PrivateIp; +import org.jclouds.abiquo.domain.network.PublicIp; +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.NodeMetadata.Status; +import org.jclouds.domain.Location; +import org.jclouds.rest.RestContext; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import com.abiquo.model.enumerator.HypervisorType; +import com.abiquo.model.rest.RESTLink; +import com.abiquo.server.core.cloud.VirtualMachineState; +import com.abiquo.server.core.cloud.VirtualMachineWithNodeExtendedDto; +import com.abiquo.server.core.infrastructure.network.ExternalIpDto; +import com.abiquo.server.core.infrastructure.network.PrivateIpDto; +import com.abiquo.server.core.infrastructure.network.PublicIpDto; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Iterables; + +/** + * Unit tests for the {@link VirtualMachineToNodeMetadata} class. + * + * @author Ignasi Barrera + */ +@Test(groups = "unit", testName = "VirtualMachineToNodeMetadataTest") +public class VirtualMachineToNodeMetadataTest { + private VirtualMachineToNodeMetadata function; + + private VirtualMachineWithNodeExtendedDto vm; + + private PrivateIpDto privNic; + + private PublicIpDto pubNic; + + private ExternalIpDto extNic; + + private Hardware hardware; + + @BeforeMethod + public void setup() { + vm = new VirtualMachineWithNodeExtendedDto(); + vm.setNodeName("VM"); + vm.setName("Internal name"); + vm.setId(5); + vm.setVdrpPort(22); + vm.setRam(2048); + vm.setCpu(2); + vm.setState(VirtualMachineState.ON); + vm.addLink(new RESTLink("edit", "http://foo/bar")); + + privNic = new PrivateIpDto(); + privNic.setIp("192.168.1.2"); + privNic.setMac("2a:6e:40:69:84:e0"); + + pubNic = new PublicIpDto(); + pubNic.setIp("80.80.80.80"); + pubNic.setMac("2a:6e:40:69:84:e1"); + + extNic = new ExternalIpDto(); + extNic.setIp("10.10.10.10"); + extNic.setMac("2a:6e:40:69:84:e2"); + + hardware = new HardwareBuilder() // + .ids("1") // + .build(); + + function = new VirtualMachineToNodeMetadata(templateToImage(), templateToHardware(), stateToNodeState(), + virtualDatacenterToLocation()); + } + + public void testVirtualMachineToNodeMetadata() { + VirtualAppliance vapp = EasyMock.createMock(VirtualAppliance.class); + VirtualMachine mockVm = mockVirtualMachine(vapp); + + NodeMetadata node = function.apply(mockVm); + + verify(mockVm); + + assertEquals(node.getId(), vm.getId().toString()); + assertEquals(node.getUri(), URI.create("http://foo/bar")); + assertEquals(node.getName(), vm.getNodeName()); + assertEquals(node.getGroup(), "VAPP"); + assertEquals(node.getLocation().getId(), "1"); + assertEquals(node.getLocation().getDescription(), "Mock Location"); + assertEquals(node.getImageId(), "1"); + assertEquals(node.getHardware().getId(), "1"); + assertEquals(node.getHardware().getRam(), vm.getRam()); + assertEquals(node.getHardware().getProcessors().get(0).getCores(), (double) vm.getCpu()); + assertEquals(node.getLoginPort(), vm.getVdrpPort()); + assertEquals(node.getPrivateAddresses().size(), 1); + assertEquals(node.getPublicAddresses().size(), 2); + assertEquals(Iterables.get(node.getPrivateAddresses(), 0), privNic.getIp()); + assertEquals(Iterables.get(node.getPublicAddresses(), 0), pubNic.getIp()); + assertEquals(Iterables.get(node.getPublicAddresses(), 1), extNic.getIp()); + } + + private VirtualMachineTemplateToImage templateToImage() { + VirtualMachineTemplateToImage templateToImage = EasyMock.createMock(VirtualMachineTemplateToImage.class); + Image image = EasyMock.createMock(Image.class); + + expect(image.getId()).andReturn("1"); + expect(image.getOperatingSystem()).andReturn(null); + expect(templateToImage.apply(anyObject(VirtualMachineTemplate.class))).andReturn(image); + + replay(image); + replay(templateToImage); + + return templateToImage; + } + + private VirtualMachineTemplateInVirtualDatacenterToHardware templateToHardware() { + VirtualMachineTemplateInVirtualDatacenterToHardware virtualMachineTemplateToHardware = EasyMock + .createMock(VirtualMachineTemplateInVirtualDatacenterToHardware.class); + + expect(virtualMachineTemplateToHardware.apply(anyObject(VirtualMachineTemplateInVirtualDatacenter.class))) + .andReturn(hardware); + + replay(virtualMachineTemplateToHardware); + + return virtualMachineTemplateToHardware; + } + + private VirtualDatacenterToLocation virtualDatacenterToLocation() { + VirtualDatacenterToLocation datacenterToLocation = EasyMock.createMock(VirtualDatacenterToLocation.class); + Location location = EasyMock.createMock(Location.class); + + expect(location.getId()).andReturn("1"); + expect(location.getDescription()).andReturn("Mock Location"); + + expect(datacenterToLocation.apply(anyObject(VirtualDatacenter.class))).andReturn(location); + + replay(location); + replay(datacenterToLocation); + + return datacenterToLocation; + } + + private VirtualMachineStateToNodeState stateToNodeState() { + VirtualMachineStateToNodeState stateToNodeState = EasyMock.createMock(VirtualMachineStateToNodeState.class); + expect(stateToNodeState.apply(anyObject(VirtualMachineState.class))).andReturn(Status.RUNNING); + replay(stateToNodeState); + return stateToNodeState; + } + + private VirtualDatacenter mockVirtualDatacenter() { + VirtualDatacenter vdc = EasyMock.createMock(VirtualDatacenter.class); + expect(vdc.getHypervisorType()).andReturn(HypervisorType.VMX_04); + expect(vdc.getDatacenter()).andReturn(null); + replay(vdc); + return vdc; + } + + private VirtualMachineTemplate mockTemplate() { + return EasyMock.createMock(VirtualMachineTemplate.class); + } + + @SuppressWarnings("unchecked") + private VirtualMachine mockVirtualMachine(final VirtualAppliance vapp) { + VirtualMachine mockVm = EasyMock.createMock(VirtualMachine.class); + + Ip mockPrivNic = wrap(EasyMock.createMock(RestContext.class), PrivateIp.class, privNic); + Ip mockPubNic = wrap(EasyMock.createMock(RestContext.class), PublicIp.class, pubNic); + Ip mockExtNic = wrap(EasyMock.createMock(RestContext.class), ExternalIp.class, extNic); + + expect(mockVm.getId()).andReturn(vm.getId()); + expect(mockVm.getURI()).andReturn(URI.create(vm.getEditLink().getHref())); + expect(mockVm.getNameLabel()).andReturn(vm.getNodeName()); + expect(mockVm.getTemplate()).andReturn(mockTemplate()); + expect(mockVm.getState()).andReturn(vm.getState()); + expect(mockVm.listAttachedNics()).andReturn(ImmutableList.> of(mockPubNic, mockPrivNic, mockExtNic)); + expect(mockVm.getVirtualAppliance()).andReturn(vapp); + expect(vapp.getName()).andReturn("VAPP"); + expect(mockVm.getVirtualDatacenter()).andReturn(mockVirtualDatacenter()); + expect(mockVm.getRam()).andReturn(vm.getRam()); + expect(mockVm.getCpu()).andReturn(vm.getCpu()); + + replay(mockVm); + replay(vapp); + + return mockVm; + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/compute/options/AbiquoTemplateOptionsTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/compute/options/AbiquoTemplateOptionsTest.java new file mode 100644 index 0000000000..13b3064b9c --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/compute/options/AbiquoTemplateOptionsTest.java @@ -0,0 +1,54 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.compute.options; + +import static org.testng.Assert.assertEquals; + +import org.jclouds.compute.options.TemplateOptions; +import org.testng.annotations.Test; + +/** + * Unit tests for the {@link AbiquoTemplateOptions} class. + * + * @author Ignasi Barrera + */ +@Test(groups = "unit", testName = "AbiquoTemplateOptionsTest") +public class AbiquoTemplateOptionsTest { + public void testAs() { + TemplateOptions options = new AbiquoTemplateOptions(); + assertEquals(options.as(AbiquoTemplateOptions.class), options); + } + + public void testOverrideCores() { + TemplateOptions options = new AbiquoTemplateOptions().overrideCores(5); + assertEquals(options.as(AbiquoTemplateOptions.class).getOverrideCores(), Integer.valueOf(5)); + } + + public void testOverrideRam() { + TemplateOptions options = new AbiquoTemplateOptions().overrideRam(2048); + assertEquals(options.as(AbiquoTemplateOptions.class).getOverrideRam(), Integer.valueOf(2048)); + } + + public void testVncPassword() { + TemplateOptions options = new AbiquoTemplateOptions().vncPassword("foo"); + assertEquals(options.as(AbiquoTemplateOptions.class).getVncPassword(), "foo"); + } + +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/config/SchedulerModuleTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/config/SchedulerModuleTest.java new file mode 100644 index 0000000000..1f160b4b25 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/config/SchedulerModuleTest.java @@ -0,0 +1,44 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.config; + +import static org.testng.Assert.assertNotNull; + +import java.util.concurrent.ScheduledExecutorService; + +import org.jclouds.Constants; +import org.jclouds.abiquo.internal.BaseInjectionTest; +import org.testng.annotations.Test; + +import com.google.inject.Key; +import com.google.inject.name.Names; + +/** + * Unit tests for the {@link SchedulerModule} class. + * + * @author Ignasi Barrera + */ +@Test(groups = "unit", testName = "SchedulerModuleTest") +public class SchedulerModuleTest extends BaseInjectionTest { + public void testScheduledExecutorIsProvided() { + assertNotNull(injector.getInstance(Key.get(ScheduledExecutorService.class, + Names.named(Constants.PROPERTY_SCHEDULER_THREADS)))); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/AbiquoVersionLiveApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/AbiquoVersionLiveApiTest.java new file mode 100644 index 0000000000..1998ab483d --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/AbiquoVersionLiveApiTest.java @@ -0,0 +1,55 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain; + +import static org.jclouds.abiquo.util.Assert.assertHasError; +import static org.testng.Assert.fail; + +import java.util.Properties; + +import javax.ws.rs.core.Response.Status; + +import org.jclouds.abiquo.domain.exception.AbiquoException; +import org.jclouds.abiquo.internal.BaseAbiquoLiveApiTest; +import org.testng.annotations.Test; + +/** + * Live integration tests for the Abiquo versioning support. + * + * @author Francesc Montserrat + */ +@Test(groups = "api", testName = "AbiquoVersionLiveApiTest") +public class AbiquoVersionLiveApiTest extends BaseAbiquoLiveApiTest { + @Override + protected Properties setupProperties() { + Properties overrides = super.setupProperties(); + overrides.setProperty("abiquo.api-version", "0.0"); + return overrides; + } + + public void testUnsupportedVersion() { + try { + view.getAdministrationService().getCurrentUser(); + fail("Unsupported versions in mime types should not be allowed"); + } catch (AbiquoException ex) { + assertHasError(ex, Status.NOT_ACCEPTABLE, "406-NOT-ACCEPTABLE"); + } + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/AdminResources.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/AdminResources.java new file mode 100644 index 0000000000..5406ab4db1 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/AdminResources.java @@ -0,0 +1,200 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain; + +import static org.jclouds.abiquo.domain.DomainUtils.link; + +import com.abiquo.model.rest.RESTLink; +import com.abiquo.server.core.enterprise.DatacenterLimitsDto; +import com.abiquo.server.core.enterprise.EnterpriseDto; +import com.abiquo.server.core.enterprise.RoleDto; +import com.abiquo.server.core.enterprise.UserDto; + +/** + * Enterprise domain utilities. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +public class AdminResources { + public static RoleDto rolePost() { + RoleDto role = new RoleDto(); + role.addLink(new RESTLink("privileges", "http://localhost/api/admin/roles/1/action/privileges")); + role.setName("HAWAIAN_ADMIN"); + return role; + } + + public static RoleDto rolePut() { + RoleDto role = rolePost(); + role.setId(1); + role.addLink(new RESTLink("edit", "http://localhost/api/admin/roles/1")); + + return role; + } + + public static String rolePostPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append(link("/admin/roles/1/action/privileges", "privileges")); + buffer.append("false"); + buffer.append("HAWAIAN_ADMIN"); + buffer.append(""); + return buffer.toString(); + } + + public static String rolePutPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append(link("/admin/roles/1/action/privileges", "privileges")); + buffer.append(link("/admin/roles/1", "edit")); + buffer.append("false"); + buffer.append("1"); + buffer.append("HAWAIAN_ADMIN"); + buffer.append(""); + return buffer.toString(); + } + + public static DatacenterLimitsDto datacenterLimitsPost() { + DatacenterLimitsDto limits = new DatacenterLimitsDto(); + limits.setCpuCountLimits(0, 0); + limits.setHdLimitsInMb(0, 0); + limits.setPublicIPLimits(0, 0); + limits.setRamLimitsInMb(0, 0); + limits.setStorageLimits(0, 0); + limits.setVlansLimits(0, 0); + limits.setRepositoryHardLimitsInMb(0); + limits.setRepositorySoftLimitsInMb(0); + return limits; + } + + public static DatacenterLimitsDto datacenterLimitsPut(final EnterpriseDto enterprise) { + DatacenterLimitsDto limits = datacenterLimitsPost(); + limits.setId(1); + limits.addLink(new RESTLink("edit", "http://localhost/api/admin/enterprises/" + enterprise.getId() + "/limits/1")); + return limits; + } + + public static String datacenterLimitsPostPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append(""); + return buffer.toString(); + } + + public static String datacenterLimitsPutPayload(final EnterpriseDto enterprise) { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append(link("/admin/enterprises/" + enterprise.getId() + "/limits/1", "edit")); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("1"); + buffer.append("0"); + buffer.append("0"); + buffer.append(""); + return buffer.toString(); + } + + public static String userPostPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append(link("/admin/roles/1", "role")); + buffer.append("true"); + buffer.append("ABIQUO"); + buffer.append("A hawaian user"); + buffer.append("abe.joha@aloha.com"); + buffer.append("en_US"); + buffer.append("Aberahama"); + buffer.append("abejo"); + buffer.append("c69a39bd64ffb77ea7ee3369dce742f3"); + buffer.append("Johanson"); + buffer.append(""); + return buffer.toString(); + } + + public static UserDto userPost() { + UserDto user = new UserDto(); + user.setName("Aberahama"); + user.setSurname("Johanson"); + user.setDescription("A hawaian user"); + user.setEmail("abe.joha@aloha.com"); + user.setNick("abejo"); + user.setAuthType("ABIQUO"); + user.setLocale("en_US"); + user.setActive(true); + user.setPassword("c69a39bd64ffb77ea7ee3369dce742f3"); + user.addLink(new RESTLink("role", "http://localhost/api/admin/roles/1")); + return user; + } + + public static String userPutPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append(link("/admin/roles/1", "role")); + buffer.append(link("/admin/enterprises/1/users/1", "edit")); + buffer.append(link("/admin/enterprises/1", "enterprise")); + buffer.append(link("/admin/enterprises/1/users/1/action/virtualmachines", "virtualmachines")); + buffer.append("true"); + buffer.append("ABIQUO"); + buffer.append("A hawaian user"); + buffer.append("abe.joha@aloha.com"); + buffer.append("1"); + buffer.append("en_US"); + buffer.append("Aberahama"); + buffer.append("abejo"); + buffer.append("c69a39bd64ffb77ea7ee3369dce742f3"); + buffer.append("Johanson"); + buffer.append(""); + return buffer.toString(); + } + + public static UserDto userPut() { + UserDto user = userPost(); + user.setId(1); + user.addLink(new RESTLink("edit", "http://localhost/api/admin/enterprises/1/users/1")); + user.addLink(new RESTLink("enterprise", "http://localhost/api/admin/enterprises/1")); + user.addLink(new RESTLink("virtualmachines", + "http://localhost/api/admin/enterprises/1/users/1/action/virtualmachines")); + return user; + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/CloudResources.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/CloudResources.java new file mode 100644 index 0000000000..6038649620 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/CloudResources.java @@ -0,0 +1,455 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain; + +import static org.jclouds.abiquo.domain.DomainUtils.link; + +import com.abiquo.model.enumerator.DiskFormatType; +import com.abiquo.model.enumerator.HypervisorType; +import com.abiquo.model.enumerator.VolumeState; +import com.abiquo.model.rest.RESTLink; +import com.abiquo.server.core.appslibrary.VirtualMachineTemplateDto; +import com.abiquo.server.core.cloud.VirtualApplianceDto; +import com.abiquo.server.core.cloud.VirtualDatacenterDto; +import com.abiquo.server.core.cloud.VirtualMachineDto; +import com.abiquo.server.core.cloud.VirtualMachineState; +import com.abiquo.server.core.cloud.VirtualMachineStateDto; +import com.abiquo.server.core.cloud.VirtualMachineTaskDto; +import com.abiquo.server.core.infrastructure.storage.DiskManagementDto; +import com.abiquo.server.core.infrastructure.storage.TierDto; +import com.abiquo.server.core.infrastructure.storage.VolumeManagementDto; + +/** + * Cloud domain utilities. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +public class CloudResources { + public static VirtualDatacenterDto virtualDatacenterPost() { + VirtualDatacenterDto virtualDatacenter = new VirtualDatacenterDto(); + virtualDatacenter.setName("VDC"); + virtualDatacenter.setHypervisorType(HypervisorType.KVM); + virtualDatacenter.setVlan(NetworkResources.vlanPost()); + return virtualDatacenter; + } + + public static VirtualApplianceDto virtualAppliancePost() { + VirtualApplianceDto virtualAppliance = new VirtualApplianceDto(); + virtualAppliance.setName("VA"); + return virtualAppliance; + } + + public static VirtualMachineDto virtualMachinePost() { + VirtualMachineDto virtualMachine = new VirtualMachineDto(); + virtualMachine.setName("VM"); + return virtualMachine; + } + + public static VirtualDatacenterDto virtualDatacenterPut() { + VirtualDatacenterDto virtualDatacenter = virtualDatacenterPost(); + virtualDatacenter.setId(1); + virtualDatacenter.addLink(new RESTLink("datacenter", "http://localhost/api/admin/datacenters/1")); + virtualDatacenter.addLink(new RESTLink("disks", "http://localhost/api/cloud/virtualdatacenters/1/disks")); + virtualDatacenter.addLink(new RESTLink("enterprise", "http://localhost/api/admin/enterprises/1")); + virtualDatacenter.addLink(new RESTLink("edit", "http://localhost/api/cloud/virtualdatacenters/1")); + virtualDatacenter.addLink(new RESTLink("tiers", "http://localhost/api/cloud/virtualdatacenters/1/tiers")); + virtualDatacenter.addLink(new RESTLink("virtualappliances", + "http://localhost/api/cloud/virtualdatacenters/1/virtualappliances")); + virtualDatacenter.addLink(new RESTLink("volumes", "http://localhost/api/cloud/virtualdatacenters/1/volumes")); + virtualDatacenter.addLink(new RESTLink("privatenetworks", + "http://localhost/api/cloud/virtualdatacenters/1/privatenetworks")); + virtualDatacenter.addLink(new RESTLink("defaultnetwork", + "http://localhost/api/cloud/virtualdatacenters/1/privatenetworks/1")); + virtualDatacenter.addLink(new RESTLink("defaultvlan", + "http://localhost/api/cloud/virtualdatacenters/1/action/defaultvlan")); + virtualDatacenter.addLink(new RESTLink("topurchase", + "http://localhost/api/cloud/virtualdatacenters/1/publicips/topurchase")); + virtualDatacenter.addLink(new RESTLink("purchased", + "http://localhost/api/cloud/virtualdatacenters/1/publicips/purchased")); + virtualDatacenter.addLink(new RESTLink("templates", + "http://localhost/api/cloud/virtualdatacenters/1/action/templates")); + return virtualDatacenter; + + } + + public static VirtualApplianceDto virtualAppliancePut() { + VirtualApplianceDto virtualAppliance = virtualAppliancePost(); + virtualAppliance.setId(1); + virtualAppliance.addLink(new RESTLink("virtualdatacenter", "http://localhost/api/cloud/virtualdatacenters/1")); + virtualAppliance.addLink(new RESTLink("deploy", + "http://localhost/api/cloud/virtualdatacenters/1/virtualappliances/1/action/deploy")); + virtualAppliance.addLink(new RESTLink("edit", + "http://localhost/api/cloud/virtualdatacenters/1/virtualappliances/1")); + virtualAppliance.addLink(new RESTLink("state", + "http://localhost/api/cloud/virtualdatacenters/1/virtualappliances/1/state")); + virtualAppliance.addLink(new RESTLink("undeploy", + "http://localhost/api/cloud/virtualdatacenters/1/virtualappliances/1/action/undeploy")); + virtualAppliance.addLink(new RESTLink("virtualmachines", + "http://localhost/api/cloud/virtualdatacenters/1/virtualappliances/1/virtualmachines")); + virtualAppliance.addLink(new RESTLink("price", + "http://localhost/api/cloud/virtualdatacenters/1/virtualappliances/1/action/price")); + return virtualAppliance; + } + + public static VirtualMachineDto virtualMachinePut() { + VirtualMachineDto virtualMachine = virtualMachinePost(); + virtualMachine.setId(1); + virtualMachine.addLink(new RESTLink("deploy", + "http://localhost/api/cloud/virtualdatacenters/1/virtualappliances/1/virtualmachines/1/action/deploy")); + virtualMachine.addLink(new RESTLink("disks", + "http://localhost/api/cloud/virtualdatacenters/1/virtualappliances/1/virtualmachines/1/storage/disks")); + virtualMachine.addLink(new RESTLink("edit", + "http://localhost/api/cloud/virtualdatacenters/1/virtualappliances/1/virtualmachines/1")); + virtualMachine.addLink(new RESTLink("state", + "http://localhost/api/cloud/virtualdatacenters/1/virtualappliances/1/virtualmachines/1/state")); + virtualMachine.addLink(new RESTLink("reset", + "http://localhost/api/cloud/virtualdatacenters/1/virtualappliances/1/virtualmachines/1/action/reset")); + virtualMachine.addLink(new RESTLink("tasks", + "http://localhost/api/cloud/virtualdatacenters/1/virtualappliances/1/virtualmachines/1/tasks")); + virtualMachine.addLink(new RESTLink("undeploy", + "http://localhost/api/cloud/virtualdatacenters/1/virtualappliances/1/virtualmachines/1/action/undeploy")); + virtualMachine.addLink(new RESTLink("persistent", + "http://localhost/api/cloud/virtualdatacenters/1/virtualappliances/1/virtualmachines/1/action/persistent")); + virtualMachine.addLink(new RESTLink("virtualappliance", + "http://localhost/api/cloud/virtualdatacenters/1/virtualappliances/1")); + virtualMachine.addLink(new RESTLink("virtualmachinetemplate", + "http://localhost/api/admin/enterprises/1/datacenterrepositories/1/virtualmachinetemplates/1")); + virtualMachine.addLink(new RESTLink("nics", + "http://localhost/api/cloud/virtualdatacenters/1/virtualappliances/1/virtualmachines/1/network/nics")); + virtualMachine.addLink(new RESTLink("volumes", + "http://localhost/api/cloud/virtualdatacenters/1/virtualappliances/1/virtualmachines/1/storage/volumes")); + virtualMachine + .addLink(new RESTLink("configurations", + "http://localhost/api/cloud/virtualdatacenters/1/virtualappliances/1/virtualmachines/1/network/configurations")); + return virtualMachine; + } + + public static VirtualMachineStateDto virtualMachineState() { + VirtualMachineStateDto state = new VirtualMachineStateDto(); + state.setState(VirtualMachineState.ON); + return state; + } + + public static String virtualMachineStatePayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append("ON"); + buffer.append(""); + return buffer.toString(); + } + + public static VolumeManagementDto volumePost() { + VolumeManagementDto volume = new VolumeManagementDto(); + volume.setName("Volume"); + volume.setSizeInMB(1024); + volume.addLink(new RESTLink("tier", "http://localhost/api/cloud/virtualdatacenters/1/tiers/1")); + return volume; + } + + public static VolumeManagementDto volumePut() { + VolumeManagementDto volume = volumePost(); + volume.setId(1); + volume.setState(VolumeState.DETACHED.name()); + + volume.getLinks().clear(); + + RESTLink mappings = new RESTLink("action", + "http://localhost/api/cloud/virtualdatacenters/1/volumes/1/action/initiatormappings"); + mappings.setTitle("initiator mappings"); + volume.addLink(mappings); + volume.addLink(new RESTLink("edit", "http://localhost/api/cloud/virtualdatacenters/1/volumes/1")); + volume.addLink(new RESTLink("tier", "http://localhost/api/cloud/virtualdatacenters/1/tiers/1")); + volume.addLink(new RESTLink("virtualdatacenter", "http://localhost/api/cloud/virtualdatacenters/1")); + return volume; + } + + public static VirtualMachineTemplateDto virtualMachineTemplatePut() { + VirtualMachineTemplateDto template = new VirtualMachineTemplateDto(); + template.setId(10); + template.setName("m0n0wall"); + template.setDiskFormatType(DiskFormatType.VMDK_FLAT.toString()); + template.setPath("1/abiquo-repository.abiquo.com/m0n0wall/m0n0wall-1.3b18-i386-flat.vmdk"); + template.setDiskFileSize(27262976); + template.setCpuRequired(1); + template.setRamRequired(128); + template.setCpuRequired(27262976); + template.setCreationUser("SYSTEM"); + template.setIconUrl("http://ww1.prweb.com/prfiles/2010/08/02/2823234/gI_0_HakunaLogoMedium.jpg"); + template.addLink(new RESTLink("icon", "http://localhost/api/config/icons/1")); + template.addLink(new RESTLink("category", "http://localhost/api/config/categories/1")); + + return template; + + } + + public static TierDto cloudTierPut() { + TierDto tier = new TierDto(); + tier.setId(1); + tier.setEnabled(true); + tier.setName("Tier"); + tier.addLink(new RESTLink("edit", "http://localhost/api/cloud/virtualdatacenters/1/tiers/1")); + return tier; + } + + public static VirtualMachineTaskDto deployOptions() { + VirtualMachineTaskDto deploy = new VirtualMachineTaskDto(); + deploy.setForceEnterpriseSoftLimits(false); + return deploy; + + } + + public static VirtualMachineTaskDto undeployOptions() { + VirtualMachineTaskDto deploy = new VirtualMachineTaskDto(); + deploy.setForceUndeploy(true); + return deploy; + } + + public static String virtualDatacenterPostPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("KVM"); + buffer.append("VDC"); + buffer.append(NetworkResources.vlanNetworkPostPayload()); + buffer.append(""); + return buffer.toString(); + } + + public static String virtualAppliancePostPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append("0"); + buffer.append("0"); + buffer.append("VA"); + buffer.append("0"); + buffer.append(""); + return buffer.toString(); + } + + public static String virtualMachinePostPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("VM"); + buffer.append("0"); + buffer.append("0"); + buffer.append(""); + return buffer.toString(); + } + + public static String virtualDatacenterPutPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append(link("/admin/datacenters/1", "datacenter")); + buffer.append(link("/cloud/virtualdatacenters/1/disks", "disks")); + buffer.append(link("/admin/enterprises/1", "enterprise")); + buffer.append(link("/cloud/virtualdatacenters/1", "edit")); + buffer.append(link("/cloud/virtualdatacenters/1/tiers", "tiers")); + buffer.append(link("/cloud/virtualdatacenters/1/virtualappliances", "virtualappliances")); + buffer.append(link("/cloud/virtualdatacenters/1/volumes", "volumes")); + buffer.append(link("/cloud/virtualdatacenters/1/privatenetworks", "privatenetworks")); + buffer.append(link("/cloud/virtualdatacenters/1/privatenetworks/1", "defaultnetwork")); + buffer.append(link("/cloud/virtualdatacenters/1/action/defaultvlan", "defaultvlan")); + buffer.append(link("/cloud/virtualdatacenters/1/publicips/topurchase", "topurchase")); + buffer.append(link("/cloud/virtualdatacenters/1/publicips/purchased", "purchased")); + buffer.append(link("/cloud/virtualdatacenters/1/action/templates", "templates")); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("KVM"); + buffer.append("1"); + buffer.append("VDC"); + buffer.append(NetworkResources.vlanNetworkPostPayload()); + buffer.append(""); + return buffer.toString(); + } + + public static String virtualDatacenterRefPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append(link("/cloud/virtualdatacenters/1", "virtualdatacenter")); + buffer.append(""); + return buffer.toString(); + } + + public static String virtualAppliancePutPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append(link("/cloud/virtualdatacenters/1", "virtualdatacenter")); + buffer.append(link("/cloud/virtualdatacenters/1/virtualappliances/1/action/deploy", "deploy")); + buffer.append(link("/cloud/virtualdatacenters/1/virtualappliances/1", "edit")); + buffer.append(link("/cloud/virtualdatacenters/1/virtualappliances/1/state", "state")); + buffer.append(link("/cloud/virtualdatacenters/1/virtualappliances/1/action/undeploy", "undeploy")); + buffer.append(link("/cloud/virtualdatacenters/1/virtualappliances/1/virtualmachines", "virtualmachines")); + buffer.append(link("/cloud/virtualdatacenters/1/virtualappliances/1/action/price", "price")); + buffer.append("0"); + buffer.append("0"); + buffer.append("1"); + buffer.append("VA"); + buffer.append("0"); + buffer.append(""); + return buffer.toString(); + } + + public static String virtualMachinePutPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append(link("/cloud/virtualdatacenters/1/virtualappliances/1/virtualmachines/1/action/deploy", "deploy")); + buffer.append(link("/cloud/virtualdatacenters/1/virtualappliances/1/virtualmachines/1/storage/disks", "disks")); + buffer.append(link("/cloud/virtualdatacenters/1/virtualappliances/1/virtualmachines/1", "edit")); + buffer.append(link("/cloud/virtualdatacenters/1/virtualappliances/1/virtualmachines/1/state", "state")); + buffer.append(link("/cloud/virtualdatacenters/1/virtualappliances/1/virtualmachines/1/action/reset", "reset")); + buffer.append(link("/cloud/virtualdatacenters/1/virtualappliances/1/virtualmachines/1/tasks", "tasks")); + buffer.append(link("/cloud/virtualdatacenters/1/virtualappliances/1/virtualmachines/1/action/undeploy", + "undeploy")); + buffer.append(link("/cloud/virtualdatacenters/1/virtualappliances/1/virtualmachines/1/action/persistent", + "persistent")); + buffer.append(link("/cloud/virtualdatacenters/1/virtualappliances/1", "virtualappliance")); + buffer.append(link("/admin/enterprises/1/datacenterrepositories/1/virtualmachinetemplates/1", + "virtualmachinetemplate")); + buffer.append(link("/cloud/virtualdatacenters/1/virtualappliances/1/virtualmachines/1/network/nics", "nics")); + buffer.append(link("/cloud/virtualdatacenters/1/virtualappliances/1/virtualmachines/1/storage/volumes", "volumes")); + buffer.append(link("/cloud/virtualdatacenters/1/virtualappliances/1/virtualmachines/1/network/configurations", + "configurations")); + + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("1"); + buffer.append("0"); + buffer.append("0"); + buffer.append("VM"); + buffer.append("0"); + buffer.append("0"); + buffer.append(""); + return buffer.toString(); + } + + public static String volumePostPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append(link("/cloud/virtualdatacenters/1/tiers/1", "tier")); + buffer.append("Volume"); + buffer.append("1024"); + buffer.append(""); + return buffer.toString(); + } + + public static String volumePutPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append(link("/cloud/virtualdatacenters/1/volumes/1/action/initiatormappings", "action", + "initiator mappings")); + buffer.append(link("/cloud/virtualdatacenters/1/volumes/1", "edit")); + buffer.append(link("/cloud/virtualdatacenters/1/tiers/1", "tier")); + buffer.append(link("/cloud/virtualdatacenters/1", "virtualdatacenter")); + buffer.append("1"); + buffer.append("Volume"); + buffer.append("DETACHED"); + buffer.append("1024"); + buffer.append(""); + return buffer.toString(); + } + + public static String cloudTierPutPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append(link("/cloud/virtualdatacenters/1/tiers/1", "edit")); + buffer.append("true"); + buffer.append("1"); + buffer.append("Tier"); + buffer.append(""); + return buffer.toString(); + } + + public static String deployPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append("false"); + buffer.append(""); + return buffer.toString(); + } + + public static String undeployPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append("false"); + buffer.append("true"); + buffer.append(""); + return buffer.toString(); + } + + public static DiskManagementDto hardDiskPost() { + DiskManagementDto disk = new DiskManagementDto(); + disk.setSizeInMb(1024L); + return disk; + } + + public static DiskManagementDto hardDiskPut() { + DiskManagementDto disk = hardDiskPost(); + disk.addLink(new RESTLink("edit", "http://localhost/api/cloud/virtualdatacenters/1/disks/1")); + disk.addLink(new RESTLink("virtualdatacenter", "http://localhost/api/cloud/virtualdatacenters/1")); + return disk; + } + + public static String hardDiskPostPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append("1024"); + buffer.append(""); + return buffer.toString(); + } + + public static String hardDiskPutPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append(link("/cloud/virtualdatacenters/1", "virtualdatacenter")); + buffer.append(link("/cloud/virtualdatacenters/1/disks/1", "edit")); + buffer.append("0"); + buffer.append("1024"); + buffer.append(""); + return buffer.toString(); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/ConfigResources.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/ConfigResources.java new file mode 100644 index 0000000000..9c07bbcca3 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/ConfigResources.java @@ -0,0 +1,164 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain; + +import static org.jclouds.abiquo.domain.DomainUtils.link; + +import java.io.IOException; +import java.net.URL; +import java.nio.charset.Charset; + +import com.abiquo.model.rest.RESTLink; +import com.abiquo.server.core.appslibrary.CategoryDto; +import com.abiquo.server.core.config.LicenseDto; +import com.abiquo.server.core.config.SystemPropertyDto; +import com.google.common.io.Resources; + +/** + * Enterprise domain utilities. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +public class ConfigResources { + public static LicenseDto licensePost() { + LicenseDto license = new LicenseDto(); + license.setCode(readLicense("license/expired")); + license.setCustomerid("3bca6d1d-5fe2-42c5-82ea-a5276ea8c71c"); + return license; + } + + public static CategoryDto categoryPost() { + CategoryDto category = new CategoryDto(); + category.setName("category"); + category.setErasable(false); + category.setDefaultCategory(false); + return category; + } + + public static CategoryDto categoryPut() { + CategoryDto category = categoryPost(); + category.setId(1); + category.addLink(new RESTLink("edit", "http://localhost/api/config/categories/1")); + return category; + } + + public static LicenseDto licensePut() { + LicenseDto license = licensePost(); + license.setId(1); + license.addLink(new RESTLink("edit", "http://localhost/api/config/licenses/1")); + + return license; + } + + public static SystemPropertyDto propertyPut() { + SystemPropertyDto property = new SystemPropertyDto(); + property.setId(1); + property.setDescription("Time interval in seconds"); + property.setValue("10"); + property.setName("api.applibrary.ovfpackagesDownloadingProgressUpdateInterval"); + property.addLink(new RESTLink("edit", "http://localhost/api/config/properties/1")); + + return property; + } + + public static String licensePutPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append(link("/admin/enterprises/config/licenses/1", "edit")); + buffer.append("3bca6d1d-5fe2-42c5-82ea-a5276ea8c71c"); + buffer.append("" + readLicense("license/expired") + ""); + buffer.append("1"); + buffer.append(""); + return buffer.toString(); + } + + public static String licensePostPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append("3bca6d1d-5fe2-42c5-82ea-a5276ea8c71c"); + buffer.append("" + readLicense("license/expired") + ""); + buffer.append(""); + return buffer.toString(); + } + + public static String categoryPostPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append("false"); + buffer.append("false"); + buffer.append("category"); + buffer.append(""); + return buffer.toString(); + } + + public static String categoryPutPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append(link("/config/categories/1", "edit")); + buffer.append("false"); + buffer.append("false"); + buffer.append("1"); + buffer.append("category"); + buffer.append(""); + return buffer.toString(); + } + + public static String iconPutPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append(link("/config/icons/1", "edit")); + buffer.append("1"); + buffer.append("icon"); + buffer.append("http://www.pixeljoint.com/files/icons/mipreview1.gif"); + buffer.append(""); + return buffer.toString(); + } + + public static String iconPostPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append("icon"); + buffer.append("http://www.pixeljoint.com/files/icons/mipreview1.gif"); + buffer.append(""); + return buffer.toString(); + } + + public static String propertyPutPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append(link("/config/properties/1", "edit")); + buffer.append("Time interval in seconds"); + buffer.append("1"); + buffer.append("api.applibrary.ovfpackagesDownloadingProgressUpdateInterval"); + buffer.append("10"); + buffer.append(""); + return buffer.toString(); + } + + private static String readLicense(final String filename) { + URL url = ConfigResources.class.getResource("/" + filename); + try { + return Resources.toString(url, Charset.defaultCharset()); + } catch (IOException e) { + throw new RuntimeException("Could not read file " + filename); + } + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/DomainUtils.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/DomainUtils.java new file mode 100644 index 0000000000..23557553ff --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/DomainUtils.java @@ -0,0 +1,60 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain; + +import org.jclouds.xml.XMLParser; + +import com.abiquo.model.rest.RESTLink; + +/** + * Utility class to build domain objects used in tests. + * + * @author Ignasi Barrera + */ +public class DomainUtils { + /** + * Adds the XML header to the given XML. + */ + public static String withHeader(final String xml) { + return XMLParser.DEFAULT_XML_HEADER + xml; + } + + /** + * Builds a link in xml format + */ + public static String link(final String href, final String rel) { + return ""; + } + + /** + * Builds a link in xml format + */ + public static String link(final String href, final String rel, final String title) { + return ""; + } + + /** + * Builds a link in xml format + */ + public static String link(final RESTLink link) { + return ""; + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/EnterpriseResources.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/EnterpriseResources.java new file mode 100644 index 0000000000..4b32b0aced --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/EnterpriseResources.java @@ -0,0 +1,322 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain; + +import static org.jclouds.abiquo.domain.DomainUtils.link; + +import java.util.HashMap; +import java.util.Map; + +import com.abiquo.model.rest.RESTLink; +import com.abiquo.server.core.appslibrary.TemplateDefinitionListDto; +import com.abiquo.server.core.enterprise.DatacenterLimitsDto; +import com.abiquo.server.core.enterprise.EnterpriseDto; +import com.abiquo.server.core.enterprise.EnterprisePropertiesDto; +import com.abiquo.server.core.enterprise.UserDto; + +/** + * Enterprise domain utilities. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +public class EnterpriseResources { + public static EnterpriseDto enterprisePost() { + EnterpriseDto enterprise = new EnterpriseDto(); + enterprise.setName("Kalakaua"); + return enterprise; + } + + public static EnterpriseDto enterprisePut() { + EnterpriseDto enterprise = enterprisePost(); + enterprise.setId(1); + enterprise.addLink(new RESTLink("edit", "http://localhost/api/admin/enterprises/1")); + enterprise.addLink(new RESTLink("limits", "http://localhost/api/admin/enterprises/1/limits")); + enterprise.addLink(new RESTLink("users", "http://localhost/api/admin/enterprises/1/users")); + enterprise.addLink(new RESTLink("properties", "http://localhost/api/admin/enterprises/1/properties")); + enterprise.addLink(new RESTLink("reservedmachines", "http://localhost/api/admin/enterprises/1/reservedmachines")); + enterprise.addLink(new RESTLink("datacenterrepositories", + "http://localhost/api/admin/enterprises/1/datacenterrepositories")); + enterprise.addLink(new RESTLink("externalnetworks", + "http://localhost/api/admin/enterprises/1/action/externalnetworks")); + enterprise.addLink(new RESTLink("virtualmachines", + "http://localhost/api/admin/enterprises/1/action/virtualmachines")); + enterprise.addLink(new RESTLink("cloud/virtualdatacenters", + "http://localhost/api/admin/enterprises/1/action/virtualdatacenters")); + enterprise.addLink(new RESTLink("virtualappliances", + "http://localhost/api/admin/enterprises/1/action/virtualappliances")); + enterprise.addLink(new RESTLink("appslib/templateDefinitionLists", + "http://localhost/api/admin/enterprises/1/appslib/templateDefinitionLists")); + + return enterprise; + } + + public static EnterprisePropertiesDto enterprisePropertiesPut() { + EnterprisePropertiesDto enterpriseProp = new EnterprisePropertiesDto(); + enterpriseProp.setId(1); + Map props = new HashMap(); + props.put("key", "value"); + enterpriseProp.setProperties(props); + enterpriseProp.addLink(new RESTLink("edit", "http://localhost/api/admin/enterprises/1/properties")); + enterpriseProp.addLink(new RESTLink("enterprise", "http://localhost/api/admin/enterprises/1")); + + return enterpriseProp; + } + + public static String enterprisePostPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("false"); + buffer.append("Kalakaua"); + buffer.append("0"); + buffer.append("0"); + buffer.append(""); + return buffer.toString(); + } + + public static String enterprisePutPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append(link("/admin/enterprises/1", "edit")); + buffer.append(link("/admin/enterprises/1/limits", "limits")); + buffer.append(link("/admin/enterprises/1/users", "users")); + buffer.append(link("/admin/enterprises/1/properties", "properties")); + buffer.append(link("/admin/enterprises/1/reservedmachines", "reservedmachines")); + buffer.append(link("/admin/enterprises/1/datacenterrepositories", "datacenterrepositories")); + buffer.append(link("/admin/enterprises/1/action/externalnetworks", "externalnetworks")); + buffer.append(link("/admin/enterprises/1/action/virtualmachines", "virtualmachines")); + buffer.append(link("/admin/enterprises/1/action/virtualdatacenters", "cloud/virtualdatacenters")); + buffer.append(link("/admin/enterprises/1/action/virtualappliances", "virtualappliances")); + buffer.append(link("/admin/enterprises/1/appslib/templateDefinitionLists", "appslib/templateDefinitionLists")); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("1"); + buffer.append("false"); + buffer.append("Kalakaua"); + buffer.append("0"); + buffer.append("0"); + buffer.append(""); + return buffer.toString(); + } + + public static String enterprisePropertiesPutPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append(link("/admin/enterprises/1/properties", "edit")); + buffer.append(link("/admin/enterprises/1", "enterprise")); + buffer.append("1"); + buffer.append(""); + buffer.append(""); + buffer.append("key"); + buffer.append("value"); + buffer.append(""); + buffer.append(""); + buffer.append(""); + return buffer.toString(); + } + + public static DatacenterLimitsDto datacenterLimitsPost() { + DatacenterLimitsDto limits = new DatacenterLimitsDto(); + limits.setCpuCountLimits(0, 0); + limits.setHdLimitsInMb(0, 0); + limits.setPublicIPLimits(0, 0); + limits.setRamLimitsInMb(0, 0); + limits.setStorageLimits(0, 0); + limits.setVlansLimits(0, 0); + limits.setRepositoryHardLimitsInMb(0); + limits.setRepositorySoftLimitsInMb(0); + return limits; + } + + public static DatacenterLimitsDto datacenterLimitsPut(final EnterpriseDto enterprise) { + DatacenterLimitsDto limits = datacenterLimitsPost(); + limits.setId(1); + limits.addLink(new RESTLink("edit", "http://localhost/api/admin/enterprises/" + enterprise.getId() + "/limits/1")); + return limits; + } + + public static TemplateDefinitionListDto templateListPost() { + TemplateDefinitionListDto templateList = new TemplateDefinitionListDto(); + templateList.setName("myList"); + templateList.setUrl("http://virtualapp-repository.com/vapp1.ovf"); + return templateList; + } + + public static TemplateDefinitionListDto templateListPut() { + TemplateDefinitionListDto templateList = templateListPost(); + templateList.setId(1); + templateList.addLink(new RESTLink("edit", + "http://localhost/api/admin/enterprises/1/appslib/templateDefinitionLists/1")); + templateList.addLink(new RESTLink("repositoryStatus", + "http://localhost/api/admin/enterprises/1/appslib/templateDefinitionLists/1/actions/repositoryStatus")); + return templateList; + } + + public static String datacenterLimitsPostPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append(""); + return buffer.toString(); + } + + public static String templateListPostPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append("myList"); + buffer.append("http://virtualapp-repository.com/vapp1.ovf"); + buffer.append(""); + return buffer.toString(); + } + + public static String templateListPutPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append(link("/admin/enterprises/1/appslib/templateDefinitionLists/1", "edit")); + buffer.append(link("/admin/enterprises/1/appslib/templateDefinitionLists/1/actions/repositoryStatus", + "repositoryStatus")); + buffer.append("1"); + buffer.append("myList"); + buffer.append("http://virtualapp-repository.com/vapp1.ovf"); + buffer.append(""); + return buffer.toString(); + } + + public static String datacenterLimitsPutPayload(final EnterpriseDto enterprise) { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append(link("/admin/enterprises/" + enterprise.getId() + "/limits/1", "edit")); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("1"); + buffer.append("0"); + buffer.append("0"); + buffer.append(""); + return buffer.toString(); + } + + public static String userPostPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append(link("/admin/roles/1", "role")); + buffer.append("true"); + buffer.append("ABIQUO"); + buffer.append("A hawaian user"); + buffer.append("abe.joha@aloha.com"); + buffer.append("en_US"); + buffer.append("Aberahama"); + buffer.append("abejo"); + buffer.append("c69a39bd64ffb77ea7ee3369dce742f3"); + buffer.append("Johanson"); + buffer.append(""); + return buffer.toString(); + } + + public static UserDto userPost() { + UserDto user = new UserDto(); + user.setName("Aberahama"); + user.setSurname("Johanson"); + user.setDescription("A hawaian user"); + user.setEmail("abe.joha@aloha.com"); + user.setNick("abejo"); + user.setAuthType("ABIQUO"); + user.setLocale("en_US"); + user.setActive(true); + user.setPassword("c69a39bd64ffb77ea7ee3369dce742f3"); + user.addLink(new RESTLink("role", "http://localhost/api/admin/roles/1")); + return user; + } + + public static String userPutPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append(link("/admin/roles/1", "role")); + buffer.append(link("/admin/enterprises/1/users/1", "edit")); + buffer.append(link("/admin/enterprises/1", "enterprise")); + buffer.append(link("/admin/enterprises/1/users/1/action/virtualmachines", "virtualmachines")); + buffer.append("true"); + buffer.append("ABIQUO"); + buffer.append("A hawaian user"); + buffer.append("abe.joha@aloha.com"); + buffer.append("1"); + buffer.append("en_US"); + buffer.append("Aberahama"); + buffer.append("abejo"); + buffer.append("c69a39bd64ffb77ea7ee3369dce742f3"); + buffer.append("Johanson"); + buffer.append(""); + return buffer.toString(); + } + + public static UserDto userPut() { + UserDto user = userPost(); + user.setId(1); + user.addLink(new RESTLink("edit", "http://localhost/api/admin/enterprises/1/users/1")); + user.addLink(new RESTLink("enterprise", "http://localhost/api/admin/enterprises/1")); + user.addLink(new RESTLink("virtualmachines", + "http://localhost/api/admin/enterprises/1/users/1/action/virtualmachines")); + return user; + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/InfrastructureResources.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/InfrastructureResources.java new file mode 100644 index 0000000000..07d4f1d436 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/InfrastructureResources.java @@ -0,0 +1,491 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain; + +import static org.jclouds.abiquo.domain.DomainUtils.link; + +import com.abiquo.model.enumerator.RemoteServiceType; +import com.abiquo.model.rest.RESTLink; +import com.abiquo.server.core.infrastructure.DatacenterDto; +import com.abiquo.server.core.infrastructure.LogicServerDto; +import com.abiquo.server.core.infrastructure.MachineDto; +import com.abiquo.server.core.infrastructure.OrganizationDto; +import com.abiquo.server.core.infrastructure.RackDto; +import com.abiquo.server.core.infrastructure.RemoteServiceDto; +import com.abiquo.server.core.infrastructure.UcsRackDto; +import com.abiquo.server.core.infrastructure.storage.StorageDeviceDto; +import com.abiquo.server.core.infrastructure.storage.StoragePoolDto; +import com.abiquo.server.core.infrastructure.storage.TierDto; + +/** + * Infrastructure domain utilities. + * + * @author Ignasi Barrera + */ +public class InfrastructureResources { + public static DatacenterDto datacenterPost() { + DatacenterDto datacenter = new DatacenterDto(); + datacenter.setName("DC"); + datacenter.setLocation("Honolulu"); + return datacenter; + } + + public static RackDto rackPost() { + RackDto rack = new RackDto(); + rack.setName("Aloha"); + rack.setShortDescription("A hawaian rack"); + rack.setHaEnabled(false); + rack.setVlanIdMin(6); + rack.setVlanIdMax(3024); + rack.setVlanPerVdcReserved(6); + rack.setNrsq(80); + return rack; + } + + public static UcsRackDto managedRackPost() { + UcsRackDto rack = new UcsRackDto(); + rack.setName("Aloha"); + rack.setShortDescription("A hawaian rack"); + rack.setHaEnabled(false); + rack.setVlanIdMin(6); + rack.setVlanIdMax(3024); + rack.setVlanPerVdcReserved(6); + rack.setNrsq(80); + return rack; + } + + public static MachineDto machinePost() { + MachineDto machine = new MachineDto(); + machine.setName("Kamehameha"); + machine.setVirtualCpuCores(3); + machine.setDescription("A hawaian machine"); + machine.setVirtualRamInMb(512); + machine.setVirtualSwitch("192.168.1.10"); + return machine; + } + + public static RemoteServiceDto remoteServicePost() { + RemoteServiceDto remoteService = new RemoteServiceDto(); + remoteService.setType(RemoteServiceType.NODE_COLLECTOR); + remoteService.setUri("http://localhost:80/nodecollector"); + remoteService.setStatus(0); + return remoteService; + } + + public static StorageDeviceDto storageDevicePost() { + StorageDeviceDto storage = new StorageDeviceDto(); + storage.setName("Aloha aloha"); + storage.setIscsiIp("10.10.10.10"); + storage.setIscsiPort(99); + storage.setManagementPort(90); + + return storage; + } + + public static StoragePoolDto storagePoolPost() { + StoragePoolDto storagePool = new StoragePoolDto(); + storagePool.setName("Hawaian Storage Pool"); + return storagePool; + } + + public static DatacenterDto datacenterPut() { + DatacenterDto datacenter = datacenterPost(); + datacenter.setId(1); + datacenter.addLink(new RESTLink("checkmachinestate", + "http://localhost/api/admin/datacenters/1/action/checkmachinestate")); + datacenter.addLink(new RESTLink("checkmachineipmistate", + "http://localhost/api/admin/datacenters/1/action/checkmachineipmistate")); + datacenter.addLink(new RESTLink("checkremoteservice", + "http://localhost/api/admin/datacenters/1/action/checkremoteservice")); + datacenter.addLink(new RESTLink("devices", "http://localhost/api/admin/datacenters/1/storage/devices")); + datacenter.addLink(new RESTLink("discovermultiple", + "http://localhost/api/admin/datacenters/1/action/discovermultiple")); + datacenter.addLink(new RESTLink("discoversingle", + "http://localhost/api/admin/datacenters/1/action/discoversingle")); + datacenter.addLink(new RESTLink("edit", "http://localhost/api/admin/datacenters/1")); + datacenter.addLink(new RESTLink("getLimits", "http://localhost/api/admin/datacenters/1/action/getLimits")); + datacenter.addLink(new RESTLink("racks", "http://localhost/api/admin/datacenters/1/racks")); + datacenter.addLink(new RESTLink("remoteservices", "http://localhost/api/admin/datacenters/1/remoteservices")); + datacenter.addLink(new RESTLink("tiers", "http://localhost/api/admin/datacenters/1/storage/tiers")); + datacenter.addLink(new RESTLink("network", "http://localhost/api/admin/datacenters/1/network")); + datacenter.addLink(new RESTLink("enterprises", "http://localhost/api/admin/datacenters/1/action/enterprises")); + datacenter.addLink(new RESTLink("hypervisor", "http://localhost/api/admin/datacenters/1/action/hypervisor")); + datacenter.addLink(new RESTLink("hypervisors", "http://localhost/api/admin/datacenters/1/hypervisors")); + return datacenter; + } + + public static RackDto rackPut() { + RackDto rack = rackPost(); + rack.setId(1); + rack.addLink(new RESTLink("datacenter", "http://localhost/api/admin/datacenters/1")); + rack.addLink(new RESTLink("edit", "http://localhost/api/admin/datacenters/1/racks/1")); + rack.addLink(new RESTLink("machines", "http://localhost/api/admin/datacenters/1/racks/1/machines")); + return rack; + } + + public static UcsRackDto managedRackPut() { + UcsRackDto rack = managedRackPost(); + rack.setId(1); + rack.addLink(new RESTLink("datacenter", "http://localhost/api/admin/datacenters/1")); + rack.addLink(new RESTLink("edit", "http://localhost/api/admin/datacenters/1/racks/1")); + rack.addLink(new RESTLink("fsm", "http://localhost/api/admin/datacenters/1/racks/1/fsm")); + rack.addLink(new RESTLink("logicservers", "http://localhost/api/admin/datacenters/1/racks/1/logicservers")); + rack.addLink(new RESTLink("ls-templates", "http://localhost/api/admin/datacenters/1/racks/1/lstemplates")); + rack.addLink(new RESTLink("organizations", "http://localhost/api/admin/datacenters/1/racks/1/organizations")); + rack.addLink(new RESTLink("ls-associate", + "http://localhost/api/admin/datacenters/1/racks/1/logicservers/associate")); + rack.addLink(new RESTLink("ls-associateclone", + "http://localhost/api/admin/datacenters/1/racks/1/logicservers/assocclone")); + rack.addLink(new RESTLink("ls-associatetemplate", + "http://localhost/api/admin/datacenters/1/racks/1/logicservers/associatetemplate")); + rack.addLink(new RESTLink("ls-clone", "http://localhost/api/admin/datacenters/1/racks/1/logicservers/clone")); + rack.addLink(new RESTLink("ls-delete", "http://localhost/api/admin/datacenters/1/racks/1/logicservers/delete")); + rack.addLink(new RESTLink("ls-dissociate", + "http://localhost/api/admin/datacenters/1/racks/1/logicservers/dissociate")); + return rack; + } + + public static LogicServerDto logicServerPut() { + LogicServerDto logicServer = new LogicServerDto(); + logicServer.setName("server"); + logicServer.setAssociated("associated"); + logicServer.setType("instance"); + + return logicServer; + } + + public static OrganizationDto organizationPut() { + OrganizationDto org = new OrganizationDto(); + org.setName("org"); + org.setDn("org-root/org-Finance"); + org.setLevel("1"); + + return org; + } + + public static TierDto tierPut() { + TierDto tier = new TierDto(); + tier.setId(1); + tier.setEnabled(true); + tier.setName("Tier"); + tier.addLink(new RESTLink("edit", "http://localhost/api/admin/datacenters/1/storage/tiers/1")); + tier.addLink(new RESTLink("datacenter", "http://localhost/api/admin/datacenters/1")); + tier.addLink(new RESTLink("pools", "http://localhost/api/admin/datacenters/1/storage/tiers/1/pools")); + + return tier; + } + + public static StorageDeviceDto storageDevicePut() { + StorageDeviceDto storageDevice = storageDevicePost(); + storageDevice.setId(1); + storageDevice.addLink(new RESTLink("datacenter", "http://localhost/api/admin/datacenters/1")); + storageDevice.addLink(new RESTLink("edit", "http://localhost/api/admin/datacenters/1/storage/devices/1")); + storageDevice.addLink(new RESTLink("pools", "http://localhost/api/admin/datacenters/1/storage/devices/1/pools")); + + return storageDevice; + } + + public static StoragePoolDto storagePoolPut() { + StoragePoolDto storagePool = storagePoolPost(); + storagePool.setIdStorage("tururututu"); + storagePool.addLink(new RESTLink("device", "http://localhost/api/admin/datacenters/1/storage/devices/1")); + storagePool.addLink(new RESTLink("edit", + "http://localhost/api/admin/datacenters/1/storage/devices/1/pools/tururututu")); + + return storagePool; + } + + public static RemoteServiceDto remoteServicePut() { + RemoteServiceDto remoteService = remoteServicePost(); + remoteService.setId(1); + remoteService.addLink(new RESTLink("check", + "http://localhost/api/admin/datacenters/1/remoteservices/nodecollector/action/check")); + remoteService.addLink(new RESTLink("datacenter", "http://localhost/api/admin/datacenters/1")); + remoteService.addLink(new RESTLink("edit", + "http://localhost/api/admin/datacenters/1/remoteservices/nodecollector")); + return remoteService; + } + + public static MachineDto machinePut() { + MachineDto machine = machinePost(); + machine.setId(1); + machine.addLink(new RESTLink("edit", "http://localhost/api/admin/datacenters/1/racks/1/machines/1")); + machine.addLink(new RESTLink("rack", "http://localhost/api/admin/datacenters/1/racks/1")); + machine.addLink(new RESTLink("checkstate", + "http://localhost/api/admin/datacenters/1/racks/1/machines/1/action/checkstate")); + machine.addLink(new RESTLink("checkipmistate", + "http://localhost/api/admin/datacenters/1/racks/1/machines/1/action/checkipmistate")); + machine.addLink(new RESTLink("led", "http://localhost/api/admin/datacenters/1/racks/1/machines/1/led")); + machine.addLink(new RESTLink("ledoff", + "http://localhost/api/admin/datacenters/1/racks/1/machines/1/action/ledoff")); + machine + .addLink(new RESTLink("ledon", "http://localhost/api/admin/datacenters/1/racks/1/machines/1/action/ledon")); + machine.addLink(new RESTLink("logicserver", + "http://localhost/api/admin/datacenters/1/racks/1/machines/1/logicserver")); + machine.addLink(new RESTLink("poweroff", + "http://localhost/api/admin/datacenters/1/racks/1/machines/1/action/poweroff")); + machine.addLink(new RESTLink("poweron", + "http://localhost/api/admin/datacenters/1/racks/1/machines/1/action/poweron")); + machine.addLink(new RESTLink("virtualmachines", + "http://localhost/api/admin/datacenters/1/racks/1/machines/1/virtualmachines")); + machine.setVirtualCpuCores(5); + + return machine; + } + + public static String datacenterPostPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append("Honolulu"); + buffer.append("DC"); + buffer.append(""); + return buffer.toString(); + } + + public static String rackPostPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append("false"); + buffer.append("Aloha"); + buffer.append("80"); + buffer.append("A hawaian rack"); + buffer.append("3024"); + buffer.append("6"); + buffer.append("6"); + buffer.append(""); + return buffer.toString(); + } + + public static String managedRackPostPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append("false"); + buffer.append("Aloha"); + buffer.append("80"); + buffer.append("A hawaian rack"); + buffer.append("3024"); + buffer.append("6"); + buffer.append("6"); + buffer.append(""); + return buffer.toString(); + } + + public static String storagePoolPostPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append("0"); + buffer.append("false"); + buffer.append("Hawaian Storage Pool"); + buffer.append("0"); + buffer.append("0"); + buffer.append(""); + return buffer.toString(); + } + + public static String storageDevicePostPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append("10.10.10.10"); + buffer.append("99"); + buffer.append("90"); + buffer.append("Aloha aloha"); + buffer.append(""); + return buffer.toString(); + } + + public static String machinePostPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append(""); + buffer.append("A hawaian machine"); + buffer.append("Kamehameha"); + buffer.append("3"); + buffer.append("1"); + buffer.append("512"); + buffer.append("1"); + buffer.append("192.168.1.10"); + buffer.append(""); + return buffer.toString(); + } + + public static String remoteServicePostPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append("0"); + buffer.append("NODE_COLLECTOR"); + buffer.append("http://localhost:80/nodecollector"); + buffer.append(""); + return buffer.toString(); + } + + public static String datacenterPutPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append(link("/admin/datacenters/1/action/checkmachinestate", "checkmachinestate")); + buffer.append(link("/admin/datacenters/1/action/checkmachineipmistate", "checkmachineipmistate")); + buffer.append(link("/admin/datacenters/1/action/checkremoteservice", "checkremoteservice")); + buffer.append(link("/admin/datacenters/1/storage/devices", "devices")); + buffer.append(link("/admin/datacenters/1/action/discovermultiple", "discovermultiple")); + buffer.append(link("/admin/datacenters/1/action/discoversingle", "discoversingle")); + buffer.append(link("/admin/datacenters/1", "edit")); + buffer.append(link("/admin/datacenters/1/action/getLimits", "getLimits")); + buffer.append(link("/admin/datacenters/1/racks", "racks")); + buffer.append(link("/admin/datacenters/1/remoteservices", "remoteservices")); + buffer.append(link("/admin/datacenters/1/storage/tiers", "tiers")); + buffer.append(link("/admin/datacenters/1/network", "network")); + buffer.append(link("/admin/datacenters/1/action/enterprises", "enterprises")); + buffer.append(link("/admin/datacenters/1/action/hypervisor", "hypervisor")); + buffer.append(link("/admin/datacenters/1/hypervisors", "hypervisors")); + buffer.append("1"); + buffer.append("Honolulu"); + buffer.append("DC"); + buffer.append(""); + return buffer.toString(); + } + + public static String storagePoolPutPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append(link("/admin/datacenters/1/storage/devices/1", "device")); + buffer.append(link("/admin/datacenters/1/storage/devices/1/pools/tururututu", "edit")); + buffer.append("0"); + buffer.append("false"); + buffer.append("tururututu"); + buffer.append("Hawaian Storage Pool"); + buffer.append("0"); + buffer.append("0"); + buffer.append(""); + return buffer.toString(); + } + + public static String tierPutPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append(link("/admin/datacenters/1/storage/tiers/1", "edit")); + buffer.append(link("/admin/datacenters/1", "datacenter")); + buffer.append(link("/admin/datacenters/1/storage/tiers/1/pools", "pools")); + buffer.append("true"); + buffer.append("1"); + buffer.append("Tier"); + buffer.append(""); + return buffer.toString(); + } + + public static String rackPutPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append(link("/admin/datacenters/1", "datacenter")); + buffer.append(link("/admin/datacenters/1/racks/1", "edit")); + buffer.append(link("/admin/datacenters/1/racks/1/machines", "machines")); + buffer.append("false"); + buffer.append("1"); + buffer.append("Aloha"); + buffer.append("80"); + buffer.append("A hawaian rack"); + buffer.append("3024"); + buffer.append("6"); + buffer.append("6"); + buffer.append(""); + return buffer.toString(); + } + + public static String managedRackPutPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append(link("/admin/datacenters/1", "datacenter")); + buffer.append(link("/admin/datacenters/1/racks/1", "edit")); + buffer.append(link("/admin/datacenters/1/racks/1/fsm", "fsm")); + buffer.append(link("/admin/datacenters/1/racks/1/logicservers", "logicservers")); + buffer.append(link("/admin/datacenters/1/racks/1/lstemplates", "ls-templates")); + buffer.append(link("/admin/datacenters/1/racks/1/organizations", "organizations")); + buffer.append(link("/admin/datacenters/1/racks/1/logicservers/associate", "ls-associate")); + buffer.append(link("/admin/datacenters/1/racks/1/logicservers/assocclone", "ls-associateclone")); + buffer.append(link("/admin/datacenters/1/racks/1/logicservers/associatetemplate", "ls-associatetemplate")); + buffer.append(link("/admin/datacenters/1/racks/1/logicservers/clone", "ls-clone")); + buffer.append(link("/admin/datacenters/1/racks/1/logicservers/delete", "ls-delete")); + buffer.append(link("/admin/datacenters/1/racks/1/logicservers/dissociate", "ls-dissociate")); + buffer.append("false"); + buffer.append("1"); + buffer.append("Aloha"); + buffer.append("80"); + buffer.append("A hawaian rack"); + buffer.append("3024"); + buffer.append("6"); + buffer.append("6"); + buffer.append(""); + return buffer.toString(); + } + + public static String storageDevicePutPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append(link("/admin/datacenters/1", "datacenter")); + buffer.append(link("/admin/datacenters/1/storage/devices/1", "edit")); + buffer.append(link("/admin/datacenters/1/storage/devices/1/pools", "pools")); + buffer.append("1"); + buffer.append("10.10.10.10"); + buffer.append("99"); + buffer.append("90"); + buffer.append("Aloha aloha"); + buffer.append(""); + return buffer.toString(); + } + + public static String remoteServicePutPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append(link("/admin/datacenters/1/remoteservices/nodecollector/action/check", "check")); + buffer.append(link("/admin/datacenters/1", "datacenter")); + buffer.append(link("/admin/datacenters/1/remoteservices/nodecollector", "edit")); + buffer.append("1"); + buffer.append("0"); + buffer.append("NODE_COLLECTOR"); + buffer.append("http://localhost:80/nodecollector"); + buffer.append(""); + return buffer.toString(); + } + + public static String machinePutPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append(link("/admin/datacenters/1/racks/1/machines/1", "edit")); + buffer.append(link("/admin/datacenters/1/racks/1", "rack")); + buffer.append(link("/admin/datacenters/1/racks/1/machines/1/action/checkstate", "checkstate")); + buffer.append(link("/admin/datacenters/1/racks/1/machines/1/action/checkipmistate", "checkipmistate")); + buffer.append(link("/admin/datacenters/1/racks/1/machines/1/led", "led")); + buffer.append(link("/admin/datacenters/1/racks/1/machines/1/action/ledoff", "ledoff")); + buffer.append(link("/admin/datacenters/1/racks/1/machines/1/action/ledon", "ledon")); + buffer.append(link("/admin/datacenters/1/racks/1/machines/1/logicserver", "logicserver")); + buffer.append(link("/admin/datacenters/1/racks/1/machines/1/action/poweroff", "poweroff")); + buffer.append(link("/admin/datacenters/1/racks/1/machines/1/action/poweron", "poweron")); + buffer.append(link("/admin/datacenters/1/racks/1/machines/1/virtualmachines", "virtualmachines")); + buffer.append(""); + buffer.append("A hawaian machine"); + buffer.append("1"); + buffer.append("Kamehameha"); + buffer.append("5"); + buffer.append("1"); + buffer.append("512"); + buffer.append("1"); + buffer.append("192.168.1.10"); + buffer.append(""); + return buffer.toString(); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/NetworkResources.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/NetworkResources.java new file mode 100644 index 0000000000..364645fcb7 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/NetworkResources.java @@ -0,0 +1,248 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain; + +import static org.jclouds.abiquo.domain.DomainUtils.link; + +import com.abiquo.model.enumerator.NetworkType; +import com.abiquo.model.rest.RESTLink; +import com.abiquo.model.transport.LinksDto; +import com.abiquo.server.core.infrastructure.network.NicDto; +import com.abiquo.server.core.infrastructure.network.PrivateIpDto; +import com.abiquo.server.core.infrastructure.network.PublicIpDto; +import com.abiquo.server.core.infrastructure.network.VLANNetworkDto; + +/** + * Network domain utilities. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +public class NetworkResources { + public static VLANNetworkDto vlanPost() { + VLANNetworkDto vlan = new VLANNetworkDto(); + vlan.setAddress("192.168.1.0"); + vlan.setDefaultNetwork(true); + vlan.setName("DefaultNetwork"); + vlan.setGateway("192.168.1.1"); + vlan.setMask(24); + + return vlan; + } + + public static PrivateIpDto privateIpPut() { + PrivateIpDto ip = new PrivateIpDto(); + ip.setId(1); + ip.setName("private ip"); + ip.setMac("00:58:5A:c0:C3:01"); + RESTLink self = new RESTLink("self", "http://localhost/api/cloud/virtualdatacenters/1/privatenetworks/1/ips/1"); + self.setTitle("privateip"); + ip.addLink(self); + return ip; + } + + public static PublicIpDto publicIpToPurchase() { + PublicIpDto ip = new PublicIpDto(); + RESTLink self = new RESTLink("purchase", "http://localhost/api/cloud/virtualdatacenters/5/publicips/purchased/1"); + ip.addLink(self); + return ip; + } + + public static PublicIpDto publicIpToRelease() { + PublicIpDto ip = new PublicIpDto(); + RESTLink self = new RESTLink("release", "http://localhost/api/cloud/virtualdatacenters/5/publicips/topurchase/1"); + ip.addLink(self); + return ip; + } + + public static NicDto nicPut() { + NicDto nic = new NicDto(); + nic.setId(1); + nic.setIp("123.123.123.123"); + nic.setMac("00:58:5A:c0:C3:01"); + nic.addLink(new RESTLink("edit", + "http://localhost/api/cloud/virtualdatacenters/1/virtualappliances/1/virtualmachines/1/network/nics/1")); + + return nic; + } + + public static VLANNetworkDto privateNetworkPut() { + VLANNetworkDto vlan = new VLANNetworkDto(); + vlan.setId(1); + vlan.setAddress("192.168.1.0"); + vlan.setDefaultNetwork(true); + vlan.setName("DefaultNetwork"); + vlan.setGateway("192.168.1.1"); + vlan.setMask(24); + vlan.setType(NetworkType.INTERNAL); + vlan.addLink(new RESTLink("edit", "http://localhost/api/cloud/virtualdatacenters/1/privatenetworks/1")); + vlan.addLink(new RESTLink("ips", "http://localhost/api/cloud/virtualdatacenters/1/privatenetworks/1/ips")); + + return vlan; + } + + public static VLANNetworkDto publicNetworkPut() { + VLANNetworkDto vlan = new VLANNetworkDto(); + vlan.setId(1); + vlan.setAddress("192.168.1.0"); + vlan.setDefaultNetwork(true); + vlan.setName("PublicNetwork"); + vlan.setGateway("192.168.1.1"); + vlan.setMask(24); + vlan.setType(NetworkType.PUBLIC); + vlan.addLink(new RESTLink("edit", "http://localhost/api/admin/datacenters/1/network/1")); + vlan.addLink(new RESTLink("ips", "http://localhost/api/admin/datacenters/1/network/1/ips")); + + return vlan; + } + + public static VLANNetworkDto externalNetworkPut() { + VLANNetworkDto vlan = new VLANNetworkDto(); + vlan.setId(1); + vlan.setAddress("192.168.1.0"); + vlan.setDefaultNetwork(true); + vlan.setName("ExternalNetwork"); + vlan.setGateway("192.168.1.1"); + vlan.setMask(24); + vlan.setType(NetworkType.EXTERNAL); + vlan.addLink(new RESTLink("edit", "http://localhost/api/admin/datacenters/1/network/1")); + vlan.addLink(new RESTLink("enterprise", "http://localhost/api/admin/enterprises/1")); + vlan.addLink(new RESTLink("ips", "http://localhost/api/admin/enterprises/1/limits/1/externalnetworks/1/ips")); + + return vlan; + } + + public static VLANNetworkDto unmanagedNetworkPut() { + VLANNetworkDto vlan = new VLANNetworkDto(); + vlan.setId(1); + vlan.setAddress("192.168.1.0"); + vlan.setDefaultNetwork(true); + vlan.setName("UnmanagedNetwork"); + vlan.setGateway("192.168.1.1"); + vlan.setMask(24); + vlan.setType(NetworkType.UNMANAGED); + vlan.addLink(new RESTLink("edit", "http://localhost/api/admin/datacenters/1/network/1")); + vlan.addLink(new RESTLink("enterprise", "http://localhost/api/admin/enterprises/1")); + vlan.addLink(new RESTLink("ips", "http://localhost/api/admin/enterprises/1/limits/1/externalnetworks/1/ips")); + + return vlan; + } + + public static String vlanNetworkPostPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append("
192.168.1.0
"); + buffer.append("true"); + buffer.append("192.168.1.1"); + buffer.append("24"); + buffer.append("DefaultNetwork"); + buffer.append("
"); + return buffer.toString(); + } + + public static String privateNetworkPutPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append(link("/cloud/virtualdatacenters/1/privatenetworks/1", "edit")); + buffer.append(link("/cloud/virtualdatacenters/1/privatenetworks/1/ips", "ips")); + buffer.append("
192.168.1.0
"); + buffer.append("true"); + buffer.append("192.168.1.1"); + buffer.append("1"); + buffer.append("24"); + buffer.append("DefaultNetwork"); + buffer.append("INTERNAL"); + buffer.append("
"); + return buffer.toString(); + } + + public static String publicNetworkPutPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append(link("/admin/datacenters/1/network/1", "edit")); + buffer.append(link("/admin/datacenters/1/network/1/ips", "ips")); + buffer.append("
192.168.1.0
"); + buffer.append("true"); + buffer.append("192.168.1.1"); + buffer.append("1"); + buffer.append("24"); + buffer.append("PublicNetwork"); + buffer.append("PUBLIC"); + buffer.append("
"); + return buffer.toString(); + } + + public static String externalNetworkPutPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append(link("/admin/datacenters/1/network/1", "edit")); + buffer.append(link("/admin/enterprises/1", "enterprise")); + buffer.append(link("/admin/enterprises/1/limits/1/externalnetworks/1/ips", "ips")); + buffer.append("
192.168.1.0
"); + buffer.append("true"); + buffer.append("192.168.1.1"); + buffer.append("1"); + buffer.append("24"); + buffer.append("ExternalNetwork"); + buffer.append("EXTERNAL"); + buffer.append("
"); + return buffer.toString(); + } + + public static String unmanagedNetworkPutPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append(link("/admin/datacenters/1/network/1", "edit")); + buffer.append(link("/admin/enterprises/1", "enterprise")); + buffer.append(link("/admin/enterprises/1/limits/1/externalnetworks/1/ips", "ips")); + buffer.append("
192.168.1.0
"); + buffer.append("true"); + buffer.append("192.168.1.1"); + buffer.append("1"); + buffer.append("24"); + buffer.append("UnmanagedNetwork"); + buffer.append("UNMANAGED"); + buffer.append("
"); + return buffer.toString(); + } + + public static String privateIpPutPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append(link("/cloud/virtualdatacenters/1/privatenetworks/1/ips/1", "self", "privateip")); + buffer.append("false"); + buffer.append("1"); + buffer.append("00:58:5A:c0:C3:01"); + buffer.append("private ip"); + buffer.append("false"); + buffer.append(""); + return buffer.toString(); + } + + public static String linksDtoPayload(final LinksDto dto) { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + for (RESTLink link : dto.getLinks()) { + buffer.append(link(link)); + } + buffer.append(""); + return buffer.toString(); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/PricingResources.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/PricingResources.java new file mode 100644 index 0000000000..636e7f5d15 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/PricingResources.java @@ -0,0 +1,276 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain; + +import static org.jclouds.abiquo.domain.DomainUtils.link; + +import java.math.BigDecimal; + +import com.abiquo.model.rest.RESTLink; +import com.abiquo.server.core.pricing.CostCodeCurrenciesDto; +import com.abiquo.server.core.pricing.CostCodeCurrencyDto; +import com.abiquo.server.core.pricing.CostCodeDto; +import com.abiquo.server.core.pricing.CurrencyDto; +import com.abiquo.server.core.pricing.PricingCostCodeDto; +import com.abiquo.server.core.pricing.PricingTemplateDto; +import com.abiquo.server.core.pricing.PricingTierDto; + +/** + * Enterprise domain utilities. + * + * @author Ignasi Barrera + * @author Susana Acedo + */ +public class PricingResources { + + public static CurrencyDto currencyPost() { + CurrencyDto currency = new CurrencyDto(); + currency.setName("yuan"); + currency.setSymbol("DUMMY"); + currency.setDigits(3); + return currency; + } + + public static CurrencyDto currencyPut() { + CurrencyDto currency = new CurrencyDto(); + currency.setName("yuan"); + currency.setSymbol("DUMMY"); + currency.setDigits(3); + currency.setId(1); + currency.addLink(new RESTLink("edit", "http://localhost/api/config/currencies/1")); + return currency; + } + + public static String currencyPostPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append("DUMMY"); + buffer.append("3"); + buffer.append("yuan"); + buffer.append(""); + return buffer.toString(); + } + + public static String currencyPutPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append(link("/config/currencies/1", "edit")); + buffer.append("DUMMY"); + buffer.append("3"); + buffer.append("1"); + buffer.append("yuan"); + buffer.append(""); + return buffer.toString(); + } + + public static Object costcodePost() { + CostCodeDto costcode = new CostCodeDto(); + costcode.setName("cost code"); + costcode.setDescription("description"); + return costcode; + } + + public static Object costcodePut() { + CostCodeDto costcode = new CostCodeDto(); + costcode.setName("cost code"); + costcode.setDescription("description"); + costcode.setId(1); + costcode.addLink(new RESTLink("edit", "http://localhost/api/config/costcodes/1")); + return costcode; + } + + public static String costcodePostPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append("cost code"); + buffer.append("description"); + buffer.append(""); + return buffer.toString(); + } + + public static String costcodePutPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append(link("/config/costcodes/1", "edit")); + buffer.append("description"); + buffer.append("1"); + buffer.append("cost code"); + buffer.append(""); + return buffer.toString(); + } + + public static Object pricingtemplatePost() { + PricingTemplateDto pricingtemplate = new PricingTemplateDto(); + pricingtemplate.setName("pricing template"); + pricingtemplate.setDescription("pt_description"); + pricingtemplate.setHdGB(new BigDecimal(0)); + pricingtemplate.setStandingChargePeriod(new BigDecimal(0)); + pricingtemplate.setVlan(new BigDecimal(0)); + pricingtemplate.setChargingPeriod(1); + pricingtemplate.setMinimumChargePeriod(new BigDecimal(0)); + pricingtemplate.setShowChangesBefore(true); + pricingtemplate.setShowMinimumCharge(false); + pricingtemplate.setMinimumCharge(2); + pricingtemplate.setPublicIp(new BigDecimal(0)); + pricingtemplate.setVcpu(new BigDecimal(0)); + pricingtemplate.setMemoryGB(new BigDecimal(0)); + pricingtemplate.setDefaultTemplate(true); + pricingtemplate.addLink(new RESTLink("currency", "http://localhost/api/config/currencies/1")); + return pricingtemplate; + } + + public static Object pricingtemplatePut() { + PricingTemplateDto pricingtemplate = new PricingTemplateDto(); + pricingtemplate.setName("pricing template"); + pricingtemplate.setDescription("pt_description"); + pricingtemplate.setHdGB(new BigDecimal(0)); + pricingtemplate.setStandingChargePeriod(new BigDecimal(0)); + pricingtemplate.setVlan(new BigDecimal(0)); + pricingtemplate.setChargingPeriod(1); + pricingtemplate.setMinimumChargePeriod(new BigDecimal(0)); + pricingtemplate.setShowChangesBefore(true); + pricingtemplate.setShowMinimumCharge(false); + pricingtemplate.setMinimumCharge(2); + pricingtemplate.setPublicIp(new BigDecimal(0)); + pricingtemplate.setVcpu(new BigDecimal(0)); + pricingtemplate.setMemoryGB(new BigDecimal(0)); + pricingtemplate.setDefaultTemplate(true); + pricingtemplate.addLink(new RESTLink("currency", "http://localhost/api/config/currencies/1")); + pricingtemplate.setId(1); + pricingtemplate.addLink(new RESTLink("edit", "http://localhost/api/config/pricingtemplates/1")); + return pricingtemplate; + } + + public static String pricingtemplatePostPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append("pricing template"); + buffer.append("pt_description"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("1"); + buffer.append("0"); + buffer.append("true"); + buffer.append("false"); + buffer.append("2"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("true"); + buffer.append(""); + buffer.append(""); + return buffer.toString(); + } + + public static String pricingtemplatePutPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append("pricing template"); + buffer.append("pt_description"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("1"); + buffer.append("0"); + buffer.append("true"); + buffer.append("false"); + buffer.append("2"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("true"); + buffer.append(""); + buffer.append("1"); + buffer.append(link("/config/pricingtemplates/1", "edit")); + buffer.append(""); + return buffer.toString(); + } + + public static Object costcodecurrencyPut() { + CostCodeCurrencyDto costcodecurrency = new CostCodeCurrencyDto(); + costcodecurrency.addLink(new RESTLink("edit", "http://localhost/api/config/costcodes/1/currencies")); + costcodecurrency.addLink(new RESTLink("currency", "http://localhost/api/config/currencies/1")); + costcodecurrency.setPrice(new BigDecimal("300")); + CostCodeCurrenciesDto costcodecurrencies = new CostCodeCurrenciesDto(); + costcodecurrencies.add(costcodecurrency); + return costcodecurrencies; + } + + public static String costcodecurrencyPutPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append(""); + buffer.append("300"); + buffer.append(""); + buffer.append(""); + buffer.append(""); + + buffer.append(""); + return buffer.toString(); + } + + public static Object pricingCostcodePut() { + PricingCostCodeDto pricingcostcode = new PricingCostCodeDto(); + pricingcostcode.setId(1); + pricingcostcode.setPrice(new BigDecimal("400")); + pricingcostcode.addLink(new RESTLink("costcode", "http://localhost/api/config/costcodes/1")); + pricingcostcode.addLink(new RESTLink("pricingtemplate", "http://localhost/api/config/pricingtemplates/1")); + pricingcostcode.addLink(new RESTLink("edit", "http://localhost/api/config/pricingtemplates/1/costcodes/1")); + return pricingcostcode; + } + + public static String pricingCostCodePutPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append(""); + buffer.append(""); + buffer.append("400"); + buffer.append("1"); + buffer.append(link("/config/pricingtemplates/1/costcodes/1", "edit")); + buffer.append(""); + return buffer.toString(); + } + + public static Object pricingTierPut() { + PricingTierDto pricingtier = new PricingTierDto(); + pricingtier.setId(1); + pricingtier.setPrice(new BigDecimal("600")); + pricingtier.addLink(new RESTLink("tier", "http://localhost/api/admin/datacenters/1/storage/tiers/2")); + pricingtier.addLink(new RESTLink("pricingtemplate", "http://localhost/api/config/pricingtemplates/1")); + pricingtier.addLink(new RESTLink("edit", "http://localhost/api/config/pricingtemplates/1/tiers/2")); + return pricingtier; + } + + public static String pricingTierPutPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append(""); + buffer.append(""); + buffer.append("600"); + buffer.append("1"); + buffer.append(link("/config/pricingtemplates/1/tiers/2", "edit")); + buffer.append(""); + return buffer.toString(); + } + +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/TemplateResources.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/TemplateResources.java new file mode 100644 index 0000000000..304889b5ce --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/TemplateResources.java @@ -0,0 +1,155 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain; + +import static org.jclouds.abiquo.domain.DomainUtils.link; + +import com.abiquo.model.enumerator.ConversionState; +import com.abiquo.model.enumerator.DiskFormatType; +import com.abiquo.model.rest.RESTLink; +import com.abiquo.server.core.appslibrary.ConversionDto; +import com.abiquo.server.core.appslibrary.DatacenterRepositoryDto; +import com.abiquo.server.core.appslibrary.VirtualMachineTemplateDto; +import com.abiquo.server.core.appslibrary.VirtualMachineTemplatePersistentDto; + +/** + * VM template domain utilities. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +public class TemplateResources { + public static DatacenterRepositoryDto datacenterRepositoryPut() { + DatacenterRepositoryDto dcRepository = new DatacenterRepositoryDto(); + dcRepository.setName("Datacenter Repo"); + dcRepository.setRepositoryCapacityMb(0); + dcRepository.setRepositoryLocation("10.60.1.104:/volume1/nfs-devel"); + dcRepository.setRepositoryRemainingMb(0); + dcRepository.addLink(new RESTLink("applianceManagerRepositoryUri", "http://localhost/am/erepos/1")); + dcRepository.addLink(new RESTLink("datacenter", "http://localhost/api/admin/datacenters/1")); + dcRepository.addLink(new RESTLink("edit", "http://localhost/api/admin/enterprises/1/datacenterrepositories/1")); + dcRepository.addLink(new RESTLink("enterprise", "http://localhost/api/admin/enterprises/1")); + dcRepository.addLink(new RESTLink("refresh", + "http://localhost/api/admin/enterprises/1/datacenterrepositories/1/actions/refresh")); + dcRepository.addLink(new RESTLink("virtualmachinetemplates", + "http://localhost/api/admin/enterprises/1/datacenterrepositories/1/virtualmachinetemplates")); + + return dcRepository; + } + + public static VirtualMachineTemplateDto virtualMachineTemplatePut() { + VirtualMachineTemplateDto template = new VirtualMachineTemplateDto(); + template.setName("Template"); + template.setId(1); + template.setDescription("Description"); + template.addLink(new RESTLink("edit", + "http://localhost/api/admin/enterprises/1/datacenterrepositories/1/virtualmachinetemplates/1")); + template.addLink(new RESTLink("enterprise", "http://localhost/api/admin/enterprises/1")); + template.addLink(new RESTLink("conversions", "http://localhost/api/admin/enterprises/1" + + "/datacenterrepositories/1/virtualmachinetemplates/1/conversions")); + template.addLink(new RESTLink("tasks", "http://localhost/api/admin/enterprises/1" + + "/datacenterrepositories/1/virtualmachinetemplates/1/tasks")); + + return template; + } + + public static String virtualMachineTemplatePutPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append(link("/admin/enterprises/1/datacenterrepositories/1/virtualmachinetemplates/1", "edit")); + buffer.append(link("/admin/enterprises/1", "enterprise")); + buffer.append(link("/admin/enterprises/1" + "/datacenterrepositories/1/virtualmachinetemplates/1/conversions", + "conversions")); + + buffer.append(link("/admin/enterprises/1" + "/datacenterrepositories/1/virtualmachinetemplates/1/tasks", "tasks")); + buffer.append("1"); + buffer.append("Template"); + buffer.append("Description"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("0"); + buffer.append("false"); + buffer.append("0"); + buffer.append("false"); + buffer.append(""); + return buffer.toString(); + } + + public static VirtualMachineTemplatePersistentDto persistentData() { + VirtualMachineTemplatePersistentDto dto = new VirtualMachineTemplatePersistentDto(); + dto.setPersistentTemplateName("New persistent template name"); + dto.setPersistentVolumeName("New persistent volume name"); + dto.addLink(new RESTLink("tier", "http://localhost/api/cloud/virtualdatacenters/1/tiers/1")); + dto.addLink(new RESTLink("virtualdatacenter", "http://localhost/api/cloud/virtualdatacenters/1")); + dto.addLink(new RESTLink("virtualmachinetemplate", + "http://localhost/api/admin/enterprises/1/datacenterrepositories/1/virtualmachinetemplates/1")); + return dto; + } + + public static String persistentPayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append(link("/cloud/virtualdatacenters/1/tiers/1", "tier")); + buffer.append(link("/cloud/virtualdatacenters/1", "virtualdatacenter")); + buffer.append(link("/admin/enterprises/1/datacenterrepositories/1/virtualmachinetemplates/1", + "virtualmachinetemplate")); + buffer.append("New persistent template name"); + buffer.append("New persistent volume name"); + buffer.append(""); + return buffer.toString(); + } + + public static ConversionDto conversionPut() { + ConversionDto conversion = new ConversionDto(); + conversion.setState(ConversionState.ENQUEUED); + conversion.setSourceFormat(DiskFormatType.VMDK_STREAM_OPTIMIZED); + conversion.setSourcePath("source/path.vmkd"); + conversion.setTargetFormat(DiskFormatType.RAW); + conversion.setTargetPath("target/path.raw"); + conversion.setTargetSizeInBytes(1000000l); + conversion + .addLink(new RESTLink("edit", + "http://localhost/api/admin/enterprises/1/datacenterrepositories/1/virtualmachinetemplates/1/conversions/RAW")); + conversion + .addLink(new RESTLink("tasks", + "http://localhost/api/admin/enterprises/1/datacenterrepositories/1/virtualmachinetemplates/1/conversions/RAW/tasks")); + + return conversion; + } + + public static String conversionPutPlayload() { + StringBuffer buffer = new StringBuffer(); + buffer.append(""); + buffer.append(link("/admin/enterprises/1/datacenterrepositories/1/virtualmachinetemplates/1/conversions/RAW", + "edit")); + buffer.append(link( + "/admin/enterprises/1/datacenterrepositories/1/virtualmachinetemplates/1/conversions/RAW/tasks", "tasks")); + + buffer.append("ENQUEUED"); + buffer.append("VMDK_STREAM_OPTIMIZED"); + buffer.append("source/path.vmkd"); + buffer.append("RAW"); + buffer.append("target/path.raw"); + buffer.append("1000000"); + buffer.append(""); + return buffer.toString(); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/admin/RoleLiveApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/admin/RoleLiveApiTest.java new file mode 100644 index 0000000000..40cdb681b1 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/admin/RoleLiveApiTest.java @@ -0,0 +1,102 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.admin; + +import static org.jclouds.abiquo.util.Assert.assertHasError; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.fail; + +import java.util.List; + +import javax.ws.rs.core.Response.Status; + +import org.jclouds.abiquo.domain.DomainWrapper; +import org.jclouds.abiquo.domain.config.Privilege; +import org.jclouds.abiquo.domain.enterprise.Role; +import org.jclouds.abiquo.domain.exception.AbiquoException; +import org.jclouds.abiquo.internal.BaseAbiquoApiLiveApiTest; +import org.jclouds.abiquo.predicates.config.PrivilegePredicates; +import org.jclouds.abiquo.predicates.enterprise.RolePredicates; +import org.testng.annotations.Test; + +import com.abiquo.server.core.enterprise.PrivilegeDto; +import com.abiquo.server.core.enterprise.RoleDto; + +/** + * Live integration tests for the {@link Role} domain class. + * + * @author Francesc Montserrat + */ +@Test(groups = "api", testName = "RoleLiveApiTest") +public class RoleLiveApiTest extends BaseAbiquoApiLiveApiTest { + + public void testUpdate() { + Role role = Role.builder(env.context.getApiContext()).name("dummyRoleUpdateRole").blocked(false).build(); + role.save(); + + role.setName("UPDATED_ROLE"); + role.update(); + + // Recover the updated role + RoleDto updated = env.adminApi.getRole(role.getId()); + + assertEquals(updated.getName(), "UPDATED_ROLE"); + + role.delete(); + } + + public void testCreateRepeated() { + Role repeated = Role.Builder.fromRole(env.role).build(); + + try { + repeated.save(); + fail("Should not be able to create roles with the same name"); + } catch (AbiquoException ex) { + assertHasError(ex, Status.CONFLICT, "ROLE-7"); + } + } + + public void testCreateEnterpriseRole() { + Role entRole = Role.Builder.fromRole(env.role).build(); + entRole.setName(entRole.getName() + "enterprise"); + entRole.setEnterprise(env.enterprise); + entRole.save(); + + entRole = env.enterprise.findRole(RolePredicates.name(entRole.getName())); + + assertNotNull(entRole); + } + + public void testAddPrivilege() { + PrivilegeDto dto = env.configApi.getPrivilege(8); + Privilege privilege = DomainWrapper.wrap(env.context.getApiContext(), Privilege.class, dto); + List privileges = env.role.listPrivileges(); + privileges.add(privilege); + + env.role.setPrivileges(privileges); + + env.role.update(); + + privilege = env.role.findPrivileges(PrivilegePredicates.name(dto.getName())); + + assertNotNull(privilege); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/cloud/HardDiskLiveApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/cloud/HardDiskLiveApiTest.java new file mode 100644 index 0000000000..3c745f5372 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/cloud/HardDiskLiveApiTest.java @@ -0,0 +1,70 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.cloud; + +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; + +import org.jclouds.abiquo.internal.BaseAbiquoApiLiveApiTest; +import org.testng.SkipException; +import org.testng.annotations.Test; + +import com.abiquo.model.enumerator.HypervisorType; + +/** + * Live integration tests for the {@link HardDisk} domain class. + * + * @author Ignasi Barrera + */ +@Test(groups = "api", testName = "HardDiskLiveApiTest") +public class HardDiskLiveApiTest extends BaseAbiquoApiLiveApiTest { + private HardDisk hardDisk; + + public void createHardDisk() { + skipIfUnsupported(); + + hardDisk = HardDisk.builder(env.context.getApiContext(), env.virtualDatacenter).sizeInMb(64L).build(); + hardDisk.save(); + + assertNotNull(hardDisk.getId()); + assertNotNull(hardDisk.getSequence()); + + assertNotNull(env.virtualDatacenter.getHardDisk(hardDisk.getId())); + } + + @Test(dependsOnMethods = "createHardDisk") + public void deleteHardDisk() { + skipIfUnsupported(); + + HardDisk hd = env.virtualDatacenter.getHardDisk(hardDisk.getId()); + assertNotNull(hd); + + Integer id = hd.getId(); + hardDisk.delete(); + assertNull(env.virtualDatacenter.getHardDisk(id)); + } + + protected static void skipIfUnsupported() { + if (!env.machine.getType().equals(HypervisorType.VMX_04)) { + throw new SkipException( + "Cannot perform this test because hard disk actions are not available for this hypervisor"); + } + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/cloud/VirtualApplianceLiveApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/cloud/VirtualApplianceLiveApiTest.java new file mode 100644 index 0000000000..7f70c00a81 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/cloud/VirtualApplianceLiveApiTest.java @@ -0,0 +1,96 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.cloud; + +import static com.google.common.collect.Iterables.size; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.List; + +import org.jclouds.abiquo.internal.BaseAbiquoApiLiveApiTest; +import org.testng.annotations.Test; + +import com.abiquo.server.core.cloud.VirtualApplianceDto; +import com.abiquo.server.core.cloud.VirtualApplianceState; + +/** + * Live integration tests for the {@link VirtualAppliance} domain class. + * + * @author Francesc Montserrat + */ +@Test(groups = "api", testName = "VirtualApplianceLiveApiTest") +public class VirtualApplianceLiveApiTest extends BaseAbiquoApiLiveApiTest { + + public void testUpdate() { + env.virtualAppliance.setName("Virtual AppAloha updated"); + env.virtualAppliance.update(); + + // Recover the updated virtual appliance + VirtualApplianceDto updated = env.cloudApi.getVirtualAppliance(env.virtualDatacenter.unwrap(), + env.virtualAppliance.getId()); + + assertEquals(updated.getName(), "Virtual AppAloha updated"); + } + + public void testCreateRepeated() { + VirtualAppliance repeated = VirtualAppliance.Builder.fromVirtualAppliance(env.virtualAppliance).build(); + + repeated.save(); + + List virtualAppliances = env.cloudApi.listVirtualAppliances(env.virtualDatacenter.unwrap()) + .getCollection(); + + assertEquals(virtualAppliances.size(), 2); + repeated.delete(); + } + + public void testGetState() { + assertEquals(env.virtualAppliance.getState(), VirtualApplianceState.NOT_DEPLOYED); + } + + public void testListVirtualMachinesReturnsAll() { + List vms = new ArrayList(); + + // Pagination by default is set to 25 items per page, so create a few more + // to verify that + // all are returned when listing + int numVms = 30; + + for (int i = 0; i < numVms; i++) { + VirtualMachine vm = VirtualMachine.Builder.fromVirtualMachine(env.virtualMachine).build(); + vm.save(); + vms.add(vm); + } + + try { + Iterable all = env.virtualAppliance.listVirtualMachines(); + + assertNotNull(all); + assertTrue(size(all) >= numVms); + } finally { + for (VirtualMachine vm : vms) { + vm.delete(); + } + } + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/cloud/VirtualDatacenterLiveApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/cloud/VirtualDatacenterLiveApiTest.java new file mode 100644 index 0000000000..14fdf14cba --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/cloud/VirtualDatacenterLiveApiTest.java @@ -0,0 +1,181 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.cloud; + +import static com.google.common.collect.Iterables.size; +import static org.jclouds.abiquo.reference.AbiquoTestConstants.PREFIX; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertTrue; + +import java.util.List; + +import org.jclouds.abiquo.domain.cloud.VirtualDatacenter.Builder; +import org.jclouds.abiquo.domain.cloud.options.VirtualDatacenterOptions; +import org.jclouds.abiquo.domain.enterprise.Enterprise; +import org.jclouds.abiquo.domain.infrastructure.Datacenter; +import org.jclouds.abiquo.domain.network.PrivateNetwork; +import org.jclouds.abiquo.domain.network.PublicIp; +import org.jclouds.abiquo.internal.BaseAbiquoApiLiveApiTest; +import org.jclouds.abiquo.predicates.cloud.VirtualMachineTemplatePredicates; +import org.jclouds.abiquo.predicates.network.IpPredicates; +import org.testng.annotations.Test; + +import com.abiquo.model.enumerator.HypervisorType; +import com.abiquo.server.core.cloud.VirtualDatacenterDto; + +/** + * Live integration tests for the {@link VirtualDatacenter} domain class. + * + * @author Francesc Montserrat + */ +@Test(groups = "api", testName = "VirtualDatacenterLiveApiTest") +public class VirtualDatacenterLiveApiTest extends BaseAbiquoApiLiveApiTest { + private VirtualMachineTemplate template; + + public void testUpdate() { + env.virtualDatacenter.setName("Aloha updated"); + env.virtualDatacenter.update(); + + // Recover the updated virtual datacenter + VirtualDatacenterDto updated = env.cloudApi.getVirtualDatacenter(env.virtualDatacenter.getId()); + + assertEquals(updated.getName(), "Aloha updated"); + } + + public void testCreateRepeated() { + PrivateNetwork newnet = PrivateNetwork.builder(env.context.getApiContext()).name("Newnet").gateway("10.0.0.1") + .address("10.0.0.0").mask(24).build(); + + VirtualDatacenter repeated = Builder.fromVirtualDatacenter(env.virtualDatacenter).network(newnet).build(); + + repeated.save(); + + List virtualDatacenters = env.cloudApi.listVirtualDatacenters( + VirtualDatacenterOptions.builder().build()).getCollection(); + + assertEquals(virtualDatacenters.size(), 2); + assertEquals(virtualDatacenters.get(0).getName(), virtualDatacenters.get(1).getName()); + repeated.delete(); + } + + public void testCreateFromEnterprise() { + Enterprise enterprise = env.enterpriseAdminContext.getAdministrationService().getCurrentUser().getEnterprise(); + assertNotNull(enterprise); + + List datacenters = enterprise.listAllowedDatacenters(); + assertNotNull(datacenters); + assertTrue(size(datacenters) > 0); + + Datacenter datacenter = datacenters.get(0); + + List hypervisors = datacenter.listAvailableHypervisors(); + assertNotNull(datacenters); + assertTrue(size(datacenters) > 0); + + HypervisorType hypervisor = hypervisors.get(0); + + PrivateNetwork network = PrivateNetwork.builder(env.enterpriseAdminContext.getApiContext()) + .name("DefaultNetwork").gateway("192.168.1.1").address("192.168.1.0").mask(24).build(); + + VirtualDatacenter virtualDatacenter = VirtualDatacenter + .builder(env.enterpriseAdminContext.getApiContext(), datacenters.get(0), enterprise) + .name(PREFIX + "Plain Virtual Aloha from ENT").cpuCountLimits(18, 20).hdLimitsInMb(279172872, 279172872) + .publicIpsLimits(2, 2).ramLimits(19456, 20480).storageLimits(289910292, 322122547).vlansLimits(1, 2) + .hypervisorType(hypervisor).network(network).build(); + + virtualDatacenter.save(); + assertNotNull(virtualDatacenter.getId()); + + virtualDatacenter.delete(); + } + + public void testCreateFromVirtualDatacenter() { + HypervisorType hypervisor = env.virtualDatacenter.getHypervisorType(); + + Enterprise enterprise = env.user.getEnterprise(); + assertNotNull(enterprise); + + Datacenter datacenter = env.virtualDatacenter.getDatacenter(); + assertNotNull(datacenter); + + PrivateNetwork network = PrivateNetwork.builder(env.plainUserContext.getApiContext()).name("DefaultNetwork") + .gateway("192.168.1.1").address("192.168.1.0").mask(24).build(); + + VirtualDatacenter virtualDatacenter = VirtualDatacenter + .builder(env.context.getApiContext(), datacenter, enterprise).name(PREFIX + "Plain Virtual Aloha from VDC") + .cpuCountLimits(18, 20).hdLimitsInMb(279172872, 279172872).publicIpsLimits(2, 2).ramLimits(19456, 20480) + .storageLimits(289910292, 322122547).vlansLimits(1, 2).hypervisorType(hypervisor).network(network).build(); + + virtualDatacenter.save(); + assertNotNull(virtualDatacenter.getId()); + + virtualDatacenter.delete(); + } + + public void testPurchaseIp() { + PublicIp publicIp = env.virtualDatacenter.listAvailablePublicIps().get(0); + assertNotNull(publicIp); + env.virtualDatacenter.purchasePublicIp(publicIp); + + PublicIp apiIp = env.virtualDatacenter.findPurchasedPublicIp(IpPredicates. address(publicIp.getIp())); + assertNotNull(apiIp); + + env.virtualDatacenter.releaseePublicIp(apiIp); + apiIp = env.virtualDatacenter.findPurchasedPublicIp(IpPredicates. address(publicIp.getIp())); + assertNull(apiIp); + } + + public void testGetDefaultNetwork() { + PrivateNetwork network = env.virtualDatacenter.getDefaultNetwork().toPrivateNetwork(); + + assertNotNull(network); + assertEquals(network.getName(), env.privateNetwork.getName()); + assertEquals(network.getType(), env.privateNetwork.getType()); + } + + public void testGetAvailableTemplates() { + List templates = env.virtualDatacenter.listAvailableTemplates(); + assertNotNull(templates); + assertFalse(templates.isEmpty()); + + template = templates.get(0); + } + + @Test(dependsOnMethods = "testGetAvailableTemplates") + public void testFindAvailableTemplate() { + VirtualMachineTemplate templateFound = env.virtualDatacenter + .findAvailableTemplate(VirtualMachineTemplatePredicates.id(template.getId())); + + assertNotNull(template); + assertNotNull(templateFound); + assertEquals(templateFound.getId(), template.getId()); + } + + @Test(dependsOnMethods = "testGetAvailableTemplates") + public void testGetAvailableTemplate() { + VirtualMachineTemplate templateFound = env.virtualDatacenter.getAvailableTemplate(template.getId()); + assertNotNull(templateFound); + assertEquals(templateFound.getId(), template.getId()); + } + +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/cloud/VirtualMachineLiveApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/cloud/VirtualMachineLiveApiTest.java new file mode 100644 index 0000000000..4f867928ef --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/cloud/VirtualMachineLiveApiTest.java @@ -0,0 +1,125 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.cloud; + +import static org.jclouds.abiquo.reference.AbiquoTestConstants.PREFIX; +import static org.jclouds.abiquo.util.Assert.assertHasError; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.fail; + +import java.util.List; + +import javax.ws.rs.core.Response.Status; + +import org.jclouds.abiquo.domain.exception.AbiquoException; +import org.jclouds.abiquo.domain.task.AsyncTask; +import org.jclouds.abiquo.internal.BaseAbiquoApiLiveApiTest; +import org.testng.annotations.Test; + +import com.abiquo.server.core.cloud.VirtualMachineDto; +import com.abiquo.server.core.cloud.VirtualMachineState; + +/** + * Live integration tests for the {@link VirtualMachine} domain class. + * + * @author Francesc Montserrat + */ +@Test(groups = "api", testName = "VirtualMachineLiveApiTest") +public class VirtualMachineLiveApiTest extends BaseAbiquoApiLiveApiTest { + public void testHasDataFromNode() { + assertNotNull(env.virtualMachine.getNameLabel()); + assertNotNull(env.virtualMachine.getInternalName()); + assertNotNull(env.virtualMachine.getOwnerName()); + } + + public void testUpdateInfoFromNode() { + env.virtualMachine.setNameLabel(PREFIX + "-label-updated"); + env.virtualMachine.update(); + env.virtualMachine.refresh(); + + assertEquals(env.virtualMachine.getNameLabel(), PREFIX + "-label-updated"); + } + + public void testGetTasks() { + List tasks = env.virtualMachine.listTasks(); + assertNotNull(tasks); + } + + public void testGetState() { + VirtualMachineState state = env.virtualMachine.getState(); + assertEquals(state, VirtualMachineState.NOT_ALLOCATED); + } + + public void testIsPersistent() { + assertFalse(env.virtualMachine.isPersistent()); + } + + public void testGetVirtualAppliance() { + VirtualAppliance vapp = env.virtualMachine.getVirtualAppliance(); + assertNotNull(vapp); + assertEquals(vapp.getId(), env.virtualAppliance.getId()); + } + + public void testRebootVirtualMachineFailsWhenNotAllocated() { + // Since the virtual machine is not deployed, this should not generate a + // task + + try { + env.virtualMachine.reboot(); + fail("Reboot should have failed for the NOT_ALLOCATED virtual machine"); + } catch (AbiquoException ex) { + assertHasError(ex, Status.CONFLICT, "VM-11"); + } + } + + public void testUpdateForcingLimits() { + int originalHard = env.virtualDatacenter.getCpuCountHardLimit(); + int originalSoft = env.virtualDatacenter.getCpuCountSoftLimit(); + + env.virtualDatacenter.setCpuCountHardLimit(10); + env.virtualDatacenter.setCpuCountSoftLimit(5); + env.virtualDatacenter.update(); + + try { + VirtualMachine vm = env.virtualAppliance.getVirtualMachine(env.virtualMachine.getId()); + vm.setCpu(7); + AsyncTask task = vm.update(true); + + assertNull(task); + assertEquals(vm.getCpu(), 7); + } finally { + env.virtualDatacenter.setCpuCountHardLimit(originalHard); + env.virtualDatacenter.setCpuCountSoftLimit(originalSoft); + env.virtualDatacenter.update(); + } + } + + public void testAttachDvd() { + VirtualMachine vm = VirtualMachine.Builder.fromVirtualMachine(env.virtualMachine).dvd(true).build(); + vm.save(); + + VirtualMachineDto updated = env.cloudApi.getVirtualMachine(env.virtualAppliance.unwrap(), vm.getId()); + + assertNotNull(updated.getDvd()); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/cloud/VirtualMachineNetworkingLiveApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/cloud/VirtualMachineNetworkingLiveApiTest.java new file mode 100644 index 0000000000..6a5e5beb5b --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/cloud/VirtualMachineNetworkingLiveApiTest.java @@ -0,0 +1,219 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.cloud; + +import static org.jclouds.abiquo.util.Assert.assertHasError; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.fail; + +import java.util.List; + +import javax.ws.rs.core.Response.Status; + +import org.jclouds.abiquo.domain.exception.AbiquoException; +import org.jclouds.abiquo.domain.network.ExternalIp; +import org.jclouds.abiquo.domain.network.Ip; +import org.jclouds.abiquo.domain.network.PrivateIp; +import org.jclouds.abiquo.domain.network.PublicIp; +import org.jclouds.abiquo.domain.network.PublicNetwork; +import org.jclouds.abiquo.domain.network.UnmanagedIp; +import org.jclouds.abiquo.domain.network.UnmanagedNetwork; +import org.jclouds.abiquo.domain.task.AsyncTask; +import org.jclouds.abiquo.internal.BaseAbiquoApiLiveApiTest; +import org.jclouds.abiquo.predicates.network.IpPredicates; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import com.google.common.collect.Lists; + +/** + * Live integration tests for the {@link VirtualMachine} networking operations. + * + * @author Ignasi Barrera + */ +@Test(groups = "api", testName = "VirtualMachineNetworkingLiveApiTest") +public class VirtualMachineNetworkingLiveApiTest extends BaseAbiquoApiLiveApiTest { + private PrivateIp privateIp; + + private ExternalIp externalIp; + + private PublicIp publicIpInfrastructure; + + private PublicIp publicIpCloud; + + private UnmanagedIp unmanagedIp1; + + private UnmanagedIp unmanagedIp2; + + @BeforeClass + public void setupIps() { + privateIp = env.privateNetwork.listUnusedIps().get(0); + assertNotNull(privateIp); + + externalIp = env.externalNetwork.listUnusedIps().get(0); + assertNotNull(externalIp); + + publicIpInfrastructure = env.virtualDatacenter.listAvailablePublicIps().get(0); + env.virtualDatacenter.purchasePublicIp(publicIpInfrastructure); + + publicIpCloud = env.virtualDatacenter.findPurchasedPublicIp(IpPredicates + . address(publicIpInfrastructure.getIp())); + assertNotNull(publicIpCloud); + } + + @AfterClass + public void restorePrivateIp() { + AsyncTask task = env.virtualMachine.setNics(Lists.> newArrayList(privateIp)); + assertNull(task); + + List> nics = env.virtualMachine.listAttachedNics(); + assertEquals(nics.size(), 1); + assertEquals(nics.get(0).getId(), privateIp.getId()); + + String address = publicIpCloud.getIp(); + env.virtualDatacenter.releaseePublicIp(publicIpCloud); + assertNull(env.virtualDatacenter.findPurchasedPublicIp(IpPredicates. address(address))); + } + + // TODO: Infrastructure edit link for public ips can not be used to attach + @Test(enabled = false) + public void testAttachInfrastructurePublicIp() { + AsyncTask task = env.virtualMachine.setNics(Lists.> newArrayList(publicIpInfrastructure)); + assertNull(task); + + List> nics = env.virtualMachine.listAttachedNics(); + assertEquals(nics.size(), 1); + assertEquals(nics.get(0).getId(), publicIpInfrastructure.getId()); + } + + public void testAttachPublicIp() { + AsyncTask task = env.virtualMachine.setNics(Lists.> newArrayList(publicIpCloud)); + assertNull(task); + + List> nics = env.virtualMachine.listAttachedNics(); + assertEquals(nics.size(), 1); + assertEquals(nics.get(0).getId(), publicIpCloud.getId()); + } + + @Test(dependsOnMethods = "testAttachPublicIp") + public void testAttachPrivateIp() { + List> nics = env.virtualMachine.listAttachedNics(); + nics.add(privateIp); + + AsyncTask task = env.virtualMachine.setNics(nics); + assertNull(task); + + nics = env.virtualMachine.listAttachedNics(); + assertEquals(nics.size(), 2); + assertEquals(nics.get(0).getId(), publicIpCloud.getId()); + assertEquals(nics.get(1).getId(), privateIp.getId()); + } + + @Test(dependsOnMethods = "testAttachPrivateIp") + public void testAttachExternalIp() { + List> nics = env.virtualMachine.listAttachedNics(); + nics.add(externalIp); + + AsyncTask task = env.virtualMachine.setNics(nics); + assertNull(task); + + nics = env.virtualMachine.listAttachedNics(); + assertEquals(nics.size(), 3); + assertEquals(nics.get(0).getId(), publicIpCloud.getId()); + assertEquals(nics.get(1).getId(), privateIp.getId()); + assertEquals(nics.get(2).getId(), externalIp.getId()); + } + + @Test(dependsOnMethods = "testAttachExternalIp") + public void testAddUnmanagedNics() { + List> nics = env.virtualMachine.listAttachedNics(); + + AsyncTask task = env.virtualMachine.setNics(nics, + Lists. newArrayList(env.unmanagedNetwork, env.unmanagedNetwork)); + assertNull(task); + + nics = env.virtualMachine.listAttachedNics(); + assertEquals(nics.size(), 5); + assertEquals(nics.get(0).getId(), publicIpCloud.getId()); + assertEquals(nics.get(1).getId(), privateIp.getId()); + assertEquals(nics.get(2).getId(), externalIp.getId()); + // Unmanaged ips are created during the attach. + assertEquals(nics.get(3).getNetworkName(), env.unmanagedNetwork.getName()); + assertEquals(nics.get(4).getNetworkName(), env.unmanagedNetwork.getName()); + + unmanagedIp1 = (UnmanagedIp) nics.get(3); + unmanagedIp2 = (UnmanagedIp) nics.get(4); + } + + @Test(dependsOnMethods = "testAddUnmanagedNics") + public void testReorderNics() { + List> nics = env.virtualMachine.listAttachedNics(); + + AsyncTask task = env.virtualMachine.setNics(Lists.> newArrayList(nics.get(2), nics.get(1), nics.get(0), + nics.get(4), nics.get(3))); + assertNull(task); + + nics = env.virtualMachine.listAttachedNics(); + assertEquals(nics.size(), 5); + assertEquals(nics.get(0).getId(), externalIp.getId()); + assertEquals(nics.get(1).getId(), privateIp.getId()); + assertEquals(nics.get(2).getId(), publicIpCloud.getId()); + assertEquals(nics.get(3).getId(), unmanagedIp2.getId()); + assertEquals(nics.get(4).getId(), unmanagedIp1.getId()); + } + + @Test(dependsOnMethods = "testReorderNics") + public void testDetachNics() { + List> nics = env.virtualMachine.listAttachedNics(); + + AsyncTask task = env.virtualMachine.setNics(Lists.> newArrayList(nics.get(1), nics.get(2))); + assertNull(task); + + nics = env.virtualMachine.listAttachedNics(); + assertEquals(nics.size(), 2); + assertEquals(nics.get(0).getId(), privateIp.getId()); + assertEquals(nics.get(1).getId(), publicIpCloud.getId()); + } + + @Test(dependsOnMethods = "testDetachNics") + public void testSetDefaultGateway() { + PublicNetwork network = publicIpCloud.getNetwork(); + env.virtualMachine.setGatewayNetwork(network); + + Integer configId = env.virtualMachine.unwrap().getIdFromLink("network_configuration"); + assertEquals(configId, network.getId()); + } + + // TODO: Review this functionality + @Test(dependsOnMethods = "testSetDefaultGateway", enabled = false) + public void testDetachAllNics() { + try { + env.virtualMachine.setNics(null); + + fail("It should not be allowed to remove all nics from a vm"); + } catch (AbiquoException ex) { + // At least one nic must be configured + assertHasError(ex, Status.BAD_REQUEST, "VM-46"); + } + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/cloud/VirtualMachineStorageLiveApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/cloud/VirtualMachineStorageLiveApiTest.java new file mode 100644 index 0000000000..99f694989f --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/cloud/VirtualMachineStorageLiveApiTest.java @@ -0,0 +1,149 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.cloud; + +import static org.jclouds.abiquo.reference.AbiquoTestConstants.PREFIX; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertTrue; + +import java.util.List; + +import org.jclouds.abiquo.domain.infrastructure.Tier; +import org.jclouds.abiquo.domain.task.AsyncTask; +import org.jclouds.abiquo.internal.BaseAbiquoApiLiveApiTest; +import org.jclouds.abiquo.predicates.infrastructure.TierPredicates; +import org.testng.annotations.Test; + +/** + * Live integration tests for the {@link VirtualMachine} storage operations. + * + * @author Francesc Montserrat + */ +@Test(groups = "api", testName = "VirtualMachineStorageLiveApiTest") +public class VirtualMachineStorageLiveApiTest extends BaseAbiquoApiLiveApiTest { + private Volume volume; + + private HardDisk hardDisk; + + public void testAttachVolumes() { + volume = createVolume(); + + // Since the virtual machine is not deployed, this should not generate a + // task + AsyncTask task = env.virtualMachine.attachVolumes(volume); + assertNull(task); + + List attached = env.virtualMachine.listAttachedVolumes(); + assertEquals(attached.size(), 1); + assertEquals(attached.get(0).getId(), volume.getId()); + } + + @Test(dependsOnMethods = "testAttachVolumes") + public void detachVolume() { + env.virtualMachine.detachVolumes(volume); + List attached = env.virtualMachine.listAttachedVolumes(); + assertTrue(attached.isEmpty()); + } + + @Test(dependsOnMethods = "detachVolume") + public void detachAllVolumes() { + // Since the virtual machine is not deployed, this should not generate a + // task + AsyncTask task = env.virtualMachine.attachVolumes(volume); + assertNull(task); + + env.virtualMachine.detachAllVolumes(); + List attached = env.virtualMachine.listAttachedVolumes(); + assertTrue(attached.isEmpty()); + + deleteVolume(volume); + } + + public void testAttachHardDisks() { + hardDisk = createHardDisk(); + + // Since the virtual machine is not deployed, this should not generate a + // task + AsyncTask task = env.virtualMachine.attachHardDisks(hardDisk); + assertNull(task); + + List attached = env.virtualMachine.listAttachedHardDisks(); + assertEquals(attached.size(), 1); + assertEquals(attached.get(0).getId(), hardDisk.getId()); + } + + @Test(dependsOnMethods = "testAttachHardDisks") + public void detachHardDisk() { + env.virtualMachine.detachHardDisks(hardDisk); + List attached = env.virtualMachine.listAttachedHardDisks(); + assertTrue(attached.isEmpty()); + } + + @Test(dependsOnMethods = "detachHardDisk") + public void detachAllHardDisks() { + // Since the virtual machine is not deployed, this should not generate a + // task + AsyncTask task = env.virtualMachine.attachHardDisks(hardDisk); + assertNull(task); + + env.virtualMachine.detachAllHardDisks(); + List attached = env.virtualMachine.listAttachedHardDisks(); + assertTrue(attached.isEmpty()); + + deleteHardDisk(hardDisk); + } + + private Volume createVolume() { + Tier tier = env.virtualDatacenter.findStorageTier(TierPredicates.name(env.tier.getName())); + + Volume volume = Volume.builder(env.context.getApiContext(), env.virtualDatacenter, tier) + .name(PREFIX + "Hawaian volume").sizeInMb(32).build(); + volume.save(); + + assertNotNull(volume.getId()); + assertNotNull(env.virtualDatacenter.getVolume(volume.getId())); + + return volume; + } + + private void deleteVolume(final Volume volume) { + Integer id = volume.getId(); + volume.delete(); + assertNull(env.virtualDatacenter.getVolume(id)); + } + + private HardDisk createHardDisk() { + HardDisk hardDisk = HardDisk.builder(env.context.getApiContext(), env.virtualDatacenter).sizeInMb(64L).build(); + hardDisk.save(); + + assertNotNull(hardDisk.getId()); + assertNotNull(hardDisk.getSequence()); + + return hardDisk; + } + + private void deleteHardDisk(final HardDisk hardDisk) { + Integer id = hardDisk.getId(); + hardDisk.delete(); + assertNull(env.virtualDatacenter.getHardDisk(id)); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/cloud/VirtualMachineTemplateLiveApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/cloud/VirtualMachineTemplateLiveApiTest.java new file mode 100644 index 0000000000..1ed86cbf88 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/cloud/VirtualMachineTemplateLiveApiTest.java @@ -0,0 +1,63 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.cloud; + +import static org.jclouds.abiquo.util.Assert.assertHasError; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.fail; + +import javax.ws.rs.core.Response.Status; + +import org.jclouds.abiquo.domain.config.Category; +import org.jclouds.abiquo.domain.exception.AbiquoException; +import org.jclouds.abiquo.domain.infrastructure.Datacenter; +import org.jclouds.abiquo.internal.BaseAbiquoApiLiveApiTest; +import org.testng.annotations.Test; + +/** + * Live integration tests for the {@link VirtualMachineTemplate} domain class. + * + * @author Francesc Montserrat + */ +@Test(groups = "api", testName = "VirtualMachineTemplateLiveApiTest") +public class VirtualMachineTemplateLiveApiTest extends BaseAbiquoApiLiveApiTest { + + public void testGetParent() { + Datacenter datacenter = env.virtualMachine.getTemplate().getDatacenter(); + assertNotNull(datacenter); + assertEquals(datacenter.getId(), env.datacenter.getId()); + } + + public void testGetCategory() { + Category category = env.virtualMachine.getTemplate().getCategory(); + assertNotNull(category); + } + + public void testRequestConversionToSameFormat() { + try { + env.virtualMachine.getTemplate().requestConversion(env.virtualMachine.getTemplate().getDiskFormatType()); + fail("Should not be able to create create a conversion to the base format"); + } catch (AbiquoException ex) { + assertHasError(ex, Status.CONFLICT, "CONVERSION-3"); + } + } + +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/cloud/VolumeLiveApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/cloud/VolumeLiveApiTest.java new file mode 100644 index 0000000000..ccce353d67 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/cloud/VolumeLiveApiTest.java @@ -0,0 +1,130 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.cloud; + +import static org.jclouds.abiquo.reference.AbiquoTestConstants.PREFIX; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertTrue; + +import java.util.List; + +import org.jclouds.abiquo.domain.cloud.options.VolumeOptions; +import org.jclouds.abiquo.domain.infrastructure.Tier; +import org.jclouds.abiquo.domain.network.PrivateNetwork; +import org.jclouds.abiquo.domain.task.AsyncTask; +import org.jclouds.abiquo.internal.BaseAbiquoApiLiveApiTest; +import org.jclouds.abiquo.predicates.cloud.VolumePredicates; +import org.jclouds.abiquo.predicates.infrastructure.TierPredicates; +import org.testng.annotations.Test; + +import com.abiquo.server.core.infrastructure.storage.VolumeManagementDto; + +/** + * Live integration tests for the {@link Volume} domain class. + * + * @author Ignasi Barrera + */ +@Test(groups = "api", testName = "VolumeLiveApiTest") +public class VolumeLiveApiTest extends BaseAbiquoApiLiveApiTest { + public void testCreateVolume() { + // We need the vdc-relative tier + Tier tier = env.virtualDatacenter.findStorageTier(TierPredicates.name(env.tier.getName())); + + Volume volume = Volume.builder(env.context.getApiContext(), env.virtualDatacenter, tier) + .name(PREFIX + "Hawaian volume").sizeInMb(32).build(); + volume.save(); + + assertNotNull(volume.getId()); + assertNotNull(env.virtualDatacenter.getVolume(volume.getId())); + } + + @Test(dependsOnMethods = "testCreateVolume") + public void testFilterVolumes() { + VolumeOptions validOptions = VolumeOptions.builder().has("hawa").build(); + VolumeOptions invalidOptions = VolumeOptions.builder().has("cacatua").build(); + + List volumes = env.cloudApi.listVolumes(env.virtualDatacenter.unwrap(), validOptions) + .getCollection(); + + assertEquals(volumes.size(), 1); + + volumes = env.cloudApi.listVolumes(env.virtualDatacenter.unwrap(), invalidOptions).getCollection(); + + assertEquals(volumes.size(), 0); + } + + @Test(dependsOnMethods = "testFilterVolumes") + public void testUpdateVolume() { + Volume volume = env.virtualDatacenter.findVolume(VolumePredicates.name(PREFIX + "Hawaian volume")); + assertNotNull(volume); + + volume.setName("Hawaian volume updated"); + AsyncTask task = volume.update(); + assertNull(task); + + // Reload the volume to check + Volume updated = env.virtualDatacenter.getVolume(volume.getId()); + assertEquals(updated.getName(), "Hawaian volume updated"); + } + + @Test(dependsOnMethods = "testUpdateVolume") + public void testMoveVolume() { + // Create the new virtual datacenter + PrivateNetwork network = PrivateNetwork.builder(env.context.getApiContext()).name("DefaultNetwork") + .gateway("192.168.1.1").address("192.168.1.0").mask(24).build(); + + VirtualDatacenter newVdc = VirtualDatacenter.builder(env.context.getApiContext(), env.datacenter, env.enterprise) + .name("New VDC").network(network).hypervisorType(env.machine.getType()).build(); + newVdc.save(); + assertNotNull(newVdc.getId()); + + Volume volume = env.virtualDatacenter.findVolume(VolumePredicates.name("Hawaian volume updated")); + assertNotNull(volume); + + volume.moveTo(newVdc); + + // Check that the underlying Dto has been updated to the new VDC + assertTrue(volume.unwrap().getEditLink().getHref().startsWith(newVdc.unwrap().getEditLink().getHref())); + + // Move it back to the original VDC + volume.moveTo(env.virtualDatacenter); + + // Check that the underlying Dto has been updated to the new VDC + assertTrue(volume.unwrap().getEditLink().getHref() + .startsWith(env.virtualDatacenter.unwrap().getEditLink().getHref())); + + // Tear down the virtual datacenter + newVdc.delete(); + } + + @Test(dependsOnMethods = "testMoveVolume") + public void testDeleteVolume() { + Volume volume = env.virtualDatacenter.findVolume(VolumePredicates.name("Hawaian volume updated")); + assertNotNull(volume); + + Integer id = volume.getId(); + volume.delete(); + + assertNull(env.virtualDatacenter.getVolume(id)); + } + +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/config/CategoryLiveApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/config/CategoryLiveApiTest.java new file mode 100644 index 0000000000..4cb31b829e --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/config/CategoryLiveApiTest.java @@ -0,0 +1,69 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.config; + +import static org.jclouds.abiquo.reference.AbiquoTestConstants.PREFIX; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; + +import org.jclouds.abiquo.internal.BaseAbiquoApiLiveApiTest; +import org.jclouds.abiquo.predicates.config.CategoryPredicates; +import org.testng.annotations.Test; + +/** + * Live integration tests for the {@link Category} domain class. + * + * @author Francesc Montserrat + */ +@Test(groups = "api", testName = "CategoryLiveApiTest") +public class CategoryLiveApiTest extends BaseAbiquoApiLiveApiTest { + public void testCreateAndGet() { + Category category = Category.builder(env.context.getApiContext()).name(PREFIX + "-test-category").build(); + category.save(); + + Category apiCategory = env.context.getAdministrationService().findCategory( + CategoryPredicates.name(PREFIX + "-test-category")); + assertNotNull(apiCategory); + assertEquals(category.getName(), apiCategory.getName()); + + apiCategory.delete(); + } + + @Test(dependsOnMethods = "testCreateAndGet") + public void testUpdate() { + Iterable categories = env.context.getAdministrationService().listCategories(); + assertNotNull(categories); + + Category category = categories.iterator().next(); + String name = category.getName(); + + category.setName(PREFIX + "-test-category-updated"); + category.update(); + + Category apiCategory = env.context.getAdministrationService().findCategory( + CategoryPredicates.name(PREFIX + "-test-category-updated")); + + assertNotNull(apiCategory); + assertEquals(PREFIX + "-test-category-updated", apiCategory.getName()); + + category.setName(name); + category.update(); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/config/CostCodeLiveApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/config/CostCodeLiveApiTest.java new file mode 100644 index 0000000000..1de82a9386 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/config/CostCodeLiveApiTest.java @@ -0,0 +1,128 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.config; + +import static org.jclouds.abiquo.reference.AbiquoTestConstants.PREFIX; +import static org.jclouds.abiquo.util.Assert.assertHasError; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.fail; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + +import javax.ws.rs.core.Response.Status; + +import org.jclouds.abiquo.domain.exception.AbiquoException; +import org.jclouds.abiquo.internal.BaseAbiquoApiLiveApiTest; +import org.jclouds.abiquo.predicates.config.PricingPredicates; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +/** + * Live integration tests for the {@link CostCode} domain class. + * + * @author Susana Acedo + */ +@Test(groups = "api", testName = "CostCodeLiveApiTest") +public class CostCodeLiveApiTest extends BaseAbiquoApiLiveApiTest { + private CostCode costcode; + + private Currency currency; + + private CostCodePrice costcodeprice; + + private List defaultPrices; + + @BeforeClass + public void setupCostCode() { + currency = Currency.builder(env.context.getApiContext()).name(PREFIX + "test-currency").symbol("test-$") + .digits(2).build(); + currency.save(); + + costcode = CostCode.builder(env.context.getApiContext()).name(PREFIX + "test-costcode") + .description("description").build(); + + costcode.save(); + } + + @AfterClass + public void tearDownCostCode() { + currency.delete(); + costcode.delete(); + } + + public void testCreateRepeated() { + CostCode repeated = CostCode.Builder.fromCostCode(costcode).build(); + + try { + repeated.save(); + fail("Should not be able to create costcodes with the same name"); + } catch (AbiquoException ex) { + assertHasError(ex, Status.CONFLICT, "COSTCODE-2"); + } + } + + public void testUpdate() { + costcode.setName(PREFIX + "costcode-updated"); + costcode.update(); + + CostCode apiCostCode = env.context.getPricingService().findCostCode( + PricingPredicates.costCode(PREFIX + "costcode-updated")); + + assertNotNull(apiCostCode); + assertEquals(PREFIX + "costcode-updated", apiCostCode.getName()); + + } + + public void testCreateCostCodewithDefaultPrices() { + CostCode costcode2 = CostCode.builder(env.context.getApiContext()).name(PREFIX + "ccdefaultprice") + .description("description").build(); + + costcodeprice = new CostCodePrice(currency, new BigDecimal(100)); + this.defaultPrices = new ArrayList(); + defaultPrices.add(costcodeprice); + costcode2.setDefaultPrices(defaultPrices); + // When a cost code is created it is also created a costcodecurrency with + // price 0 and after + // that if a list of prices(CostCodePrice) has been sent this costcode is + // updated with the + // new price + costcode2.save(); + + // check that costcode has been created + CostCode apiCostCode = env.context.getPricingService().findCostCode( + PricingPredicates.costCode(PREFIX + "ccdefaultprice")); + + assertNotNull(apiCostCode); + assertEquals(PREFIX + "ccdefaultprice", apiCostCode.getName()); + + // check that the price has been modified in the + Iterable costcodecurrencies = env.context.getPricingService().getCostCodeCurrencies( + costcode2.getId(), currency.getId()); + for (CostCodeCurrency costcodecurrency : costcodecurrencies) { + assertEquals(costcodecurrency.getPrice().compareTo(new BigDecimal(100)), 0); + } + + costcode2.delete(); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/config/CurrencyLiveApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/config/CurrencyLiveApiTest.java new file mode 100644 index 0000000000..c2626b1326 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/config/CurrencyLiveApiTest.java @@ -0,0 +1,70 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.config; + +import static org.jclouds.abiquo.reference.AbiquoTestConstants.PREFIX; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; + +import org.jclouds.abiquo.internal.BaseAbiquoApiLiveApiTest; +import org.jclouds.abiquo.predicates.config.PricingPredicates; +import org.testng.annotations.Test; + +/** + * Live integration tests for the {@link Currency} domain class. + * + * @author Susana Acedo + */ +@Test(groups = "api", testName = "CurrencyLiveApiTest") +public class CurrencyLiveApiTest extends BaseAbiquoApiLiveApiTest { + public void testCreateAndGet() { + Currency currency = Currency.builder(env.context.getApiContext()).name(PREFIX + "test-currency").symbol("test-$") + .digits(2).build(); + currency.save(); + + Currency apiCurrency = env.context.getPricingService().findCurrency( + PricingPredicates.currency(PREFIX + "test-currency")); + assertNotNull(apiCurrency); + assertEquals(currency.getName(), apiCurrency.getName()); + + apiCurrency.delete(); + } + + @Test(dependsOnMethods = "testCreateAndGet") + public void testUpdate() { + Iterable currencies = env.context.getPricingService().listCurrencies(); + assertNotNull(currencies); + + Currency currency = currencies.iterator().next(); + String name = currency.getName(); + + currency.setName(PREFIX + "t-currency-upd"); + currency.update(); + + Currency apiCurrency = env.context.getPricingService().findCurrency( + PricingPredicates.currency(PREFIX + "t-currency-upd")); + + assertNotNull(apiCurrency); + assertEquals(PREFIX + "t-currency-upd", apiCurrency.getName()); + + currency.setName(name); + currency.update(); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/config/LicenseLiveApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/config/LicenseLiveApiTest.java new file mode 100644 index 0000000000..e10a123fa5 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/config/LicenseLiveApiTest.java @@ -0,0 +1,50 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.config; + +import static org.jclouds.abiquo.util.Assert.assertHasError; +import static org.testng.Assert.fail; + +import javax.ws.rs.core.Response.Status; + +import org.jclouds.abiquo.domain.enterprise.User; +import org.jclouds.abiquo.domain.exception.AbiquoException; +import org.jclouds.abiquo.internal.BaseAbiquoApiLiveApiTest; +import org.testng.annotations.Test; + +/** + * Live integration tests for the {@link User} domain class. + * + * @author Francesc Montserrat + */ +@Test(groups = "api", testName = "LicenseLiveApiTest") +public class LicenseLiveApiTest extends BaseAbiquoApiLiveApiTest { + + public void testCreateRepeated() { + License repeated = License.Builder.fromLicense(env.license).build(); + + try { + repeated.add(); + fail("Should not be able to create licenses with the same code"); + } catch (AbiquoException ex) { + assertHasError(ex, Status.CONFLICT, "LICENSE-5"); + } + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/config/PricingTemplateLiveApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/config/PricingTemplateLiveApiTest.java new file mode 100644 index 0000000000..470f1d36b3 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/config/PricingTemplateLiveApiTest.java @@ -0,0 +1,131 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.config; + +import static org.jclouds.abiquo.reference.AbiquoTestConstants.PREFIX; +import static org.jclouds.abiquo.util.Assert.assertHasError; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.fail; + +import java.math.BigDecimal; +import java.util.Collection; +import java.util.Date; + +import javax.ws.rs.core.Response.Status; + +import org.jclouds.abiquo.domain.exception.AbiquoException; +import org.jclouds.abiquo.internal.BaseAbiquoApiLiveApiTest; +import org.jclouds.abiquo.predicates.config.PricingPredicates; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import com.abiquo.model.enumerator.PricingPeriod; + +/** + * Live integration tests for the {@link PricingTemplate} domain class. + * + * @author Susana Acedo + */ +@Test(groups = "api", testName = "PricingTemplateLiveApiTest") +public class PricingTemplateLiveApiTest extends BaseAbiquoApiLiveApiTest { + private PricingTemplate pricingTemplate; + + private Currency currency; + + private CostCode costcode; + + private BigDecimal zero = new BigDecimal(0); + + @BeforeClass + public void setupPricingTemplate() { + Iterable currencies = env.context.getPricingService().listCurrencies(); + currency = currencies.iterator().next(); + + costcode = CostCode.builder(env.context.getApiContext()).name(PREFIX + "test-costcode") + .description("description").build(); + + costcode.save(); + + pricingTemplate = PricingTemplate.builder(env.context.getApiContext(), currency).name("pricing_template") + .description("description").hdGB(zero).standingChargePeriod(zero).vlan(zero) + .chargingPeriod(PricingPeriod.MONTH).minimumChargePeriod(zero).showChangesBefore(true) + .showMinimumCharge(false).minimumCharge(PricingPeriod.WEEK).publicIp(zero).vcpu(zero).memoryGB(zero) + .defaultTemplate(true).lastUpdate(new Date()).build(); + + pricingTemplate.save(); + } + + @AfterClass + public void tearDownPricingTemplate() { + pricingTemplate.delete(); + costcode.delete(); + } + + public void testCreateRepeated() { + PricingTemplate repeated = PricingTemplate.Builder.fromPricingTemplate(pricingTemplate).build(); + + try { + repeated.save(); + fail("Should not be able to create pricingtemplates with the same name"); + } catch (AbiquoException ex) { + assertHasError(ex, Status.CONFLICT, "PRICINGTEMPLATE-2"); + } + } + + public void testUpdate() { + pricingTemplate.setName(PREFIX + "pt-updated"); + pricingTemplate.update(); + + PricingTemplate apiPricingTemplate = env.context.getPricingService().findPricingTemplate( + PricingPredicates.pricingTemplate(PREFIX + "pt-updated")); + + assertNotNull(apiPricingTemplate); + assertEquals(PREFIX + "pt-updated", apiPricingTemplate.getName()); + + } + + // when a pricing template is created, pricing cost codes for each existent + // cost code are also + // created with price 0 + public void getPricingCostCodes() { + Collection pricingCostCodes = env.context.getPricingService().getPricingCostCodes( + pricingTemplate.getId()); + assertEquals(pricingCostCodes.size(), 1); + assertNotNull(pricingCostCodes); + for (PricingCostCode pc : pricingCostCodes) { + assertEquals(pc.getPrice().compareTo(zero), 0); + } + } + + // when a pricing template is created, pricing tiers are also created with + // price 0 + public void getPricingTiers() { + Collection pricingTiers = + + env.context.getPricingService().getPricingTiers(pricingTemplate.getId()); + assertEquals(pricingTiers.size(), 4); + assertNotNull(pricingTiers); + for (PricingTier pt : pricingTiers) { + assertEquals(pt.getPrice().compareTo(zero), 0); + } + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/config/SystemPropertiesLiveApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/config/SystemPropertiesLiveApiTest.java new file mode 100644 index 0000000000..6546d6730f --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/config/SystemPropertiesLiveApiTest.java @@ -0,0 +1,50 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.config; + +import static org.testng.Assert.assertEquals; + +import org.jclouds.abiquo.domain.enterprise.User; +import org.jclouds.abiquo.internal.BaseAbiquoApiLiveApiTest; +import org.testng.annotations.Test; + +/** + * Live integration tests for the {@link User} domain class. + * + * @author Francesc Montserrat + */ +@Test(groups = "api", testName = "SystemPropertiesLiveApiTest") +public class SystemPropertiesLiveApiTest extends BaseAbiquoApiLiveApiTest { + public void testUpdate() { + SystemProperty prop = env.administrationService.getSystemProperty("client.dashboard.showStartUpAlert"); + + String value = prop.getValue(); + prop.setValue("0"); + prop.update(); + + // Recover the updated datacenter + SystemProperty updated = env.administrationService.getSystemProperty("client.dashboard.showStartUpAlert"); + + assertEquals(updated.getValue(), "0"); + + prop.setValue(value); + prop.update(); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/enterprise/EnterpriseLiveApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/enterprise/EnterpriseLiveApiTest.java new file mode 100644 index 0000000000..fdaa4d5cc4 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/enterprise/EnterpriseLiveApiTest.java @@ -0,0 +1,168 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.enterprise; + +import static org.jclouds.abiquo.reference.AbiquoTestConstants.PREFIX; +import static org.jclouds.abiquo.util.Assert.assertHasError; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertTrue; +import static org.testng.Assert.fail; + +import java.util.List; + +import javax.ws.rs.core.Response.Status; + +import org.jclouds.abiquo.domain.cloud.VirtualAppliance; +import org.jclouds.abiquo.domain.cloud.VirtualMachine; +import org.jclouds.abiquo.domain.enterprise.Enterprise.Builder; +import org.jclouds.abiquo.domain.exception.AbiquoException; +import org.jclouds.abiquo.domain.infrastructure.Datacenter; +import org.jclouds.abiquo.internal.BaseAbiquoApiLiveApiTest; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import com.abiquo.server.core.enterprise.DatacentersLimitsDto; +import com.abiquo.server.core.enterprise.EnterpriseDto; + +/** + * Live integration tests for the {@link Enterprise} domain class. + * + * @author Ignasi Barrera + */ +@Test(groups = "api", testName = "EnterpriseLiveApiTest") +public class EnterpriseLiveApiTest extends BaseAbiquoApiLiveApiTest { + private Enterprise enterprise; + + private Limits limits; + + @BeforeClass + public void setupEnterprise() { + enterprise = Enterprise.Builder.fromEnterprise(env.enterprise).build(); + enterprise.setName(PREFIX + "-enterprise-test"); + enterprise.save(); + + limits = enterprise.allowDatacenter(env.datacenter); + assertNotNull(limits); + + DatacentersLimitsDto limitsDto = env.enterpriseApi.getLimits(enterprise.unwrap(), env.datacenter.unwrap()); + assertNotNull(limitsDto); + assertEquals(limitsDto.getCollection().size(), 1); + } + + @AfterClass + public void tearDownEnterprise() { + enterprise.prohibitDatacenter(env.datacenter); + + try { + // If a datacenter is not allowed, the limits for it can not be + // retrieved + env.enterpriseApi.getLimits(enterprise.unwrap(), env.datacenter.unwrap()); + } catch (AbiquoException ex) { + assertHasError(ex, Status.CONFLICT, "ENTERPRISE-10"); + } + + List allowed = enterprise.listAllowedDatacenters(); + assertNotNull(allowed); + assertTrue(allowed.isEmpty()); + + enterprise.delete(); + } + + public void testUpdate() { + enterprise.setName("Updated Enterprise"); + enterprise.update(); + + // Recover the updated enterprise + EnterpriseDto updated = env.enterpriseApi.getEnterprise(enterprise.getId()); + + assertEquals(updated.getName(), "Updated Enterprise"); + } + + public void testCreateRepeated() { + Enterprise repeated = Builder.fromEnterprise(enterprise).build(); + + try { + repeated.save(); + fail("Should not be able to create enterprises with the same name"); + } catch (AbiquoException ex) { + assertHasError(ex, Status.CONFLICT, "ENTERPRISE-4"); + } + } + + public void testAllowTwiceWorks() { + // Allow the datacenter again and check that the configuration has not + // changed + Limits limits = enterprise.allowDatacenter(env.datacenter); + assertNotNull(limits); + + DatacentersLimitsDto limitsDto = env.enterpriseApi.getLimits(enterprise.unwrap(), env.datacenter.unwrap()); + assertNotNull(limitsDto); + assertEquals(limitsDto.getCollection().size(), 1); + } + + public void testListLimits() { + List allLimits = enterprise.listLimits(); + assertNotNull(allLimits); + assertEquals(allLimits.size(), 1); + } + + public void testUpdateInvalidLimits() { + // CPU soft remains to 0 => conflict because hard is smaller + limits.setCpuCountHardLimit(2); + + try { + limits.update(); + } catch (AbiquoException ex) { + assertHasError(ex, Status.BAD_REQUEST, "CONSTR-LIMITRANGE"); + } + } + + public void testUpdateLimits() { + limits.setCpuCountLimits(4, 5); + limits.update(); + + DatacentersLimitsDto limitsDto = env.enterpriseApi.getLimits(enterprise.unwrap(), env.datacenter.unwrap()); + assertNotNull(limitsDto); + assertEquals(limitsDto.getCollection().size(), 1); + assertEquals(limitsDto.getCollection().get(0).getCpuCountHardLimit(), 5); + assertEquals(limitsDto.getCollection().get(0).getCpuCountSoftLimit(), 4); + } + + public void testListAllowedDatacenters() { + List allowed = enterprise.listAllowedDatacenters(); + + assertNotNull(allowed); + assertFalse(allowed.isEmpty()); + assertEquals(allowed.get(0).getId(), env.datacenter.getId()); + } + + public void testListVirtualMachines() { + List machines = env.defaultEnterprise.listVirtualMachines(); + assertTrue(machines.size() > 0); + } + + public void testListVirtualAppliances() { + List vapps = env.defaultEnterprise.listVirtualAppliances(); + assertTrue(vapps.size() > 0); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/enterprise/EnterprisePropertiesLiveApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/enterprise/EnterprisePropertiesLiveApiTest.java new file mode 100644 index 0000000000..9e3b4c45ed --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/enterprise/EnterprisePropertiesLiveApiTest.java @@ -0,0 +1,52 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.enterprise; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertTrue; + +import org.jclouds.abiquo.internal.BaseAbiquoApiLiveApiTest; +import org.testng.annotations.Test; + +import com.abiquo.server.core.enterprise.EnterprisePropertiesDto; + +/** + * Live integration tests for the {@link Enterprise} domain class. + * + * @author Ignasi Barrera + */ +@Test(groups = "api", testName = "EnterprisePropertiesLiveApiTest") +public class EnterprisePropertiesLiveApiTest extends BaseAbiquoApiLiveApiTest { + + public void testUpdate() { + EnterpriseProperties properties = env.administrationService.getEnterpriseProperties(env.enterprise); + + Integer size = properties.getProperties().size(); + properties.getProperties().put("Prop", "Value"); + properties.update(); + + // Recover the updated properties + EnterprisePropertiesDto updated = env.enterpriseApi.getEnterpriseProperties(env.enterprise.unwrap()); + + assertEquals(updated.getProperties().size(), size + 1); + assertTrue(updated.getProperties().containsKey("Prop")); + assertTrue(updated.getProperties().containsValue("Value")); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/enterprise/TemplateDefinitionListLiveApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/enterprise/TemplateDefinitionListLiveApiTest.java new file mode 100644 index 0000000000..7be86b98a2 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/enterprise/TemplateDefinitionListLiveApiTest.java @@ -0,0 +1,74 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.enterprise; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; + +import java.util.List; + +import org.jclouds.abiquo.internal.BaseAbiquoApiLiveApiTest; +import org.jclouds.abiquo.predicates.enterprise.TemplateDefinitionListPredicates; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +/** + * Live integration tests for the {@link TemplateDefinitionList} domain class. + * + * @author Francesc Montserrat + */ +@Test(groups = "api", testName = "TemplateDefinitionListLiveApiTest") +public class TemplateDefinitionListLiveApiTest extends BaseAbiquoApiLiveApiTest { + private TemplateDefinitionList list; + + public void testUpdate() { + list.setName(list.getName() + "Updated"); + list.update(); + + List lists = env.enterprise.listTemplateDefinitionLists(TemplateDefinitionListPredicates + .name("myListUpdated")); + + assertEquals(lists.size(), 1); + } + + public void testListStates() { + List states = list.listStatus(env.datacenter); + assertNotNull(states); + } + + @BeforeClass + public void setup() { + list = TemplateDefinitionList.builder(env.context.getApiContext(), env.enterprise).name("myList") + .url("http://virtualapp-repository.com/vapp1.ovf").build(); + + list.save(); + + assertNotNull(list.getId()); + } + + @AfterClass + public void tearDown() { + Integer idTemplateList = list.getId(); + list.delete(); + assertNull(env.enterprise.getTemplateDefinitionList(idTemplateList)); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/enterprise/UserLiveApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/enterprise/UserLiveApiTest.java new file mode 100644 index 0000000000..88b096010d --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/enterprise/UserLiveApiTest.java @@ -0,0 +1,100 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.enterprise; + +import static org.jclouds.abiquo.predicates.enterprise.UserPredicates.nick; +import static org.jclouds.abiquo.util.Assert.assertHasError; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.fail; + +import javax.ws.rs.core.Response.Status; + +import org.jclouds.abiquo.domain.exception.AbiquoException; +import org.jclouds.abiquo.internal.BaseAbiquoApiLiveApiTest; +import org.jclouds.abiquo.predicates.enterprise.UserPredicates; +import org.testng.annotations.Test; + +import com.abiquo.server.core.enterprise.UserDto; +import com.google.common.collect.Iterables; + +/** + * Live integration tests for the {@link User} domain class. + * + * @author Francesc Montserrat + */ +@Test(groups = "api", testName = "UserLiveApiTest") +public class UserLiveApiTest extends BaseAbiquoApiLiveApiTest { + + public void testUpdate() { + String username = env.user.getName(); + env.user.setName("Manolo"); + env.user.update(); + + // Recover the updated user + UserDto updated = env.enterpriseApi.getUser(env.enterprise.unwrap(), env.user.getId()); + + assertEquals(updated.getName(), "Manolo"); + + env.user.setName(username); + env.user.update(); + } + + public void testCreateRepeated() { + User repeated = User.Builder.fromUser(env.user).build(); + + try { + repeated.save(); + fail("Should not be able to create users with the same nick"); + } catch (AbiquoException ex) { + assertHasError(ex, Status.CONFLICT, "USER-4"); + } + } + + public void testChangeRoleAndUpdate() { + env.user.setRole(env.anotherRole); + env.user.update(); + + Role role2 = env.enterprise.findUser(UserPredicates.nick(env.user.getNick())).getRole(); + + assertEquals(env.anotherRole.getId(), role2.getId()); + assertEquals(role2.getName(), "Another role"); + + env.user.setRole(env.role); + env.user.update(); + } + + public void testListUser() { + Iterable users = env.enterprise.listUsers(); + assertEquals(Iterables.size(users), 2); + + users = env.enterprise.listUsers(nick(env.user.getNick())); + assertEquals(Iterables.size(users), 1); + + users = env.enterprise.listUsers(nick(env.user.getName() + "FAIL")); + assertEquals(Iterables.size(users), 0); + } + + public void testGetCurrentUser() { + User user = env.context.getAdministrationService().getCurrentUser(); + assertNotNull(user); + assertEquals(user.getNick(), env.context.getApiContext().getIdentity()); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/event/EventLiveApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/event/EventLiveApiTest.java new file mode 100644 index 0000000000..91c22b0afc --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/event/EventLiveApiTest.java @@ -0,0 +1,244 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.event; + +import static org.jclouds.abiquo.reference.AbiquoTestConstants.PREFIX; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertTrue; + +import java.util.Date; +import java.util.UUID; + +import org.jclouds.abiquo.domain.cloud.VirtualMachine; +import org.jclouds.abiquo.domain.cloud.Volume; +import org.jclouds.abiquo.domain.enterprise.User; +import org.jclouds.abiquo.domain.event.options.EventOptions; +import org.jclouds.abiquo.domain.infrastructure.Tier; +import org.jclouds.abiquo.internal.BaseAbiquoApiLiveApiTest; +import org.jclouds.abiquo.predicates.infrastructure.TierPredicates; +import org.testng.annotations.Test; + +import com.abiquo.model.enumerator.ComponentType; +import com.abiquo.model.enumerator.EventType; +import com.abiquo.model.enumerator.SeverityType; +import com.google.common.collect.Iterables; + +/** + * Live integration tests for the {@link Event} domain class. + * + * @author Vivien Mahé + */ +@Test(groups = "api", testName = "EventLiveApiTest") +public class EventLiveApiTest extends BaseAbiquoApiLiveApiTest { + public void testListEventsFilteredByDatacenter() { + String name = randomName(); + env.datacenter.setName(name); + env.datacenter.update(); + + EventOptions options = EventOptions.builder().dateFrom(new Date()).datacenterName(name).build(); + assertEvents(options); + } + + public void testListEventsFilteredByRack() { + String name = randomName(); + env.rack.setName(name); + env.rack.update(); + + EventOptions options = EventOptions.builder().dateFrom(new Date()).rackName(name).build(); + assertEvents(options); + } + + public void testListEventsFilteredByPM() { + String name = randomName(); + env.machine.setName(name); + env.machine.update(); + + EventOptions options = EventOptions.builder().dateFrom(new Date()).physicalMachineName(name).build(); + assertEvents(options); + } + + public void testListEventsFilteredByStorageDevice() { + String name = randomName(); + env.storageDevice.setName(name); + env.storageDevice.update(); + + EventOptions options = EventOptions.builder().dateFrom(new Date()).storageSystemName(name).build(); + assertEvents(options); + } + + public void testListEventsFilteredByStoragePool() { + Tier tier = env.datacenter.findTier(TierPredicates.name("Default Tier 2")); + assertNotNull(tier); + + try { + env.storagePool.setTier(tier); + env.storagePool.update(); + + EventOptions options = EventOptions.builder().dateFrom(new Date()).storagePoolName(env.storagePool.getName()) + .build(); + assertEvents(options); + } finally { + // Restore the original tier + env.storagePool.setTier(env.tier); + env.storagePool.update(); + } + } + + public void testListEventsFilteredByEnterprise() { + String entName = env.enterprise.getName(); + String name = randomName(); + env.enterprise.setName(name); + env.enterprise.update(); + + // Enterprise current = + // env.enterpriseAdminContext.getAdministrationService().getCurrentEnterprise(); + // current.setName("Enterprise updated"); + // current.update(); + + EventOptions options = EventOptions.builder().dateFrom(new Date()).enterpriseName(name).build(); + assertEvents(options); + + env.enterprise.setName(entName); + env.enterprise.update(); + } + + /** + * TODO: Using the painUserContext, modifying the user returns this error: + * HTTP/1.1 401 Unauthorized + **/ + @Test(enabled = false) + public void testListEventsFilteredByUser() { + User current = env.plainUserContext.getAdministrationService().getCurrentUser(); + current.setEmail("test@test.com"); + current.update(); + + EventOptions options = EventOptions.builder().dateFrom(new Date()).userName(current.getName()).build(); + assertEvents(options); + } + + public void testListEventsFilteredByVDC() { + String name = randomName(); + env.virtualDatacenter.setName(name); + env.virtualDatacenter.update(); + + EventOptions options = EventOptions.builder().dateFrom(new Date()).virtualDatacenterName(name).build(); + assertEvents(options); + } + + public void testListEventsFilteredByVapp() { + String name = randomName(); + env.virtualAppliance.setName(name); + env.virtualAppliance.update(); + + EventOptions options = EventOptions.builder().dateFrom(new Date()).virtualAppName(name).build(); + assertEvents(options); + } + + public void testListEventsFilteredByVM() { + VirtualMachine vm = createVirtualMachine(); + vm.delete(); + + EventOptions options = EventOptions.builder().dateFrom(new Date()).actionPerformed(EventType.VM_DELETE).build(); + assertEvents(options); + } + + public void testListEventsFilteredByVolume() { + String name = randomName(); + Volume volume = createVolume(); + volume.setName(name); + volume.update(); + volume.delete(); // We don't need it any more. events already exist + + EventOptions options = EventOptions.builder().dateFrom(new Date()).volumeName(name).build(); + assertEvents(options); + } + + public void testListEventsFilteredBySeverity() { + String name = randomName(); + env.virtualAppliance.setName(name); + env.virtualAppliance.update(); + + EventOptions options = EventOptions.builder().dateFrom(new Date()).virtualAppName(name) + .severity(SeverityType.INFO).build(); + assertEvents(options); + } + + public void testListEventsFilteredByActionPerformed() { + String name = randomName(); + env.virtualAppliance.setName(name); + env.virtualAppliance.update(); + + EventOptions options = EventOptions.builder().dateFrom(new Date()).virtualAppName(name) + .actionPerformed(EventType.VAPP_MODIFY).build(); + assertEvents(options); + } + + public void testListEventsFilteredByComponent() { + String name = randomName(); + env.virtualAppliance.setName(name); + env.virtualAppliance.update(); + + EventOptions options = EventOptions.builder().dateFrom(new Date()).virtualAppName(name) + .component(ComponentType.VIRTUAL_APPLIANCE).build(); + assertEvents(options); + } + + public void testListEventsFilteredByDescription() { + String name = randomName(); + env.virtualAppliance.setName(name); + env.virtualAppliance.update(); + + EventOptions options = EventOptions.builder().dateFrom(new Date()).virtualAppName(name) + .description("Virtual appliance '" + name + "' has been modified.").build(); + assertEvents(options); + } + + // Helpers + + private void assertEvents(final EventOptions options) { + Iterable events = env.eventService.listEvents(options); + assertTrue(Iterables.size(events) >= 1); + } + + private Volume createVolume() { + Tier tier = env.virtualDatacenter.findStorageTier(TierPredicates.name(env.tier.getName())); + Volume volume = Volume.builder(env.context.getApiContext(), env.virtualDatacenter, tier) + .name(PREFIX + "Event vol").sizeInMb(32).build(); + + volume.save(); + assertNotNull(volume.getId()); + + return volume; + } + + private VirtualMachine createVirtualMachine() { + VirtualMachine virtualMachine = VirtualMachine + .builder(env.context.getApiContext(), env.virtualAppliance, env.template).cpu(2).ram(128).build(); + + virtualMachine.save(); + assertNotNull(virtualMachine.getId()); + + return virtualMachine; + } + + private static String randomName() { + return PREFIX + UUID.randomUUID().toString().substring(0, 12); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/infrastructure/BladeLiveUcsTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/infrastructure/BladeLiveUcsTest.java new file mode 100644 index 0000000000..77d2a828f1 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/infrastructure/BladeLiveUcsTest.java @@ -0,0 +1,83 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.infrastructure; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertTrue; + +import org.jclouds.abiquo.internal.BaseAbiquoApiLiveApiTest; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import com.google.common.collect.Iterables; + +/** + * Live integration tests for the {@link Blade} domain class. + * + * @author Ignasi Barrera + */ +@Test(groups = "ucs", testName = "BladeLiveUcsTest") +public class BladeLiveUcsTest extends BaseAbiquoApiLiveApiTest { + Blade blade; + + public void testFindAvailableVirtualSwitch() { + String vswitch = blade.getAvailableVirtualSwitches().get(0); + String found = blade.findAvailableVirtualSwitch(vswitch); + assertEquals(found, vswitch); + } + + public void testGetRack() { + ManagedRack rack = blade.getRack(); + assertNotNull(rack); + assertEquals(rack.getId(), env.ucsRack.getId()); + } + + public void testListBlades() { + Iterable blades = env.ucsRack.listMachines(); + assertTrue(Iterables.size(blades) > 0); + } + + public void testGetLogicServer() { + LogicServer logicServer = blade.getLogicServer(); + assertNotNull(logicServer); + assertNotNull(logicServer.getName()); + } + + public void testLedOn() { + blade.ledOn(); + BladeLocatorLed led = blade.getLocatorLed(); + assertNotNull(led); + assertEquals(led.getAdminStatus(), "on"); + } + + public void testLedOff() { + blade.ledOff(); + BladeLocatorLed led = blade.getLocatorLed(); + assertNotNull(led); + assertEquals(led.getAdminStatus(), "off"); + } + + @BeforeClass + public void setup() { + blade = env.ucsRack.listMachines().get(0); + assertNotNull(blade); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/infrastructure/DatacenterLiveApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/infrastructure/DatacenterLiveApiTest.java new file mode 100644 index 0000000000..af6cbe49a0 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/infrastructure/DatacenterLiveApiTest.java @@ -0,0 +1,82 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.infrastructure; + +import static org.jclouds.abiquo.util.Assert.assertHasError; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertTrue; +import static org.testng.Assert.fail; + +import java.util.List; + +import javax.ws.rs.core.Response.Status; + +import org.jclouds.abiquo.domain.enterprise.Limits; +import org.jclouds.abiquo.domain.exception.AbiquoException; +import org.jclouds.abiquo.domain.infrastructure.Datacenter.Builder; +import org.jclouds.abiquo.internal.BaseAbiquoApiLiveApiTest; +import org.testng.annotations.Test; + +import com.abiquo.model.enumerator.HypervisorType; +import com.abiquo.server.core.infrastructure.DatacenterDto; + +/** + * Live integration tests for the {@link Datacenter} domain class. + * + * @author Ignasi Barrera + */ +@Test(groups = "api", testName = "DatacenterLiveApiTest") +public class DatacenterLiveApiTest extends BaseAbiquoApiLiveApiTest { + + public void testUpdate() { + env.datacenter.setLocation("New York"); + env.datacenter.update(); + + // Recover the updated datacenter + DatacenterDto updated = env.infrastructureApi.getDatacenter(env.datacenter.getId()); + + assertEquals(updated.getLocation(), "New York"); + } + + public void testCheckHypervisorType() { + HypervisorType type = env.datacenter.getHypervisorType(env.machine.getIp()); + + assertEquals(env.machine.getType(), type); + } + + public void testCreateRepeated() { + Datacenter repeated = Builder.fromDatacenter(env.datacenter).build(); + + try { + repeated.save(); + fail("Should not be able to create datacenters with the same name"); + } catch (AbiquoException ex) { + assertHasError(ex, Status.CONFLICT, "DC-3"); + } + } + + public void testListLimits() { + List limits = env.datacenter.listLimits(); + assertNotNull(limits); + assertTrue(limits.size() > 0); + } + +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/infrastructure/MachineLiveApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/infrastructure/MachineLiveApiTest.java new file mode 100644 index 0000000000..6864088de8 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/infrastructure/MachineLiveApiTest.java @@ -0,0 +1,152 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.infrastructure; + +import static org.jclouds.abiquo.util.Assert.assertHasError; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertTrue; + +import java.net.URI; +import java.util.List; + +import javax.ws.rs.core.Response.Status; + +import org.jclouds.abiquo.domain.cloud.VirtualMachine; +import org.jclouds.abiquo.domain.enterprise.Enterprise; +import org.jclouds.abiquo.domain.exception.AbiquoException; +import org.jclouds.abiquo.internal.BaseAbiquoApiLiveApiTest; +import org.jclouds.abiquo.predicates.infrastructure.RemoteServicePredicates; +import org.jclouds.abiquo.util.Config; +import org.testng.annotations.Test; + +import com.abiquo.model.enumerator.HypervisorType; +import com.abiquo.model.enumerator.MachineState; +import com.abiquo.model.enumerator.RemoteServiceType; +import com.abiquo.server.core.infrastructure.MachineDto; + +/** + * Live integration tests for the {@link Machine} domain class. + * + * @author Ignasi Barrera + */ +@Test(groups = "api", testName = "MachineLiveApiTest") +public class MachineLiveApiTest extends BaseAbiquoApiLiveApiTest { + public void testDiscoverMachineWithouRemoteService() { + // Delete node collector + RemoteService nc = env.datacenter.findRemoteService(RemoteServicePredicates + .type(RemoteServiceType.NODE_COLLECTOR)); + nc.delete(); + + try { + String ip = Config.get("abiquo.hypervisor.address"); + HypervisorType type = HypervisorType.valueOf(Config.get("abiquo.hypervisor.type")); + String user = Config.get("abiquo.hypervisor.user"); + String pass = Config.get("abiquo.hypervisor.pass"); + + env.datacenter.discoverSingleMachine(ip, type, user, pass); + } catch (AbiquoException ex) { + assertHasError(ex, Status.NOT_FOUND, "RS-2"); + } + + URI endpoint = URI.create(env.context.getApiContext().getProviderMetadata().getEndpoint()); + + // Restore rs + nc = RemoteService.builder(env.context.getApiContext(), env.datacenter).type(RemoteServiceType.NODE_COLLECTOR) + .ip(endpoint.getHost()).build(); + nc.save(); + } + + public void testUpdate() { + env.machine.setName("API Machine"); + env.machine.update(); + + // Recover the updated machine + MachineDto updated = env.infrastructureApi.getMachine(env.rack.unwrap(), env.machine.getId()); + assertEquals(updated.getName(), "API Machine"); + } + + public void testCheck() { + MachineState state = env.machine.check(); + + // Recover the machine with same state that has been returned + MachineDto machine = env.infrastructureApi.getMachine(env.rack.unwrap(), env.machine.getId()); + assertEquals(machine.getState(), state); + } + + public void testCheckFromDatacenter() { + String ip = Config.get("abiquo.hypervisor.address"); + HypervisorType type = HypervisorType.valueOf(Config.get("abiquo.hypervisor.type")); + String user = Config.get("abiquo.hypervisor.user"); + String pass = Config.get("abiquo.hypervisor.pass"); + + MachineState state = env.datacenter.checkMachineState(ip, type, user, pass); + + // Recover the same machine and compare states + MachineDto machine = env.infrastructureApi.getMachine(env.rack.unwrap(), env.machine.getId()); + assertEquals(machine.getState(), state); + } + + public void testFindDatastore() { + Datastore datastore = env.machine.getDatastores().get(0); + Datastore found = env.machine.findDatastore(datastore.getName()); + assertEquals(found.getName(), datastore.getName()); + } + + public void testFindAvailableVirtualSwitch() { + String vswitch = env.machine.getAvailableVirtualSwitches().get(0); + String found = env.machine.findAvailableVirtualSwitch(vswitch); + assertEquals(found, vswitch); + } + + public void testGetRack() { + Rack rack = env.machine.getRack(); + assertNotNull(rack); + assertEquals(rack.getId(), env.rack.getId()); + } + + public void testListVirtualMachines() { + List machines = env.machine.listRemoteVirtualMachines(); + assertNotNull(machines); + assertTrue(machines.size() >= 0); + } + + public void testReserveMachine() { + assertFalse(env.machine.isReserved()); + + env.machine.reserveFor(env.enterprise); + assertTrue(env.machine.isReserved()); + + Enterprise owner = env.machine.getOwnerEnterprise(); + assertNotNull(owner); + assertEquals(owner.getId(), env.enterprise.getId()); + } + + @Test(dependsOnMethods = "testReserveMachine") + public void testCancelReservation() { + env.machine.cancelReservationFor(env.enterprise); + assertFalse(env.machine.isReserved()); + + Enterprise owner = env.machine.getOwnerEnterprise(); + assertNull(owner); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/infrastructure/ManagedRackLiveUcsTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/infrastructure/ManagedRackLiveUcsTest.java new file mode 100644 index 0000000000..cf0ce82818 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/infrastructure/ManagedRackLiveUcsTest.java @@ -0,0 +1,111 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.infrastructure; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertTrue; + +import java.util.List; + +import org.jclouds.abiquo.internal.BaseAbiquoApiLiveApiTest; +import org.jclouds.abiquo.predicates.infrastructure.LogicServerPredicates; +import org.jclouds.abiquo.predicates.infrastructure.ManagedRackPredicates; +import org.testng.annotations.Test; + +import com.abiquo.server.core.infrastructure.UcsRackDto; +import com.google.common.collect.Iterables; + +/** + * Live integration tests for the {@link ManagedRack} domain class. + * + * @author Francesc Montserrat + */ +@Test(groups = "ucs", testName = "ManagedRackLiveUcsTest") +public class ManagedRackLiveUcsTest extends BaseAbiquoApiLiveApiTest { + private LogicServer logicServer; + + private Organization organization; + + public void testUpdate() { + env.ucsRack.setShortDescription("Updated description"); + env.ucsRack.update(); + + // Recover the updated rack + UcsRackDto updated = env.infrastructureApi.getManagedRack(env.datacenter.unwrap(), env.ucsRack.getId()); + + assertEquals(updated.getShortDescription(), "Updated description"); + } + + public void testListManagedRacks() { + Iterable racks = env.datacenter.listManagedRacks(); + assertEquals(Iterables.size(racks), 1); + + racks = env.datacenter.listManagedRacks(ManagedRackPredicates.name(env.ucsRack.getName())); + assertEquals(Iterables.size(racks), 1); + } + + public void testFindRack() { + ManagedRack rack = env.datacenter.findManagedRack(ManagedRackPredicates.name(env.ucsRack.getName())); + assertNotNull(rack); + + rack = env.datacenter.findManagedRack(ManagedRackPredicates.name(env.ucsRack.getName() + "FAIL")); + assertNull(rack); + } + + public void testCloneLogicServer() { + List originals = env.ucsRack.listServiceProfiles(); + assertNotNull(originals); + assertTrue(originals.size() > 0); + LogicServer original = originals.get(0); + + List organizations = env.ucsRack.listOrganizations(); + assertNotNull(organizations); + assertTrue(organizations.size() > 0); + organization = organizations.get(0); + + env.ucsRack.cloneLogicServer(original, organization, "jclouds"); + + logicServer = env.ucsRack + .findServiceProfile(LogicServerPredicates.name(organization.getDn() + "/" + "ls-jclouds")); + assertNotNull(logicServer); + + String name = logicServer.getName(); + assertEquals(name.substring(name.length() - 7, name.length()), "jclouds"); + } + + @Test(dependsOnMethods = "testCloneLogicServer") + public void testListFsms() { + List fsms = env.ucsRack.listFsm(logicServer.getName()); + assertNotNull(fsms); + assertTrue(fsms.size() > 0); + } + + @Test(dependsOnMethods = { "testCloneLogicServer", "testListFsms" }) + public void testDeleteLogicServer() { + String name = logicServer.getName(); + + env.ucsRack.deleteLogicServer(logicServer); + + LogicServer profile = env.ucsRack.findServiceProfile(LogicServerPredicates.name(name)); + assertNull(profile); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/infrastructure/RackLiveApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/infrastructure/RackLiveApiTest.java new file mode 100644 index 0000000000..23c3c76eb0 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/infrastructure/RackLiveApiTest.java @@ -0,0 +1,70 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.infrastructure; + +import static org.jclouds.abiquo.predicates.infrastructure.RackPredicates.name; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; + +import org.jclouds.abiquo.internal.BaseAbiquoApiLiveApiTest; +import org.testng.annotations.Test; + +import com.abiquo.server.core.infrastructure.RackDto; +import com.google.common.collect.Iterables; + +/** + * Live integration tests for the {@link Rack} domain class. + * + * @author Ignasi Barrera + */ +@Test(groups = "api", testName = "RackLiveApiTest") +public class RackLiveApiTest extends BaseAbiquoApiLiveApiTest { + + public void testUpdate() { + env.rack.setName("Updated rack"); + env.rack.update(); + + // Recover the updated rack + RackDto updated = env.infrastructureApi.getRack(env.datacenter.unwrap(), env.rack.getId()); + + assertEquals(updated.getName(), "Updated rack"); + } + + public void testListRacks() { + Iterable racks = env.datacenter.listRacks(); + assertEquals(Iterables.size(racks), 1); + + racks = env.datacenter.listRacks(name(env.rack.getName())); + assertEquals(Iterables.size(racks), 1); + + racks = env.datacenter.listRacks(name(env.rack.getName() + "FAIL")); + assertEquals(Iterables.size(racks), 0); + } + + public void testFindRack() { + Rack rack = env.datacenter.findRack(name(env.rack.getName())); + assertNotNull(rack); + + rack = env.datacenter.findRack(name(env.rack.getName() + "FAIL")); + assertNull(rack); + } + +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/infrastructure/RemoteServiceLiveApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/infrastructure/RemoteServiceLiveApiTest.java new file mode 100644 index 0000000000..95060e704a --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/infrastructure/RemoteServiceLiveApiTest.java @@ -0,0 +1,115 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.infrastructure; + +import static org.jclouds.abiquo.predicates.infrastructure.RemoteServicePredicates.type; +import static org.jclouds.abiquo.util.Assert.assertHasError; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertTrue; +import static org.testng.Assert.fail; + +import java.net.URI; + +import javax.ws.rs.core.Response.Status; + +import org.jclouds.abiquo.domain.exception.AbiquoException; +import org.jclouds.abiquo.domain.infrastructure.RemoteService.Builder; +import org.jclouds.abiquo.internal.BaseAbiquoApiLiveApiTest; +import org.testng.annotations.Test; + +import com.abiquo.model.enumerator.RemoteServiceType; +import com.abiquo.server.core.infrastructure.RemoteServiceDto; +import com.google.common.collect.Iterables; + +/** + * Live integration tests for the {@link RemoteService} domain class. + * + * @author Ignasi Barrera + */ +@Test(groups = "api", testName = "RemoteServiceLiveApiTest") +public class RemoteServiceLiveApiTest extends BaseAbiquoApiLiveApiTest { + public void testUpdate() { + // Update the remote service + RemoteService rs = env.datacenter.findRemoteService(type(RemoteServiceType.VIRTUAL_FACTORY)); + rs.setUri(rs.getUri()); + rs.update(); + + // Recover the updated remote service + RemoteServiceDto updated = env.infrastructureApi.getRemoteService(env.datacenter.unwrap(), + RemoteServiceType.VIRTUAL_FACTORY); + + assertEquals(updated.getUri(), rs.getUri()); + } + + public void testDelete() { + RemoteService rs = env.datacenter.findRemoteService(type(RemoteServiceType.BPM_SERVICE)); + rs.delete(); + + // Recover the deleted remote service + RemoteServiceDto deleted = env.infrastructureApi.getRemoteService(env.datacenter.unwrap(), + RemoteServiceType.BPM_SERVICE); + + assertNull(deleted); + + URI endpoint = URI.create(env.context.getApiContext().getProviderMetadata().getEndpoint()); + + // Restore rs + RemoteService bpm = RemoteService.builder(env.context.getApiContext(), env.datacenter) + .type(RemoteServiceType.BPM_SERVICE).ip(endpoint.getHost()).build(); + bpm.save(); + } + + public void testIsAvailableNonCheckeable() { + RemoteService rs = env.datacenter.findRemoteService(type(RemoteServiceType.DHCP_SERVICE)); + assertTrue(rs.isAvailable()); + } + + public void testIsAvailable() { + RemoteService rs = env.datacenter.findRemoteService(type(RemoteServiceType.NODE_COLLECTOR)); + assertTrue(rs.isAvailable()); + } + + public void testCreateRepeated() { + RemoteService repeated = Builder.fromRemoteService(env.remoteServices.get(1)).build(); + + try { + repeated.save(); + fail("Should not be able to create duplicated remote services in the datacenter"); + } catch (AbiquoException ex) { + assertHasError(ex, Status.CONFLICT, "RS-6"); + } + } + + public void testListRemoteServices() { + Iterable remoteServices = env.datacenter.listRemoteServices(); + assertEquals(Iterables.size(remoteServices), env.remoteServices.size()); + + remoteServices = env.datacenter.listRemoteServices(type(RemoteServiceType.NODE_COLLECTOR)); + assertEquals(Iterables.size(remoteServices), 1); + } + + public void testFindRemoteService() { + RemoteService remoteService = env.datacenter.findRemoteService(type(RemoteServiceType.NODE_COLLECTOR)); + assertNotNull(remoteService); + } + +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/infrastructure/StorageDeviceLiveApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/infrastructure/StorageDeviceLiveApiTest.java new file mode 100644 index 0000000000..179c5ef739 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/infrastructure/StorageDeviceLiveApiTest.java @@ -0,0 +1,75 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.infrastructure; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; + +import org.jclouds.abiquo.internal.BaseAbiquoApiLiveApiTest; +import org.jclouds.abiquo.predicates.infrastructure.StorageDevicePredicates; +import org.testng.annotations.Test; + +import com.abiquo.server.core.infrastructure.storage.StorageDeviceDto; +import com.google.common.collect.Iterables; + +/** + * Live integration tests for the {@link StorageDevice} domain class. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +@Test(groups = "api", testName = "StorageDeviceLiveApiTest") +public class StorageDeviceLiveApiTest extends BaseAbiquoApiLiveApiTest { + + public void testUpdate() { + env.storageDevice.setName("Updated storage device"); + env.storageDevice.update(); + + // Recover the updated storage device + StorageDeviceDto updated = env.infrastructureApi.getStorageDevice(env.datacenter.unwrap(), + env.storageDevice.getId()); + + assertEquals(updated.getName(), "Updated storage device"); + } + + public void testListStorageDevices() { + Iterable storageDevices = env.datacenter.listStorageDevices(); + assertEquals(Iterables.size(storageDevices), 1); + + storageDevices = env.datacenter.listStorageDevices(StorageDevicePredicates.name(env.storageDevice.getName())); + assertEquals(Iterables.size(storageDevices), 1); + + storageDevices = env.datacenter.listStorageDevices(StorageDevicePredicates.name(env.storageDevice.getName() + + "FAIL")); + assertEquals(Iterables.size(storageDevices), 0); + } + + public void testFindStorageDevice() { + StorageDevice storageDevice = env.datacenter.findStorageDevice(StorageDevicePredicates.name(env.storageDevice + .getName())); + assertNotNull(storageDevice); + + storageDevice = env.datacenter.findStorageDevice(StorageDevicePredicates.name(env.storageDevice.getName() + + "FAIL")); + assertNull(storageDevice); + } + +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/infrastructure/StoragePoolLiveApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/infrastructure/StoragePoolLiveApiTest.java new file mode 100644 index 0000000000..303e4598ce --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/infrastructure/StoragePoolLiveApiTest.java @@ -0,0 +1,87 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.infrastructure; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; + +import org.jclouds.abiquo.internal.BaseAbiquoApiLiveApiTest; +import org.jclouds.abiquo.predicates.infrastructure.StoragePoolPredicates; +import org.jclouds.abiquo.predicates.infrastructure.TierPredicates; +import org.testng.annotations.Test; + +import com.google.common.collect.Iterables; + +/** + * Live integration tests for the {@link StorageDevice} domain class. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +@Test(groups = "api", testName = "StoragePoolLiveApiTest") +public class StoragePoolLiveApiTest extends BaseAbiquoApiLiveApiTest { + public void testGetDevice() { + StorageDevice device = env.storagePool.getStorageDevice(); + assertNotNull(device); + assertEquals(device.getId(), env.storageDevice.getId()); + } + + public void testUpdate() { + try { + Tier tier3 = env.datacenter.findTier(TierPredicates.name("Default Tier 3")); + assertNotNull(tier3); + env.storagePool.setTier(tier3); + env.storagePool.update(); + + assertEquals(env.storagePool.getTier().getName(), "Default Tier 3"); + } finally { + // Restore the original tier + env.storagePool.setTier(env.tier); + env.storagePool.update(); + assertEquals(env.storagePool.getTier().getId(), env.tier.getId()); + } + } + + public void testListStoragePool() { + Iterable storagePools = env.storageDevice.listStoragePools(); + assertEquals(Iterables.size(storagePools), 1); + + storagePools = env.storageDevice.listStoragePools(StoragePoolPredicates.name(env.storagePool.getName())); + assertEquals(Iterables.size(storagePools), 1); + + storagePools = env.storageDevice.listStoragePools(StoragePoolPredicates.name(env.storagePool.getName() + "FAIL")); + assertEquals(Iterables.size(storagePools), 0); + } + + public void testFindStoragePool() { + StoragePool storagePool = env.storageDevice + .findStoragePool(StoragePoolPredicates.name(env.storagePool.getName())); + assertNotNull(storagePool); + + storagePool = env.storageDevice.findStoragePool(StoragePoolPredicates.name(env.storagePool.getName() + "FAIL")); + assertNull(storagePool); + } + + public void testRefreshStoragePool() { + env.storagePool.refresh(); + } + +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/infrastructure/TierLiveApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/infrastructure/TierLiveApiTest.java new file mode 100644 index 0000000000..96ea1aee1d --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/infrastructure/TierLiveApiTest.java @@ -0,0 +1,64 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.infrastructure; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; + +import org.jclouds.abiquo.internal.BaseAbiquoApiLiveApiTest; +import org.jclouds.abiquo.predicates.infrastructure.TierPredicates; +import org.testng.annotations.Test; + +import com.google.common.collect.Iterables; + +/** + * Live integration tests for the {@link StorageDevice} domain class. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +@Test(groups = "api", testName = "TierLiveApiTest") +public class TierLiveApiTest extends BaseAbiquoApiLiveApiTest { + + public void testUpdate() { + Tier tier = env.datacenter.listTiers().get(0); + assertNotNull(tier); + + String previousName = tier.getName(); + tier.setName("Updated tier"); + tier.update(); + + // Recover the updated tier + Tier updated = env.datacenter.findTier(TierPredicates.name("Updated tier")); + assertEquals(updated.getName(), "Updated tier"); + + // Set original name + tier.setName(previousName); + tier.update(); + } + + public void testListTiers() { + Iterable tiers = env.datacenter.listTiers(); + assertEquals(Iterables.size(tiers), 4); + + tiers = env.datacenter.listTiers(TierPredicates.name("FAIL")); + assertEquals(Iterables.size(tiers), 0); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/network/ExternalNetworkLiveApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/network/ExternalNetworkLiveApiTest.java new file mode 100644 index 0000000000..013bd93684 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/network/ExternalNetworkLiveApiTest.java @@ -0,0 +1,160 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.network; + +import static org.jclouds.abiquo.reference.AbiquoTestConstants.PREFIX; +import static org.jclouds.abiquo.util.Assert.assertHasError; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.fail; + +import java.util.List; + +import javax.ws.rs.core.Response.Status; + +import org.jclouds.abiquo.domain.exception.AbiquoException; +import org.jclouds.abiquo.domain.network.options.IpOptions; +import org.jclouds.abiquo.internal.BaseAbiquoApiLiveApiTest; +import org.jclouds.abiquo.predicates.network.IpPredicates; +import org.jclouds.abiquo.predicates.network.NetworkPredicates; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import com.abiquo.server.core.infrastructure.network.ExternalIpsDto; + +/** + * Live integration tests for the {@link ExternalNetwork} domain class. + * + * @author Ignasi Barrera + */ +@Test(groups = "api", testName = "ExternalNetworkLiveApiTest") +public class ExternalNetworkLiveApiTest extends BaseAbiquoApiLiveApiTest { + private ExternalNetwork externalNetwork; + + @BeforeClass + public void setupNetwork() { + externalNetwork = createNetwork(env.externalNetwork, PREFIX + "-externalnetwork-test"); + } + + @AfterClass + public void tearDownNetwork() { + externalNetwork.delete(); + } + + public void testListIps() { + ExternalIpsDto ipsDto = env.context.getApiContext().getApi().getInfrastructureApi() + .listExternalIps(externalNetwork.unwrap(), IpOptions.builder().limit(1).build()); + int totalIps = ipsDto.getTotalSize(); + + List ips = externalNetwork.listIps(); + + assertEquals(ips.size(), totalIps); + } + + public void testListIpsWithOptions() { + List ips = externalNetwork.listIps(IpOptions.builder().limit(5).build()); + assertEquals(ips.size(), 5); + } + + public void testListUnusedIps() { + ExternalIpsDto ipsDto = env.context.getApiContext().getApi().getInfrastructureApi() + .listExternalIps(externalNetwork.unwrap(), IpOptions.builder().limit(1).build()); + int totalIps = ipsDto.getTotalSize(); + + List ips = externalNetwork.listUnusedIps(); + assertEquals(ips.size(), totalIps); + } + + public void testUpdateBasicInfo() { + externalNetwork.setName("External network Updated"); + externalNetwork.setPrimaryDNS("8.8.8.8"); + externalNetwork.setSecondaryDNS("8.8.8.8"); + externalNetwork.update(); + + assertEquals(externalNetwork.getName(), "External network Updated"); + assertEquals(externalNetwork.getPrimaryDNS(), "8.8.8.8"); + assertEquals(externalNetwork.getSecondaryDNS(), "8.8.8.8"); + + // Refresh the external network + ExternalNetwork en = env.enterprise.findExternalNetwork(env.datacenter, + NetworkPredicates. name(externalNetwork.getName())); + + assertEquals(en.getId(), externalNetwork.getId()); + assertEquals(en.getName(), "External network Updated"); + assertEquals(en.getPrimaryDNS(), "8.8.8.8"); + assertEquals(en.getSecondaryDNS(), "8.8.8.8"); + } + + public void testUpdateReadOnlyFields() { + ExternalNetwork toUpdate = createNetwork(externalNetwork, PREFIX + "-exttoupdate-test"); + + try { + toUpdate.setTag(20); + toUpdate.setAddress("10.1.0.0"); + toUpdate.setMask(16); + toUpdate.update(); + + fail("Tag field should not be editable"); + } catch (AbiquoException ex) { + assertHasError(ex, Status.CONFLICT, "VLAN-19"); + } finally { + toUpdate.delete(); + } + } + + public void testUpdateWithInvalidValues() { + ExternalNetwork toUpdate = createNetwork(externalNetwork, PREFIX + "-exttoupdate-test"); + + try { + toUpdate.setMask(60); + toUpdate.update(); + + fail("Invalid mask value"); + } catch (AbiquoException ex) { + assertHasError(ex, Status.BAD_REQUEST, "CONSTR-MAX"); + } finally { + toUpdate.delete(); + } + } + + public void testGetEnterprise() { + assertEquals(externalNetwork.getEnterprise().getId(), env.enterprise.getId()); + } + + public void testGetDatacenter() { + assertEquals(externalNetwork.getDatacenter().getId(), env.datacenter.getId()); + } + + public void testGetNetworkFromIp() { + ExternalIp ip = externalNetwork.findIp(IpPredicates. notUsed()); + ExternalNetwork network = ip.getNetwork(); + + assertEquals(network.getId(), externalNetwork.getId()); + } + + private ExternalNetwork createNetwork(final ExternalNetwork from, final String name) { + ExternalNetwork network = ExternalNetwork.Builder.fromExternalNetwork(from).build(); + network.setName(name); + network.save(); + assertNotNull(network.getId()); + return network; + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/network/GenericNetworkLiveApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/network/GenericNetworkLiveApiTest.java new file mode 100644 index 0000000000..1d80e2ed89 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/network/GenericNetworkLiveApiTest.java @@ -0,0 +1,84 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.network; + +import static org.jclouds.abiquo.util.Assert.assertHasError; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; + +import java.util.List; + +import javax.ws.rs.core.Response.Status; + +import org.jclouds.abiquo.domain.exception.AbiquoException; +import org.jclouds.abiquo.internal.BaseAbiquoApiLiveApiTest; +import org.testng.annotations.Test; + +import com.abiquo.model.enumerator.NetworkType; + +/** + * Live integration tests for the {@link Network} domain class. + * + * @author Ignasi Barrera + */ +@Test(groups = "api", testName = "GenericNetworkLiveApiTest") +public class GenericNetworkLiveApiTest extends BaseAbiquoApiLiveApiTest { + public void testListDatacenterNetworks() { + // Make sure all network types are listed + List> networks = env.datacenter.listNetworks(); + assertNotNull(networks); + assertEquals(networks.size(), 3); + } + + public void testListPublicNetworks() { + List> networks = env.datacenter.listNetworks(NetworkType.PUBLIC); + assertNotNull(networks); + assertEquals(networks.size(), 1); + + // Make sure it can be converted + networks.get(0).toPublicNetwork(); + } + + public void testListExternaletworks() { + List> networks = env.datacenter.listNetworks(NetworkType.EXTERNAL); + assertNotNull(networks); + assertEquals(networks.size(), 1); + + // Make sure it can be converted + networks.get(0).toExternalNetwork(); + } + + public void testListUnmanagedNetworks() { + List> networks = env.datacenter.listNetworks(NetworkType.UNMANAGED); + assertNotNull(networks); + assertEquals(networks.size(), 1); + + // Make sure it can be converted + networks.get(0).toUnmanagedNetwork(); + } + + public void testListPrivateNetworks() { + try { + env.datacenter.listNetworks(NetworkType.INTERNAL); + } catch (AbiquoException ex) { + assertHasError(ex, Status.BAD_REQUEST, "QUERY-1"); + } + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/network/PrivateNetworkLiveApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/network/PrivateNetworkLiveApiTest.java new file mode 100644 index 0000000000..f17881f8b4 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/network/PrivateNetworkLiveApiTest.java @@ -0,0 +1,150 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.network; + +import static org.jclouds.abiquo.reference.AbiquoTestConstants.PREFIX; +import static org.jclouds.abiquo.util.Assert.assertHasError; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.fail; + +import java.util.List; + +import javax.ws.rs.core.Response.Status; + +import org.jclouds.abiquo.domain.cloud.VirtualDatacenter; +import org.jclouds.abiquo.domain.exception.AbiquoException; +import org.jclouds.abiquo.domain.network.options.IpOptions; +import org.jclouds.abiquo.internal.BaseAbiquoApiLiveApiTest; +import org.jclouds.abiquo.predicates.network.IpPredicates; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import com.abiquo.server.core.infrastructure.network.PrivateIpsDto; + +/** + * Live integration tests for the {@link PrivateNetwork} domain class. + * + * @author Ignasi Barrera + */ +@Test(groups = "api", testName = "PrivateNetworkLiveApiTest") +public class PrivateNetworkLiveApiTest extends BaseAbiquoApiLiveApiTest { + private PrivateNetwork privateNetwork; + + @BeforeClass + public void setupNetwork() { + privateNetwork = createNetwork(env.virtualDatacenter, env.privateNetwork, PREFIX + "-privatenetwork-test"); + } + + @AfterClass + public void tearDownNetwork() { + privateNetwork.delete(); + } + + public void testListIps() { + PrivateIpsDto ipsDto = env.context.getApiContext().getApi().getCloudApi() + .listPrivateNetworkIps(privateNetwork.unwrap(), IpOptions.builder().limit(1).build()); + int totalIps = ipsDto.getTotalSize(); + + List ips = privateNetwork.listIps(); + + assertEquals(ips.size(), totalIps); + } + + public void testListIpsWithOptions() { + List ips = privateNetwork.listIps(IpOptions.builder().limit(5).build()); + assertEquals(ips.size(), 5); + } + + public void testListUnusedIps() { + PrivateIpsDto ipsDto = env.context.getApiContext().getApi().getCloudApi() + .listPrivateNetworkIps(privateNetwork.unwrap(), IpOptions.builder().limit(1).build()); + int totalIps = ipsDto.getTotalSize(); + + List ips = privateNetwork.listUnusedIps(); + assertEquals(ips.size(), totalIps); + } + + public void testUpdateBasicInfo() { + privateNetwork.setName("Private network Updated"); + privateNetwork.setPrimaryDNS("8.8.8.8"); + privateNetwork.setSecondaryDNS("8.8.8.8"); + privateNetwork.update(); + + assertEquals(privateNetwork.getName(), "Private network Updated"); + assertEquals(privateNetwork.getPrimaryDNS(), "8.8.8.8"); + assertEquals(privateNetwork.getSecondaryDNS(), "8.8.8.8"); + + // Refresh the private network + PrivateNetwork pn = env.virtualDatacenter.getPrivateNetwork(privateNetwork.getId()); + + assertEquals(pn.getName(), "Private network Updated"); + assertEquals(pn.getPrimaryDNS(), "8.8.8.8"); + assertEquals(pn.getSecondaryDNS(), "8.8.8.8"); + } + + public void testUpdateReadOnlyFields() { + PrivateNetwork toUpdate = createNetwork(env.virtualDatacenter, privateNetwork, PREFIX + "-privtoupdate-test"); + + try { + toUpdate.setTag(20); + toUpdate.setAddress("10.1.1.0"); + toUpdate.setMask(16); + toUpdate.update(); + + fail("Tag field should not be editable"); + } catch (AbiquoException ex) { + assertHasError(ex, Status.CONFLICT, "VLAN-10"); + } finally { + toUpdate.delete(); + } + } + + public void testUpdateWithInvalidValues() { + PrivateNetwork toUpdate = createNetwork(env.virtualDatacenter, privateNetwork, PREFIX + "-privtoupdate-test"); + + try { + toUpdate.setMask(60); + toUpdate.update(); + + fail("Invalid mask value"); + } catch (AbiquoException ex) { + assertHasError(ex, Status.BAD_REQUEST, "CONSTR-MAX"); + } finally { + toUpdate.delete(); + } + } + + public void testGetNetworkFromIp() { + PrivateIp ip = privateNetwork.findIp(IpPredicates. notUsed()); + PrivateNetwork network = ip.getNetwork(); + + assertEquals(network.getId(), privateNetwork.getId()); + } + + private PrivateNetwork createNetwork(final VirtualDatacenter vdc, final PrivateNetwork from, final String name) { + PrivateNetwork network = PrivateNetwork.Builder.fromPrivateNetwork(from).virtualDatacenter(vdc).build(); + network.setName(name); + network.save(); + assertNotNull(network.getId()); + return network; + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/network/PublicNetworkLiveApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/network/PublicNetworkLiveApiTest.java new file mode 100644 index 0000000000..94200fc268 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/network/PublicNetworkLiveApiTest.java @@ -0,0 +1,154 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.network; + +import static org.jclouds.abiquo.reference.AbiquoTestConstants.PREFIX; +import static org.jclouds.abiquo.util.Assert.assertHasError; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.fail; + +import java.util.List; + +import javax.ws.rs.core.Response.Status; + +import org.jclouds.abiquo.domain.exception.AbiquoException; +import org.jclouds.abiquo.domain.network.options.IpOptions; +import org.jclouds.abiquo.internal.BaseAbiquoApiLiveApiTest; +import org.jclouds.abiquo.predicates.network.IpPredicates; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import com.abiquo.server.core.infrastructure.network.PublicIpsDto; + +/** + * Live integration tests for the {@link PublicNetwork} domain class. + * + * @author Ignasi Barrera + */ +@Test(groups = "api", testName = "PublicNetworkLiveApiTest") +public class PublicNetworkLiveApiTest extends BaseAbiquoApiLiveApiTest { + private PublicNetwork publicNetwork; + + @BeforeClass + public void setupNetwork() { + publicNetwork = createNetwork(env.publicNetwork, PREFIX + "-publicnetwork-test"); + } + + @AfterClass + public void tearDownNetwork() { + publicNetwork.delete(); + } + + public void testListIps() { + PublicIpsDto ipsDto = env.context.getApiContext().getApi().getInfrastructureApi() + .listPublicIps(publicNetwork.unwrap(), IpOptions.builder().limit(1).build()); + int totalIps = ipsDto.getTotalSize(); + + List ips = publicNetwork.listIps(); + + assertEquals(ips.size(), totalIps); + } + + public void testListIpsWithOptions() { + List ips = publicNetwork.listIps(IpOptions.builder().limit(5).build()); + assertEquals(ips.size(), 5); + } + + public void testListUnusedIps() { + PublicIpsDto ipsDto = env.context.getApiContext().getApi().getInfrastructureApi() + .listPublicIps(publicNetwork.unwrap(), IpOptions.builder().limit(1).build()); + int totalIps = ipsDto.getTotalSize(); + + List ips = publicNetwork.listUnusedIps(); + assertEquals(ips.size(), totalIps); + } + + public void testUpdateBasicInfo() { + publicNetwork.setName("Public network Updated"); + publicNetwork.setPrimaryDNS("8.8.8.8"); + publicNetwork.setSecondaryDNS("8.8.8.8"); + publicNetwork.update(); + + assertEquals(publicNetwork.getName(), "Public network Updated"); + assertEquals(publicNetwork.getPrimaryDNS(), "8.8.8.8"); + assertEquals(publicNetwork.getSecondaryDNS(), "8.8.8.8"); + + // Refresh the public network + PublicNetwork pn = env.datacenter.getNetwork(publicNetwork.getId()).toPublicNetwork(); + + assertEquals(pn.getId(), publicNetwork.getId()); + assertEquals(pn.getName(), "Public network Updated"); + assertEquals(pn.getPrimaryDNS(), "8.8.8.8"); + assertEquals(pn.getSecondaryDNS(), "8.8.8.8"); + } + + public void testUpdateReadOnlyFields() { + PublicNetwork toUpdate = createNetwork(publicNetwork, PREFIX + "-pubtoupdate-test"); + + try { + toUpdate.setTag(20); + toUpdate.setAddress("80.81.81.0"); + toUpdate.setMask(16); + toUpdate.update(); + + fail("Tag field should not be editable"); + } catch (AbiquoException ex) { + assertHasError(ex, Status.CONFLICT, "VLAN-19"); + } finally { + toUpdate.delete(); + } + } + + public void testUpdateWithInvalidValues() { + PublicNetwork toUpdate = createNetwork(publicNetwork, PREFIX + "-pubtoupdate-test"); + + try { + toUpdate.setMask(60); + toUpdate.update(); + + fail("Invalid mask value"); + } catch (AbiquoException ex) { + assertHasError(ex, Status.BAD_REQUEST, "CONSTR-MAX"); + } finally { + toUpdate.delete(); + } + } + + public void testGetDatacenter() { + assertEquals(publicNetwork.getDatacenter().getId(), env.datacenter.getId()); + } + + public void testGetNetworkFromIp() { + PublicIp ip = publicNetwork.findIp(IpPredicates. notUsed()); + PublicNetwork network = ip.getNetwork(); + + assertEquals(network.getId(), publicNetwork.getId()); + } + + private PublicNetwork createNetwork(final PublicNetwork from, final String name) { + PublicNetwork network = PublicNetwork.Builder.fromPublicNetwork(from).build(); + network.setName(name); + network.save(); + assertNotNull(network.getId()); + return network; + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/network/UnmanagedNetworkLiveApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/network/UnmanagedNetworkLiveApiTest.java new file mode 100644 index 0000000000..cf2ebf77bb --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/domain/network/UnmanagedNetworkLiveApiTest.java @@ -0,0 +1,161 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.domain.network; + +import static org.jclouds.abiquo.reference.AbiquoTestConstants.PREFIX; +import static org.jclouds.abiquo.util.Assert.assertHasError; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.fail; + +import java.util.List; + +import javax.ws.rs.core.Response.Status; + +import org.jclouds.abiquo.domain.exception.AbiquoException; +import org.jclouds.abiquo.domain.network.options.IpOptions; +import org.jclouds.abiquo.internal.BaseAbiquoApiLiveApiTest; +import org.jclouds.abiquo.predicates.network.IpPredicates; +import org.jclouds.abiquo.predicates.network.NetworkPredicates; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import com.abiquo.server.core.infrastructure.network.UnmanagedIpsDto; + +/** + * Live integration tests for the {@link UnmanagedNetwork} domain class. + * + * @author Ignasi Barrera + */ +@Test(groups = "api", testName = "UnmanagedNetworkLiveApiTest") +public class UnmanagedNetworkLiveApiTest extends BaseAbiquoApiLiveApiTest { + private UnmanagedNetwork unmanagedNetwork; + + @BeforeClass + public void setupNetwork() { + unmanagedNetwork = createNetwork(env.unmanagedNetwork, PREFIX + "-unmanagednetwork-test"); + } + + @AfterClass + public void tearDownNetwork() { + unmanagedNetwork.delete(); + } + + public void testListIps() { + UnmanagedIpsDto ipsDto = env.context.getApiContext().getApi().getInfrastructureApi() + .listUnmanagedIps(unmanagedNetwork.unwrap(), IpOptions.builder().limit(1).build()); + int totalIps = ipsDto.getTotalSize(); + + List ips = unmanagedNetwork.listIps(); + + assertEquals(ips.size(), totalIps); + } + + public void testListIpsWithOptions() { + List ips = unmanagedNetwork.listIps(IpOptions.builder().limit(5).build()); + // Unmanaged networks do not have IPs until attached to VMs + assertEquals(ips.size(), 0); + } + + public void testListUnusedIps() { + UnmanagedIpsDto ipsDto = env.context.getApiContext().getApi().getInfrastructureApi() + .listUnmanagedIps(unmanagedNetwork.unwrap(), IpOptions.builder().limit(1).build()); + int totalIps = ipsDto.getTotalSize(); + + List ips = unmanagedNetwork.listUnusedIps(); + assertEquals(ips.size(), totalIps); + } + + public void testUpdateBasicInfo() { + unmanagedNetwork.setName("Unmanaged network Updated"); + unmanagedNetwork.setPrimaryDNS("8.8.8.8"); + unmanagedNetwork.setSecondaryDNS("8.8.8.8"); + unmanagedNetwork.update(); + + assertEquals(unmanagedNetwork.getName(), "Unmanaged network Updated"); + assertEquals(unmanagedNetwork.getPrimaryDNS(), "8.8.8.8"); + assertEquals(unmanagedNetwork.getSecondaryDNS(), "8.8.8.8"); + + // Refresh the unmanaged network + UnmanagedNetwork en = env.enterprise.findUnmanagedNetwork(env.datacenter, + NetworkPredicates. name(unmanagedNetwork.getName())); + + assertEquals(en.getId(), unmanagedNetwork.getId()); + assertEquals(en.getName(), "Unmanaged network Updated"); + assertEquals(en.getPrimaryDNS(), "8.8.8.8"); + assertEquals(en.getSecondaryDNS(), "8.8.8.8"); + } + + public void testUpdateReadOnlyFields() { + UnmanagedNetwork toUpdate = createNetwork(unmanagedNetwork, PREFIX + "-umtoupdate-test"); + + try { + toUpdate.setTag(20); + toUpdate.setAddress("10.2.0.0"); + toUpdate.setMask(16); + toUpdate.update(); + + fail("Tag field should not be editable"); + } catch (AbiquoException ex) { + assertHasError(ex, Status.CONFLICT, "VLAN-19"); + } finally { + toUpdate.delete(); + } + } + + public void testUpdateWithInvalidValues() { + UnmanagedNetwork toUpdate = createNetwork(unmanagedNetwork, PREFIX + "-umtoupdate-test"); + + try { + toUpdate.setMask(60); + toUpdate.update(); + + fail("Invalid mask value"); + } catch (AbiquoException ex) { + assertHasError(ex, Status.BAD_REQUEST, "CONSTR-MAX"); + } finally { + toUpdate.delete(); + } + } + + public void testGetEnterprise() { + assertEquals(unmanagedNetwork.getEnterprise().getId(), env.enterprise.getId()); + } + + public void testGetDatacenter() { + assertEquals(unmanagedNetwork.getDatacenter().getId(), env.datacenter.getId()); + } + + public void testGetNetworkFromIp() { + UnmanagedIp ip = unmanagedNetwork.findIp(IpPredicates. notUsed()); + // Unmanaged networks do not have IPs until attached to VMs + assertNull(ip); + } + + private UnmanagedNetwork createNetwork(final UnmanagedNetwork from, final String name) { + UnmanagedNetwork network = UnmanagedNetwork.Builder.fromUnmanagedNetwork(from).build(); + network.setName(name); + network.save(); + assertNotNull(network.getId()); + return network; + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/environment/CloudTestEnvironment.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/environment/CloudTestEnvironment.java new file mode 100644 index 0000000000..dbfc244367 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/environment/CloudTestEnvironment.java @@ -0,0 +1,220 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.environment; + +import static com.google.common.base.Preconditions.checkNotNull; +import static org.jclouds.abiquo.reference.AbiquoTestConstants.PREFIX; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; + +import java.util.Collections; +import java.util.List; + +import org.jclouds.ContextBuilder; +import org.jclouds.abiquo.AbiquoApiMetadata; +import org.jclouds.abiquo.AbiquoContext; +import org.jclouds.abiquo.domain.cloud.VirtualAppliance; +import org.jclouds.abiquo.domain.cloud.VirtualDatacenter; +import org.jclouds.abiquo.domain.cloud.VirtualMachine; +import org.jclouds.abiquo.domain.cloud.VirtualMachineTemplate; +import org.jclouds.abiquo.domain.enterprise.Enterprise; +import org.jclouds.abiquo.domain.network.PrivateIp; +import org.jclouds.abiquo.domain.network.PrivateNetwork; +import org.jclouds.abiquo.features.CloudApi; +import org.jclouds.abiquo.features.services.EventService; +import org.jclouds.abiquo.predicates.enterprise.EnterprisePredicates; +import org.jclouds.abiquo.predicates.network.NetworkPredicates; + +import com.google.common.collect.Ordering; +import com.google.common.primitives.Longs; + +/** + * Test environment for cloud live tests. + * + * @author Francesc Montserrat + */ +public class CloudTestEnvironment extends InfrastructureTestEnvironment { + + // Environment data made public so tests can use them easily + public CloudApi cloudApi; + + public EventService eventService; + + public VirtualDatacenter virtualDatacenter; + + public VirtualAppliance virtualAppliance; + + public VirtualMachine virtualMachine; + + public VirtualMachineTemplate template; + + public PrivateNetwork privateNetwork; + + public Enterprise defaultEnterprise; + + public AbiquoContext plainUserContext; + + public AbiquoContext enterpriseAdminContext; + + public CloudTestEnvironment(final AbiquoContext context) { + super(context); + this.cloudApi = context.getApiContext().getApi().getCloudApi(); + this.eventService = context.getEventService(); + } + + @Override + public void setup() throws Exception { + // Create base infrastructure + super.setup(); + + createUserContext(); + createEnterpriseAdminContext(); + + findDefaultEnterprise(); + createVirtualDatacenter(); + createVirtualAppliance(); + refreshTemplateRepository(); + createVirtualMachine(); + } + + @Override + public void tearDown() throws Exception { + closeEnterpriseAdminContext(); + closeUserContext(); + + deleteVirtualMachine(); + deleteVirtualAppliance(); + deleteVirtualDatacenter(); + + // Delete base infrastructure + super.tearDown(); + } + + // Setup + + private void createUserContext() { + String endpoint = checkNotNull(System.getProperty("test.abiquo.endpoint"), "test.abiquo.endpoint"); + + plainUserContext = ContextBuilder.newBuilder(new AbiquoApiMetadata()) // + .endpoint(endpoint) // + .credentials("abiquo", "jclouds") // + .build(AbiquoContext.class); + } + + private void createEnterpriseAdminContext() { + String endpoint = checkNotNull(System.getProperty("test.abiquo.endpoint"), "test.abiquo.endpoint"); + + enterpriseAdminContext = ContextBuilder.newBuilder(new AbiquoApiMetadata()) // + .endpoint(endpoint) // + .credentials("jclouds-admin", "admin") // + .build(AbiquoContext.class); + } + + protected void findDefaultEnterprise() { + defaultEnterprise = context.getAdministrationService().findEnterprise(EnterprisePredicates.name("Abiquo")); + } + + protected void createVirtualDatacenter() { + privateNetwork = PrivateNetwork.builder(context.getApiContext()).name("DefaultNetwork").gateway("192.168.1.1") + .address("192.168.1.0").mask(24).build(); + + virtualDatacenter = VirtualDatacenter.builder(context.getApiContext(), datacenter, defaultEnterprise) + .name(PREFIX + "Virtual Aloha").cpuCountLimits(18, 20).hdLimitsInMb(279172872, 279172872) + .publicIpsLimits(2, 3).ramLimits(19456, 20480).storageLimits(289910292, 322122547).vlansLimits(3, 4) + .hypervisorType(machine.getType()).network(privateNetwork).build(); + + virtualDatacenter.save(); + assertNotNull(virtualDatacenter.getId()); + + privateNetwork = virtualDatacenter + .findPrivateNetwork(NetworkPredicates. name(privateNetwork.getName())); + } + + protected void createVirtualAppliance() { + virtualAppliance = VirtualAppliance.builder(context.getApiContext(), virtualDatacenter) + .name(PREFIX + "Virtual AppAloha").build(); + + virtualAppliance.save(); + assertNotNull(virtualAppliance.getId()); + } + + protected void createVirtualMachine() { + List templates = virtualDatacenter.listAvailableTemplates(); + assertFalse(templates.isEmpty()); + + // Sort by size to use the smallest one + Collections.sort(templates, new Ordering() { + @Override + public int compare(final VirtualMachineTemplate left, final VirtualMachineTemplate right) { + return Longs.compare(left.getDiskFileSize(), right.getDiskFileSize()); + } + }); + + template = templates.get(0); + + virtualMachine = VirtualMachine.builder(context.getApiContext(), virtualAppliance, template).cpu(2) + .nameLabel(PREFIX + "VM Aloha").ram(128).build(); + + virtualMachine.save(); + assertNotNull(virtualMachine.getId()); + + } + + protected void refreshTemplateRepository() { + defaultEnterprise.refreshTemplateRepository(datacenter); + } + + // Tear down + + private void closeUserContext() { + plainUserContext.close(); + } + + private void closeEnterpriseAdminContext() { + enterpriseAdminContext.close(); + } + + protected void deleteVirtualDatacenter() { + if (virtualDatacenter != null && enterprise != null && datacenter != null) { + Integer idVirtualDatacenter = virtualDatacenter.getId(); + virtualDatacenter.delete(); + assertNull(cloudApi.getVirtualDatacenter(idVirtualDatacenter)); + } + } + + protected void deleteVirtualAppliance() { + if (virtualAppliance != null && virtualDatacenter != null) { + Integer idVirtualAppliance = virtualAppliance.getId(); + virtualAppliance.delete(); + assertNull(cloudApi.getVirtualAppliance(virtualDatacenter.unwrap(), idVirtualAppliance)); + } + } + + protected void deleteVirtualMachine() { + if (virtualMachine != null && virtualAppliance != null && virtualDatacenter != null) { + Integer idVirtualMachine = virtualMachine.getId(); + virtualMachine.delete(); + assertNull(cloudApi.getVirtualMachine(virtualAppliance.unwrap(), idVirtualMachine)); + } + + } + +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/environment/InfrastructureTestEnvironment.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/environment/InfrastructureTestEnvironment.java new file mode 100644 index 0000000000..2a68d3154b --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/environment/InfrastructureTestEnvironment.java @@ -0,0 +1,471 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.environment; + +import static com.google.common.collect.Iterables.find; +import static org.jclouds.abiquo.reference.AbiquoTestConstants.PREFIX; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; + +import java.io.IOException; +import java.net.URI; +import java.net.URL; +import java.nio.charset.Charset; +import java.util.List; +import java.util.UUID; + +import org.jclouds.abiquo.AbiquoContext; +import org.jclouds.abiquo.config.AbiquoEdition; +import org.jclouds.abiquo.domain.config.License; +import org.jclouds.abiquo.domain.enterprise.Enterprise; +import org.jclouds.abiquo.domain.enterprise.Limits; +import org.jclouds.abiquo.domain.enterprise.Role; +import org.jclouds.abiquo.domain.enterprise.User; +import org.jclouds.abiquo.domain.infrastructure.Datacenter; +import org.jclouds.abiquo.domain.infrastructure.Datastore; +import org.jclouds.abiquo.domain.infrastructure.Machine; +import org.jclouds.abiquo.domain.infrastructure.ManagedRack; +import org.jclouds.abiquo.domain.infrastructure.Rack; +import org.jclouds.abiquo.domain.infrastructure.RemoteService; +import org.jclouds.abiquo.domain.infrastructure.StorageDevice; +import org.jclouds.abiquo.domain.infrastructure.StorageDeviceMetadata; +import org.jclouds.abiquo.domain.infrastructure.StoragePool; +import org.jclouds.abiquo.domain.infrastructure.Tier; +import org.jclouds.abiquo.domain.network.ExternalNetwork; +import org.jclouds.abiquo.domain.network.PublicNetwork; +import org.jclouds.abiquo.domain.network.UnmanagedNetwork; +import org.jclouds.abiquo.features.AdminApi; +import org.jclouds.abiquo.features.ConfigApi; +import org.jclouds.abiquo.features.EnterpriseApi; +import org.jclouds.abiquo.features.InfrastructureApi; +import org.jclouds.abiquo.features.services.AdministrationService; +import org.jclouds.abiquo.predicates.enterprise.RolePredicates; +import org.jclouds.abiquo.predicates.enterprise.UserPredicates; +import org.jclouds.abiquo.predicates.infrastructure.RemoteServicePredicates; +import org.jclouds.abiquo.predicates.infrastructure.StorageDeviceMetadataPredicates; +import org.jclouds.abiquo.predicates.infrastructure.StoragePoolPredicates; +import org.jclouds.abiquo.predicates.infrastructure.TierPredicates; +import org.jclouds.abiquo.util.Config; + +import com.abiquo.model.enumerator.HypervisorType; +import com.abiquo.model.enumerator.RemoteServiceType; +import com.google.common.collect.Iterables; +import com.google.common.io.Resources; + +/** + * Test environment for infrastructure live tests. + * + * @author Ignasi Barrera + */ +public class InfrastructureTestEnvironment implements TestEnvironment { + /** The rest context. */ + public AbiquoContext context; + + // Environment data made public so tests can use them easily + + public AdministrationService administrationService; + + public InfrastructureApi infrastructureApi; + + public EnterpriseApi enterpriseApi; + + public AdminApi adminApi; + + public ConfigApi configApi; + + // Resources + + public License license; + + public Datacenter datacenter; + + public PublicNetwork publicNetwork; + + public ExternalNetwork externalNetwork; + + public UnmanagedNetwork unmanagedNetwork; + + public List remoteServices; + + public Rack rack; + + public Machine machine; + + public Enterprise enterprise; + + public StorageDevice storageDevice; + + public StoragePool storagePool; + + public Tier tier; + + public User user; + + public User enterpriseAdmin; + + public Role role; + + public Role anotherRole; + + public ManagedRack ucsRack; + + public InfrastructureTestEnvironment(final AbiquoContext context) { + super(); + this.context = context; + this.administrationService = context.getAdministrationService(); + this.context = context; + this.enterpriseApi = context.getApiContext().getApi().getEnterpriseApi(); + this.infrastructureApi = context.getApiContext().getApi().getInfrastructureApi(); + this.adminApi = context.getApiContext().getApi().getAdminApi(); + this.configApi = context.getApiContext().getApi().getConfigApi(); + } + + @Override + public void setup() throws Exception { + // Configuration + createLicense(); + + // Intrastructure + createDatacenter(); + createRack(); + createMachine(); + createStorageDevice(); + createStoragePool(); + createPublicNetwork(); + + // Enterprise + createEnterprise(); + createRoles(); + createUsers(); + + // Networking + createExternalNetwork(); + createUnmanagedNetwork(); + } + + @Override + public void tearDown() throws Exception { + deleteUsers(); + + deleteRole(role); + deleteRole(anotherRole); + + deleteUnmanagedNetwork(); + deleteExternalNetwork(); + deletePublicNetwork(); + deleteStoragePool(); + deleteStorageDevice(); + deleteMachine(); + deleteUcsRack(); + deleteRack(); + deleteDatacenter(); + deleteEnterprise(); + + deleteLicense(); + } + + // Setup + + protected void createLicense() throws IOException { + license = License.builder(context.getApiContext(), readLicense()).build(); + + license.add(); + assertNotNull(license.getId()); + } + + protected void createDatacenter() { + // Assume a monolithic install + URI endpoint = URI.create(context.getApiContext().getProviderMetadata().getEndpoint()); + String remoteServicesAddress = endpoint.getHost(); + + datacenter = Datacenter.builder(context.getApiContext()).name(randomName()).location("Honolulu") + .remoteServices(remoteServicesAddress, AbiquoEdition.ENTERPRISE).build(); + datacenter.save(); + assertNotNull(datacenter.getId()); + + remoteServices = datacenter.listRemoteServices(); + assertEquals(remoteServices.size(), 7); + } + + protected void createMachine() { + String ip = Config.get("abiquo.hypervisor.address"); + HypervisorType type = HypervisorType.valueOf(Config.get("abiquo.hypervisor.type")); + String user = Config.get("abiquo.hypervisor.user"); + String pass = Config.get("abiquo.hypervisor.pass"); + + machine = datacenter.discoverSingleMachine(ip, type, user, pass); + + String vswitch = machine.findAvailableVirtualSwitch(Config.get("abiquo.hypervisor.vswitch")); + machine.setVirtualSwitch(vswitch); + + Datastore datastore = machine.findDatastore(Config.get("abiquo.hypervisor.datastore")); + datastore.setEnabled(true); + + machine.setRack(rack); + machine.save(); + assertNotNull(machine.getId()); + } + + protected void createRack() { + rack = Rack.builder(context.getApiContext(), datacenter).name(PREFIX + "Aloha").build(); + rack.save(); + assertNotNull(rack.getId()); + } + + public void createUcsRack() { + String ip = Config.get("abiquo.ucs.address"); + Integer port = Integer.parseInt(Config.get("abiquo.ucs.port")); + String user = Config.get("abiquo.ucs.user"); + String pass = Config.get("abiquo.ucs.pass"); + + ucsRack = ManagedRack.builder(context.getApiContext(), datacenter).ipAddress(ip).port(port).user(user) + .name("ucs rack").password(pass).build(); + + ucsRack.save(); + assertNotNull(ucsRack.getId()); + } + + protected void createStorageDevice() { + String ip = Config.get("abiquo.storage.address"); + String type = Config.get("abiquo.storage.type"); + String user = Config.get("abiquo.storage.user"); + String pass = Config.get("abiquo.storage.pass"); + + List devices = datacenter.listSupportedStorageDevices(); + StorageDeviceMetadata metadata = Iterables.find(devices, StorageDeviceMetadataPredicates.type(type)); + + storageDevice = StorageDevice.builder(context.getApiContext(), datacenter) // + .name(PREFIX + "Storage Device")// + .type(type)// + .managementIp(ip).managementPort(metadata.getDefaultManagementPort())// + .iscsiIp(ip).iscsiPort(metadata.getDefaultIscsiPort()) // + .username(user)// + .password(pass) // + .build(); + + storageDevice.save(); + assertNotNull(storageDevice.getId()); + } + + protected void createStoragePool() { + String pool = Config.get("abiquo.storage.pool"); + + storagePool = storageDevice.findRemoteStoragePool(StoragePoolPredicates.name(pool)); + tier = datacenter.findTier(TierPredicates.name("Default Tier 1")); + + storagePool.setTier(tier); + storagePool.save(); + + assertNotNull(storagePool.getUUID()); + } + + protected void createUsers() { + Role userRole = administrationService.findRole(RolePredicates.name("USER")); + Role enterpriseAdminRole = administrationService.findRole(RolePredicates.name("ENTERPRISE_ADMIN")); + + user = User.builder(context.getApiContext(), enterprise, userRole).name(randomName(), randomName()) + .nick("jclouds").authType("ABIQUO").description(randomName()).email(randomName() + "@abiquo.com") + .locale("en_US").password("user").build(); + + user.save(); + assertNotNull(user.getId()); + assertEquals(userRole.getId(), user.getRole().getId()); + + enterpriseAdmin = User.builder(context.getApiContext(), enterprise, enterpriseAdminRole) + .name(randomName(), randomName()).nick("jclouds-admin").authType("ABIQUO").description(randomName()) + .email(randomName() + "@abiquo.com").locale("en_US").password("admin").build(); + + enterpriseAdmin.save(); + assertNotNull(enterpriseAdmin.getId()); + assertEquals(enterpriseAdminRole.getId(), enterpriseAdmin.getRole().getId()); + } + + protected void createRoles() { + role = Role.builder(context.getApiContext()).name(randomName()).blocked(false).build(); + role.save(); + + anotherRole = Role.Builder.fromRole(role).build(); + anotherRole.setName("Another role"); + anotherRole.save(); + + assertNotNull(role.getId()); + assertNotNull(anotherRole.getId()); + } + + protected void createEnterprise() { + enterprise = Enterprise.builder(context.getApiContext()).name(randomName()).build(); + enterprise.save(); + assertNotNull(enterprise.getId()); + Limits limits = enterprise.allowDatacenter(datacenter); + assertNotNull(limits); + } + + protected void createPublicNetwork() { + publicNetwork = PublicNetwork.builder(context.getApiContext(), datacenter).name("PublicNetwork") + .gateway("80.80.80.1").address("80.80.80.0").mask(24).tag(5).build(); + publicNetwork.save(); + assertNotNull(publicNetwork.getId()); + } + + protected void createExternalNetwork() { + externalNetwork = ExternalNetwork.builder(context.getApiContext(), datacenter, enterprise) + .name("ExternalNetwork").gateway("10.0.0.1").address("10.0.0.0").mask(24).tag(7).build(); + externalNetwork.save(); + assertNotNull(externalNetwork.getId()); + } + + protected void createUnmanagedNetwork() { + unmanagedNetwork = UnmanagedNetwork.builder(context.getApiContext(), datacenter, enterprise) + .name("UnmanagedNetwork").gateway("10.0.1.1").address("10.0.1.0").mask(24).tag(8).build(); + unmanagedNetwork.save(); + assertNotNull(unmanagedNetwork.getId()); + } + + // Tear down + + protected void deleteUnmanagedNetwork() { + if (unmanagedNetwork != null) { + Integer id = unmanagedNetwork.getId(); + unmanagedNetwork.delete(); + assertNull(datacenter.getNetwork(id)); + } + } + + protected void deleteExternalNetwork() { + if (externalNetwork != null) { + Integer id = externalNetwork.getId(); + externalNetwork.delete(); + assertNull(datacenter.getNetwork(id)); + } + } + + protected void deletePublicNetwork() { + if (publicNetwork != null) { + Integer id = publicNetwork.getId(); + publicNetwork.delete(); + assertNull(datacenter.getNetwork(id)); + } + } + + protected void deleteUsers() { + if (user != null) { + String nick = user.getNick(); + user.delete(); + // Nick is unique in an enterprise + assertNull(enterprise.findUser(UserPredicates.nick(nick))); + } + + if (enterpriseAdmin != null) { + String nick = enterpriseAdmin.getNick(); + enterpriseAdmin.delete(); + // Nick is unique in an enterprise + assertNull(enterprise.findUser(UserPredicates.nick(nick))); + } + } + + protected void deleteRole(final Role role) { + if (role != null) { + Integer roleId = role.getId(); + role.delete(); + assertNull(adminApi.getRole(roleId)); + } + } + + protected void deleteStoragePool() { + if (storagePool != null) { + String idStoragePool = storagePool.getUUID(); + storagePool.delete(); + assertNull(infrastructureApi.getStoragePool(storageDevice.unwrap(), idStoragePool)); + } + + } + + protected void deleteStorageDevice() { + if (storageDevice != null) { + Integer idStorageDevice = storageDevice.getId(); + storageDevice.delete(); + assertNull(infrastructureApi.getStorageDevice(datacenter.unwrap(), idStorageDevice)); + } + } + + protected void deleteMachine() { + if (machine != null && rack != null) { + Integer idMachine = machine.getId(); + machine.delete(); + assertNull(infrastructureApi.getMachine(rack.unwrap(), idMachine)); + } + } + + protected void deleteRack() { + if (rack != null && datacenter != null) { + Integer idRack = rack.getId(); + rack.delete(); + assertNull(infrastructureApi.getRack(datacenter.unwrap(), idRack)); + } + } + + protected void deleteUcsRack() { + if (ucsRack != null && datacenter != null) { + Integer idRack = ucsRack.getId(); + ucsRack.delete(); + assertNull(infrastructureApi.getManagedRack(datacenter.unwrap(), idRack)); + } + } + + protected void deleteDatacenter() { + if (datacenter != null) { + // Remove limits first + enterprise.prohibitDatacenter(datacenter); + + Integer idDatacenter = datacenter.getId(); + datacenter.delete(); // Abiquo API will delete remote services too + assertNull(infrastructureApi.getDatacenter(idDatacenter)); + } + } + + protected void deleteEnterprise() { + if (enterprise != null) { + Integer idEnterprise = enterprise.getId(); + enterprise.delete(); + assertNull(enterpriseApi.getEnterprise(idEnterprise)); + } + } + + protected void deleteLicense() { + license.remove(); + } + + protected static String randomName() { + return PREFIX + UUID.randomUUID().toString().substring(0, 12); + } + + // Utility methods + + public static String readLicense() throws IOException { + URL url = CloudTestEnvironment.class.getResource("/license/expired"); + + return Resources.toString(url, Charset.defaultCharset()); + } + + public RemoteService findRemoteService(final RemoteServiceType type) { + return find(remoteServices, RemoteServicePredicates.type(type)); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/environment/TestEnvironment.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/environment/TestEnvironment.java new file mode 100644 index 0000000000..53426fa32e --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/environment/TestEnvironment.java @@ -0,0 +1,40 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.environment; + +/** + * Base class fot test environment populators. + *

+ * This class should be used to populate and clean the test environment used in + * live tests. + * + * @author Ignasi Barrera + */ +public interface TestEnvironment { + /** + * Builds the test environment. + */ + public void setup() throws Exception; + + /** + * Cleans the test environment. + */ + public void tearDown() throws Exception; +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/events/handlers/BlockingEventHandlerTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/events/handlers/BlockingEventHandlerTest.java new file mode 100644 index 0000000000..87f45229eb --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/events/handlers/BlockingEventHandlerTest.java @@ -0,0 +1,112 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.events.handlers; + +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertTrue; + +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +import org.jclouds.abiquo.events.monitor.MonitorEvent; +import org.jclouds.abiquo.events.monitor.MonitorEvent.Type; +import org.testng.annotations.Test; + +/** + * Unit tests for the {@link BlockingEventHandler} handler. + * + * @author Ignasi Barrera + */ +@Test(groups = "unit", testName = "BlockingEventHandlerTest") +public class BlockingEventHandlerTest { + @Test(expectedExceptions = IllegalArgumentException.class) + public void testConstructorWithoutObjects() { + new BlockingEventHandler(); + } + + @Test(expectedExceptions = NullPointerException.class) + public void testConstructorWithNullObjects() { + new BlockingEventHandler((Object[]) null); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testConstructorWithtEmptyObjects() { + new BlockingEventHandler(new Object[] {}); + } + + public void testHandles() { + Object object = new Object(); + BlockingEventHandler handler = new BlockingEventHandler(object); + + assertTrue(handler.handles(new MonitorEvent(Type.COMPLETED, object))); + assertFalse(handler.handles(new MonitorEvent(Type.COMPLETED, new Object()))); + } + + public void testReleaseDoesNothingIfNotLocked() { + Object object = new Object(); + BlockingEventHandler handler = new BlockingEventHandler(object); + handler.release(object); + } + + public void testRelease() { + final Object object = new Object(); + final BlockingEventHandler handler = new BlockingEventHandler(object); + + // Unlock the handler (in a separate thread) after a certain delay + Executors.newSingleThreadScheduledExecutor().schedule(new Runnable() { + @Override + public void run() { + handler.release(object); + assertTrue(handler.lockedObjects.isEmpty()); + } + + }, 500L, TimeUnit.MILLISECONDS); + + handler.lock(); + } + + public void testHandle() { + final Object object = new Object(); + final BlockingEventHandler handler = new BlockingEventHandler(object); + + // Unlock the handler (in a separate thread) after a certain delay + Executors.newSingleThreadScheduledExecutor().schedule(new Runnable() { + @Override + public void run() { + handler.handle(new MonitorEvent(Type.COMPLETED, object)); + assertTrue(handler.lockedObjects.isEmpty()); + } + + }, 500L, TimeUnit.MILLISECONDS); + + handler.lock(); + } + + public void testLockDoesNothingIfNoObjects() { + Object object = new Object(); + BlockingEventHandler handler = new BlockingEventHandler(object); + handler.lockedObjects.clear(); + + handler.lock(); // Lock should do nothing + + assertNull(handler.completeSignal); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/features/AdminAsyncApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/features/AdminAsyncApiTest.java new file mode 100644 index 0000000000..a1be6aa19f --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/features/AdminAsyncApiTest.java @@ -0,0 +1,182 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.features; + +import static org.jclouds.abiquo.domain.DomainUtils.withHeader; + +import java.io.IOException; +import java.lang.reflect.Method; + +import org.jclouds.abiquo.domain.AdminResources; +import org.jclouds.abiquo.domain.EnterpriseResources; +import org.jclouds.http.functions.ParseXMLWithJAXB; +import org.jclouds.http.functions.ReleasePayloadAndReturn; +import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; +import org.jclouds.rest.internal.GeneratedHttpRequest; +import org.jclouds.rest.internal.RestAnnotationProcessor; +import org.testng.annotations.Test; + +import com.abiquo.server.core.enterprise.PrivilegesDto; +import com.abiquo.server.core.enterprise.RoleDto; +import com.abiquo.server.core.enterprise.RolesDto; +import com.abiquo.server.core.enterprise.UserDto; +import com.google.inject.TypeLiteral; + +/** + * Tests annotation parsing of {@code AdminAsyncApi} + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +@Test(groups = "unit", testName = "AdminAsyncApiTest") +public class AdminAsyncApiTest extends BaseAbiquoAsyncApiTest { + /*********************** Role ***********************/ + + public void testListRoles() throws SecurityException, NoSuchMethodException, IOException { + Method method = AdminAsyncApi.class.getMethod("listRoles"); + GeneratedHttpRequest request = processor.createRequest(method); + + assertRequestLineEquals(request, "GET http://localhost/api/admin/roles HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + RolesDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testGetRoleFromUser() throws SecurityException, NoSuchMethodException, IOException { + Method method = AdminAsyncApi.class.getMethod("getRole", UserDto.class); + GeneratedHttpRequest request = processor.createRequest(method, EnterpriseResources.userPut()); + + assertRequestLineEquals(request, "GET http://localhost/api/admin/roles/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + RoleDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); + + checkFilters(request); + } + + public void testCreateRole() throws SecurityException, NoSuchMethodException, IOException { + Method method = AdminAsyncApi.class.getMethod("createRole", RoleDto.class); + GeneratedHttpRequest request = processor.createRequest(method, AdminResources.rolePost()); + + assertRequestLineEquals(request, "POST http://localhost/api/admin/roles HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + RoleDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(AdminResources.rolePostPayload()), RoleDto.class, + RoleDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testDeleteRole() throws SecurityException, NoSuchMethodException { + Method method = AdminAsyncApi.class.getMethod("deleteRole", RoleDto.class); + GeneratedHttpRequest request = processor.createRequest(method, AdminResources.rolePut()); + + assertRequestLineEquals(request, "DELETE http://localhost/api/admin/roles/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testUpdateRole() throws SecurityException, NoSuchMethodException, IOException { + Method method = AdminAsyncApi.class.getMethod("updateRole", RoleDto.class); + GeneratedHttpRequest request = processor.createRequest(method, AdminResources.rolePut()); + + assertRequestLineEquals(request, "PUT http://localhost/api/admin/roles/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + RoleDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(AdminResources.rolePutPayload()), RoleDto.class, RoleDto.BASE_MEDIA_TYPE, + false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testGetRoleById() throws SecurityException, NoSuchMethodException, IOException { + Method method = AdminAsyncApi.class.getMethod("getRole", Integer.class); + GeneratedHttpRequest request = processor.createRequest(method, 1); + + assertRequestLineEquals(request, "GET http://localhost/api/admin/roles/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + RoleDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); + + checkFilters(request); + } + + public void testListPrivilegesByRoles() throws SecurityException, NoSuchMethodException, IOException { + Method method = AdminAsyncApi.class.getMethod("listPrivileges", RoleDto.class); + GeneratedHttpRequest request = processor.createRequest(method, AdminResources.rolePut()); + + assertRequestLineEquals(request, "GET http://localhost/api/admin/roles/1/action/privileges HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + PrivilegesDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + /*********************** Current User **********************/ + + public void testGetCurrentUser() throws SecurityException, NoSuchMethodException, IOException { + Method method = AdminAsyncApi.class.getMethod("getCurrentUser"); + GeneratedHttpRequest request = processor.createRequest(method, 1); + + assertRequestLineEquals(request, "GET http://localhost/api/login HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + UserDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + @Override + protected TypeLiteral> createTypeLiteral() { + return new TypeLiteral>() { + }; + } + +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/features/BaseAbiquoAsyncApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/features/BaseAbiquoAsyncApiTest.java new file mode 100644 index 0000000000..561418f602 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/features/BaseAbiquoAsyncApiTest.java @@ -0,0 +1,92 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.features; + +import static org.jclouds.Constants.PROPERTY_PRETTY_PRINT_PAYLOADS; +import static org.testng.Assert.assertEquals; + +import java.io.IOException; +import java.util.Properties; + +import org.jclouds.abiquo.AbiquoApiMetadata; +import org.jclouds.abiquo.config.AbiquoRestClientModule; +import org.jclouds.abiquo.http.filters.AbiquoAuthentication; +import org.jclouds.abiquo.http.filters.AppendApiVersionToMediaType; +import org.jclouds.http.HttpRequest; +import org.jclouds.providers.AnonymousProviderMetadata; +import org.jclouds.providers.ProviderMetadata; +import org.jclouds.rest.internal.BaseAsyncClientTest; +import org.jclouds.xml.XMLParser; +import org.testng.annotations.BeforeClass; + +import com.abiquo.model.transport.SingleResourceTransportDto; +import com.google.inject.Module; + +/** + * Tests annotation parsing of {@code AbiquoAsyncApi}. + * + * @author Ignasi Barrera + */ +public abstract class BaseAbiquoAsyncApiTest extends BaseAsyncClientTest { + private XMLParser xml; + + @BeforeClass + @Override + protected void setupFactory() throws IOException { + super.setupFactory(); + xml = injector.getInstance(XMLParser.class); + } + + @Override + protected void checkFilters(final HttpRequest request) { + assertEquals(request.getFilters().size(), 2); + assertEquals(request.getFilters().get(0).getClass(), AbiquoAuthentication.class); + assertEquals(request.getFilters().get(1).getClass(), AppendApiVersionToMediaType.class); + } + + @Override + protected Module createModule() { + return new AbiquoRestClientModule(); + } + + @Override + protected ProviderMetadata createProviderMetadata() { + return AnonymousProviderMetadata.forApiWithEndpoint(new AbiquoApiMetadata(), "http://localhost/api"); + } + + @Override + protected Properties setupProperties() { + Properties props = super.setupProperties(); + // Do not pretty print payloads in tests + props.setProperty(PROPERTY_PRETTY_PRINT_PAYLOADS, "false"); + return props; + } + + protected void assertPayloadEquals(final HttpRequest request, final String toMatch, + final Class entityClass, final String contentType, + final boolean contentMD5) throws IOException { + // Make sure we don't have formatting issues + SingleResourceTransportDto entity = xml.fromXML(toMatch, entityClass); + String stringToMatch = xml.toXML(entity, entityClass); + + super.assertPayloadEquals(request, stringToMatch, contentType, contentMD5); + } + +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/features/CloudAsyncApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/features/CloudAsyncApiTest.java new file mode 100644 index 0000000000..9405b0b908 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/features/CloudAsyncApiTest.java @@ -0,0 +1,1262 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.features; + +import static org.jclouds.abiquo.domain.DomainUtils.withHeader; + +import java.io.IOException; +import java.lang.reflect.Method; + +import javax.ws.rs.core.MediaType; + +import org.jclouds.abiquo.domain.CloudResources; +import org.jclouds.abiquo.domain.EnterpriseResources; +import org.jclouds.abiquo.domain.InfrastructureResources; +import org.jclouds.abiquo.domain.NetworkResources; +import org.jclouds.abiquo.domain.cloud.options.VirtualDatacenterOptions; +import org.jclouds.abiquo.domain.cloud.options.VirtualMachineOptions; +import org.jclouds.abiquo.domain.cloud.options.VirtualMachineTemplateOptions; +import org.jclouds.abiquo.domain.cloud.options.VolumeOptions; +import org.jclouds.abiquo.domain.network.options.IpOptions; +import org.jclouds.abiquo.domain.options.search.reference.OrderBy; +import org.jclouds.abiquo.functions.ReturnTaskReferenceOrNull; +import org.jclouds.abiquo.functions.cloud.ReturnMovedVolume; +import org.jclouds.http.functions.ParseXMLWithJAXB; +import org.jclouds.http.functions.ReleasePayloadAndReturn; +import org.jclouds.http.functions.ReturnStringIf2xx; +import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; +import org.jclouds.rest.internal.GeneratedHttpRequest; +import org.jclouds.rest.internal.RestAnnotationProcessor; +import org.testng.annotations.Test; + +import com.abiquo.model.enumerator.HypervisorType; +import com.abiquo.model.rest.RESTLink; +import com.abiquo.model.transport.AcceptedRequestDto; +import com.abiquo.model.transport.LinksDto; +import com.abiquo.server.core.appslibrary.VirtualMachineTemplateDto; +import com.abiquo.server.core.appslibrary.VirtualMachineTemplatesDto; +import com.abiquo.server.core.cloud.VirtualApplianceDto; +import com.abiquo.server.core.cloud.VirtualApplianceStateDto; +import com.abiquo.server.core.cloud.VirtualAppliancesDto; +import com.abiquo.server.core.cloud.VirtualDatacenterDto; +import com.abiquo.server.core.cloud.VirtualDatacentersDto; +import com.abiquo.server.core.cloud.VirtualMachineDto; +import com.abiquo.server.core.cloud.VirtualMachineStateDto; +import com.abiquo.server.core.cloud.VirtualMachineTaskDto; +import com.abiquo.server.core.cloud.VirtualMachineWithNodeExtendedDto; +import com.abiquo.server.core.cloud.VirtualMachinesWithNodeExtendedDto; +import com.abiquo.server.core.enterprise.EnterpriseDto; +import com.abiquo.server.core.infrastructure.DatacenterDto; +import com.abiquo.server.core.infrastructure.network.PrivateIpDto; +import com.abiquo.server.core.infrastructure.network.PrivateIpsDto; +import com.abiquo.server.core.infrastructure.network.PublicIpDto; +import com.abiquo.server.core.infrastructure.network.PublicIpsDto; +import com.abiquo.server.core.infrastructure.network.VLANNetworkDto; +import com.abiquo.server.core.infrastructure.network.VLANNetworksDto; +import com.abiquo.server.core.infrastructure.network.VMNetworkConfigurationsDto; +import com.abiquo.server.core.infrastructure.storage.DiskManagementDto; +import com.abiquo.server.core.infrastructure.storage.DisksManagementDto; +import com.abiquo.server.core.infrastructure.storage.MovedVolumeDto; +import com.abiquo.server.core.infrastructure.storage.TierDto; +import com.abiquo.server.core.infrastructure.storage.TiersDto; +import com.abiquo.server.core.infrastructure.storage.VolumeManagementDto; +import com.abiquo.server.core.infrastructure.storage.VolumesManagementDto; +import com.google.inject.TypeLiteral; + +/** + * Tests annotation parsing of {@code CloudAsyncApi} + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +@Test(groups = "unit", testName = "CloudAsyncApiTest") +public class CloudAsyncApiTest extends BaseAbiquoAsyncApiTest { + /*********************** Virtual Datacenter ***********************/ + + public void testListVirtualDatacentersParams() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("listVirtualDatacenters", VirtualDatacenterOptions.class); + GeneratedHttpRequest request = processor.createRequest(method, VirtualDatacenterOptions.builder().datacenterId(1) + .enterpriseId(1).build()); + + assertRequestLineEquals(request, + "GET http://localhost/api/cloud/virtualdatacenters?datacenter=1&enterprise=1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + VirtualDatacentersDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testListVirtualDatacentersNoParams() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("listVirtualDatacenters", VirtualDatacenterOptions.class); + GeneratedHttpRequest request = processor.createRequest(method, VirtualDatacenterOptions.builder().build()); + + assertRequestLineEquals(request, "GET http://localhost/api/cloud/virtualdatacenters HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + VirtualDatacentersDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testCreateVirtualDatacenter() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("createVirtualDatacenter", VirtualDatacenterDto.class, + DatacenterDto.class, EnterpriseDto.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.virtualDatacenterPost(), + InfrastructureResources.datacenterPut(), EnterpriseResources.enterprisePut()); + + assertRequestLineEquals(request, + "POST http://localhost/api/cloud/virtualdatacenters?enterprise=1&datacenter=1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + VirtualDatacenterDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(CloudResources.virtualDatacenterPostPayload()), + VirtualDatacenterDto.class, VirtualDatacenterDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testGetVirtualDatacenter() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("getVirtualDatacenter", Integer.class); + GeneratedHttpRequest request = processor.createRequest(method, 1); + + assertRequestLineEquals(request, "GET http://localhost/api/cloud/virtualdatacenters/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + VirtualDatacenterDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); + + checkFilters(request); + } + + public void testUpdateVirtualDatacenter() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("updateVirtualDatacenter", VirtualDatacenterDto.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.virtualDatacenterPut()); + + assertRequestLineEquals(request, "PUT http://localhost/api/cloud/virtualdatacenters/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + VirtualDatacenterDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(CloudResources.virtualDatacenterPutPayload()), + VirtualDatacenterDto.class, VirtualDatacenterDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testDeleteVirtualDatacenter() throws SecurityException, NoSuchMethodException { + Method method = CloudAsyncApi.class.getMethod("deleteVirtualDatacenter", VirtualDatacenterDto.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.virtualDatacenterPut()); + + assertRequestLineEquals(request, "DELETE http://localhost/api/cloud/virtualdatacenters/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + /*********************** Ips ***********************/ + + public void testListAvailablePublicIpsWithOptions() throws SecurityException, NoSuchMethodException, IOException { + IpOptions options = IpOptions.builder().limit(5).build(); + Method method = CloudAsyncApi.class.getMethod("listAvailablePublicIps", VirtualDatacenterDto.class, + IpOptions.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.virtualDatacenterPut(), options); + + assertRequestLineEquals(request, + "GET http://localhost/api/cloud/virtualdatacenters/1/publicips/topurchase?limit=5 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + PublicIpsDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testListPurchasedPublicIpsWithOptions() throws SecurityException, NoSuchMethodException, IOException { + IpOptions options = IpOptions.builder().limit(5).build(); + Method method = CloudAsyncApi.class.getMethod("listPurchasedPublicIps", VirtualDatacenterDto.class, + IpOptions.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.virtualDatacenterPut(), options); + + assertRequestLineEquals(request, + "GET http://localhost/api/cloud/virtualdatacenters/1/publicips/purchased?limit=5 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + PublicIpsDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testPurchasePublicIp() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("purchasePublicIp", PublicIpDto.class); + GeneratedHttpRequest request = processor.createRequest(method, NetworkResources.publicIpToPurchase()); + + assertRequestLineEquals(request, + "PUT http://localhost/api/cloud/virtualdatacenters/5/publicips/purchased/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + PublicIpDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testReleasePublicIp() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("releasePublicIp", PublicIpDto.class); + GeneratedHttpRequest request = processor.createRequest(method, NetworkResources.publicIpToRelease()); + + assertRequestLineEquals(request, + "PUT http://localhost/api/cloud/virtualdatacenters/5/publicips/topurchase/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + PublicIpDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + /*********************** Available templates ***********************/ + + public void testListAvailableTemplates() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("listAvailableTemplates", VirtualDatacenterDto.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.virtualDatacenterPut()); + + assertRequestLineEquals(request, "GET http://localhost/api/cloud/virtualdatacenters/1/action/templates HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + VirtualMachineTemplatesDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testListAvailableTemplatesWithOptions() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("listAvailableTemplates", VirtualDatacenterDto.class, + VirtualMachineTemplateOptions.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.virtualDatacenterPut(), + VirtualMachineTemplateOptions.builder().hypervisorType(HypervisorType.XENSERVER).categoryName("Firewalls") + .idTemplate(1).build()); + + assertRequestLineEquals(request, "GET http://localhost/api/cloud/virtualdatacenters/1/action/templates" + + "?hypervisorTypeName=XENSERVER&categoryName=Firewalls&idTemplate=1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + VirtualMachineTemplatesDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + /*********************** Storage Tiers ***********************/ + + public void testListStorageTiers() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("listStorageTiers", VirtualDatacenterDto.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.virtualDatacenterPut()); + + assertRequestLineEquals(request, "GET http://localhost/api/cloud/virtualdatacenters/1/tiers HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + TiersDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testGetStorageTier() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("getStorageTier", VirtualDatacenterDto.class, Integer.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.virtualDatacenterPut(), 1); + + assertRequestLineEquals(request, "GET http://localhost/api/cloud/virtualdatacenters/1/tiers/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + TierDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); + + checkFilters(request); + } + + public void testGetDefaultNetwork() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("getDefaultNetwork", VirtualDatacenterDto.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.virtualDatacenterPut()); + + assertRequestLineEquals(request, "GET http://localhost/api/cloud/virtualdatacenters/1/privatenetworks/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + VLANNetworkDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testSetDefaultNetworkInternal() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("setDefaultNetwork", VirtualDatacenterDto.class, + VLANNetworkDto.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.virtualDatacenterPut(), + NetworkResources.privateNetworkPut()); + + RESTLink netLink = NetworkResources.privateNetworkPut().getEditLink(); + + assertRequestLineEquals(request, + "PUT http://localhost/api/cloud/virtualdatacenters/1/action/defaultvlan HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, withHeader(""), LinksDto.class, LinksDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testSetDefaultNetworkExternal() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("setDefaultNetwork", VirtualDatacenterDto.class, + VLANNetworkDto.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.virtualDatacenterPut(), + NetworkResources.externalNetworkPut()); + + RESTLink netLink = NetworkResources.externalNetworkPut().getEditLink(); + + assertRequestLineEquals(request, + "PUT http://localhost/api/cloud/virtualdatacenters/1/action/defaultvlan HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, withHeader(""), LinksDto.class, LinksDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + /*********************** Private Network ***********************/ + + public void testListPrivateNetworks() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("listPrivateNetworks", VirtualDatacenterDto.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.virtualDatacenterPut()); + + assertRequestLineEquals(request, "GET http://localhost/api/cloud/virtualdatacenters/1/privatenetworks HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + VLANNetworksDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testGetPrivateNetwork() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("getPrivateNetwork", VirtualDatacenterDto.class, Integer.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.virtualDatacenterPut(), 1); + + assertRequestLineEquals(request, "GET http://localhost/api/cloud/virtualdatacenters/1/privatenetworks/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + VLANNetworkDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); + + checkFilters(request); + } + + public void testCreatePrivateNetwork() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("createPrivateNetwork", VirtualDatacenterDto.class, + VLANNetworkDto.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.virtualDatacenterPut(), + NetworkResources.vlanPost()); + + assertRequestLineEquals(request, "POST http://localhost/api/cloud/virtualdatacenters/1/privatenetworks HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + VLANNetworkDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(NetworkResources.vlanNetworkPostPayload()), VLANNetworkDto.class, + VLANNetworkDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testUpdatePrivateNetwork() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("updatePrivateNetwork", VLANNetworkDto.class); + GeneratedHttpRequest request = processor.createRequest(method, NetworkResources.privateNetworkPut()); + + assertRequestLineEquals(request, "PUT http://localhost/api/cloud/virtualdatacenters/1/privatenetworks/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + VLANNetworkDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(NetworkResources.privateNetworkPutPayload()), VLANNetworkDto.class, + VLANNetworkDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testDeletePrivateNetwork() throws SecurityException, NoSuchMethodException { + Method method = CloudAsyncApi.class.getMethod("deletePrivateNetwork", VLANNetworkDto.class); + GeneratedHttpRequest request = processor.createRequest(method, NetworkResources.privateNetworkPut()); + + assertRequestLineEquals(request, + "DELETE http://localhost/api/cloud/virtualdatacenters/1/privatenetworks/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + /*********************** Private Network IPs ***********************/ + + public void testListPrivateNetworkIps() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("listPrivateNetworkIps", VLANNetworkDto.class); + GeneratedHttpRequest request = processor.createRequest(method, NetworkResources.privateNetworkPut()); + + assertRequestLineEquals(request, + "GET http://localhost/api/cloud/virtualdatacenters/1/privatenetworks/1/ips HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + PrivateIpsDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testListPrivateNetworkIpsWithOptions() throws SecurityException, NoSuchMethodException, IOException { + IpOptions options = IpOptions.builder().startWith(10).build(); + Method method = CloudAsyncApi.class.getMethod("listPrivateNetworkIps", VLANNetworkDto.class, IpOptions.class); + GeneratedHttpRequest request = processor.createRequest(method, NetworkResources.privateNetworkPut(), options); + + assertRequestLineEquals(request, + "GET http://localhost/api/cloud/virtualdatacenters/1/privatenetworks/1/ips?startwith=10 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + PrivateIpsDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testGetPrivateNetworkIp() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("getPrivateNetworkIp", VLANNetworkDto.class, Integer.class); + GeneratedHttpRequest request = processor.createRequest(method, NetworkResources.privateNetworkPut(), 1); + + assertRequestLineEquals(request, + "GET http://localhost/api/cloud/virtualdatacenters/1/privatenetworks/1/ips/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + PrivateIpDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + /*********************** Virtual Appliance ***********************/ + + public void testListVirtualAppliances() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("listVirtualAppliances", VirtualDatacenterDto.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.virtualDatacenterPut()); + + assertRequestLineEquals(request, "GET http://localhost/api/cloud/virtualdatacenters/1/virtualappliances HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + VirtualAppliancesDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testGetVirtualAppliance() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("getVirtualAppliance", VirtualDatacenterDto.class, Integer.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.virtualDatacenterPut(), 1); + + assertRequestLineEquals(request, + "GET http://localhost/api/cloud/virtualdatacenters/1/virtualappliances/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + VirtualApplianceDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); + + checkFilters(request); + } + + public void testGetVirtualApplianceState() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("getVirtualApplianceState", VirtualApplianceDto.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.virtualAppliancePut()); + + assertRequestLineEquals(request, + "GET http://localhost/api/cloud/virtualdatacenters/1/virtualappliances/1/state HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + VirtualApplianceStateDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testCreateVirtualAppliance() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("createVirtualAppliance", VirtualDatacenterDto.class, + VirtualApplianceDto.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.virtualDatacenterPut(), + CloudResources.virtualAppliancePost()); + + assertRequestLineEquals(request, + "POST http://localhost/api/cloud/virtualdatacenters/1/virtualappliances HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + VirtualApplianceDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(CloudResources.virtualAppliancePostPayload()), VirtualApplianceDto.class, + VirtualApplianceDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testUpdateVirtualAppliance() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("updateVirtualAppliance", VirtualApplianceDto.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.virtualAppliancePut()); + + assertRequestLineEquals(request, + "PUT http://localhost/api/cloud/virtualdatacenters/1/virtualappliances/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + VirtualApplianceDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(CloudResources.virtualAppliancePutPayload()), VirtualApplianceDto.class, + VirtualApplianceDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testDeleteVirtualAppliance() throws SecurityException, NoSuchMethodException { + Method method = CloudAsyncApi.class.getMethod("deleteVirtualAppliance", VirtualApplianceDto.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.virtualAppliancePut()); + + assertRequestLineEquals(request, + "DELETE http://localhost/api/cloud/virtualdatacenters/1/virtualappliances/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testDeployVirtualAppliance() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("deployVirtualAppliance", VirtualApplianceDto.class, + VirtualMachineTaskDto.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.virtualAppliancePut(), + CloudResources.deployOptions()); + + assertRequestLineEquals(request, + "POST http://localhost/api/cloud/virtualdatacenters/1/virtualappliances/1/action/deploy HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + AcceptedRequestDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(CloudResources.deployPayload()), VirtualMachineTaskDto.class, + VirtualMachineTaskDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testUndeployVirtualAppliance() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("undeployVirtualAppliance", VirtualApplianceDto.class, + VirtualMachineTaskDto.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.virtualAppliancePut(), + CloudResources.undeployOptions()); + + assertRequestLineEquals(request, + "POST http://localhost/api/cloud/virtualdatacenters/1/virtualappliances/1/action/undeploy HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + AcceptedRequestDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(CloudResources.undeployPayload()), VirtualMachineTaskDto.class, + VirtualMachineTaskDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testGetVirtualAppliancePrice() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("getVirtualAppliancePrice", VirtualApplianceDto.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.virtualAppliancePut()); + + assertRequestLineEquals(request, + "GET http://localhost/api/cloud/virtualdatacenters/1/virtualappliances/1/action/price HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + MediaType.TEXT_PLAIN + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ReturnStringIf2xx.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + /*********************** Virtual Machine ***********************/ + + public void testListVirtualMachines() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("listVirtualMachines", VirtualApplianceDto.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.virtualAppliancePut()); + + assertRequestLineEquals(request, + "GET http://localhost/api/cloud/virtualdatacenters/1/virtualappliances/1/virtualmachines HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + VirtualMachinesWithNodeExtendedDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testListVirtualMachinesWithOptions() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("listVirtualMachines", VirtualApplianceDto.class, + VirtualMachineOptions.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.virtualAppliancePut(), + VirtualMachineOptions.builder().disablePagination().build()); + + assertRequestLineEquals(request, + "GET http://localhost/api/cloud/virtualdatacenters/1/virtualappliances/1/virtualmachines?limit=0 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + VirtualMachinesWithNodeExtendedDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testGetVirtualMachine() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("getVirtualMachine", VirtualApplianceDto.class, Integer.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.virtualAppliancePut(), 1); + + assertRequestLineEquals(request, + "GET http://localhost/api/cloud/virtualdatacenters/1/virtualappliances/1/virtualmachines/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + VirtualMachineWithNodeExtendedDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); + + checkFilters(request); + } + + public void testCreateVirtualMachine() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("createVirtualMachine", VirtualApplianceDto.class, + VirtualMachineWithNodeExtendedDto.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.virtualAppliancePut(), + CloudResources.virtualMachinePost()); + + assertRequestLineEquals(request, + "POST http://localhost/api/cloud/virtualdatacenters/1/virtualappliances/1/virtualmachines HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + VirtualMachineWithNodeExtendedDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(CloudResources.virtualMachinePostPayload()), + VirtualMachineWithNodeExtendedDto.class, VirtualMachineWithNodeExtendedDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testUpdateVirtualMachine() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("updateVirtualMachine", VirtualMachineWithNodeExtendedDto.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.virtualMachinePut()); + + assertRequestLineEquals(request, + "PUT http://localhost/api/cloud/virtualdatacenters/1/virtualappliances/1/virtualmachines/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + AcceptedRequestDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(CloudResources.virtualMachinePutPayload()), + VirtualMachineWithNodeExtendedDto.class, VirtualMachineWithNodeExtendedDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ReturnTaskReferenceOrNull.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testUpdateVirtualMachineWithOptions() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("updateVirtualMachine", VirtualMachineWithNodeExtendedDto.class, + VirtualMachineOptions.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.virtualMachinePut(), + VirtualMachineOptions.builder().force(true).build()); + + assertRequestLineEquals(request, + "PUT http://localhost/api/cloud/virtualdatacenters/1/virtualappliances/1/virtualmachines/1?force=true HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + AcceptedRequestDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(CloudResources.virtualMachinePutPayload()), + VirtualMachineWithNodeExtendedDto.class, VirtualMachineWithNodeExtendedDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ReturnTaskReferenceOrNull.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testChangeVirtualMachineState() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("changeVirtualMachineState", VirtualMachineDto.class, + VirtualMachineStateDto.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.virtualMachinePut(), + CloudResources.virtualMachineState()); + + assertRequestLineEquals(request, + "PUT http://localhost/api/cloud/virtualdatacenters/1/virtualappliances/1/virtualmachines/1/state HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + AcceptedRequestDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(CloudResources.virtualMachineStatePayload()), + VirtualMachineStateDto.class, VirtualMachineStateDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testDeleteVirtualMachine() throws SecurityException, NoSuchMethodException { + Method method = CloudAsyncApi.class.getMethod("deleteVirtualMachine", VirtualMachineDto.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.virtualMachinePut()); + + assertRequestLineEquals(request, + "DELETE http://localhost/api/cloud/virtualdatacenters/1/virtualappliances/1/virtualmachines/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testGetVirtualMachineState() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("getVirtualMachineState", VirtualMachineDto.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.virtualMachinePut()); + + assertRequestLineEquals(request, + "GET http://localhost/api/cloud/virtualdatacenters/1/virtualappliances/1/virtualmachines/1/state HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + VirtualMachineStateDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testDeployVirtualMachine() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("deployVirtualMachine", VirtualMachineDto.class, + VirtualMachineTaskDto.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.virtualMachinePut(), + CloudResources.deployOptions()); + + assertRequestLineEquals(request, + "POST http://localhost/api/cloud/virtualdatacenters/1/virtualappliances/1/virtualmachines/1/action/deploy HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + AcceptedRequestDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(CloudResources.deployPayload()), VirtualMachineTaskDto.class, + VirtualMachineTaskDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testUndeployVirtualMachine() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("undeployVirtualMachine", VirtualMachineDto.class, + VirtualMachineTaskDto.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.virtualMachinePut(), + CloudResources.undeployOptions()); + + assertRequestLineEquals(request, + "POST http://localhost/api/cloud/virtualdatacenters/1/virtualappliances/1/virtualmachines/1/action/undeploy HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + AcceptedRequestDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(CloudResources.undeployPayload()), VirtualMachineTaskDto.class, + VirtualMachineTaskDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testRebootVirtualMachine() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("rebootVirtualMachine", VirtualMachineDto.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.virtualMachinePut()); + + assertRequestLineEquals(request, + "POST http://localhost/api/cloud/virtualdatacenters/1/virtualappliances/1/virtualmachines/1/action/reset HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + AcceptedRequestDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testListNetworkConfigurations() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("listNetworkConfigurations", VirtualMachineDto.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.virtualMachinePut()); + + assertRequestLineEquals( + request, + "GET http://localhost/api/cloud/virtualdatacenters/1/virtualappliances/1/virtualmachines/1/network/configurations HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + VMNetworkConfigurationsDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testSetGatewayNetwork() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("setGatewayNetwork", VirtualMachineDto.class, VLANNetworkDto.class); + + VirtualMachineDto vm = CloudResources.virtualMachinePut(); + VLANNetworkDto network = NetworkResources.privateNetworkPut(); + + GeneratedHttpRequest request = processor.createRequest(method, vm, network); + + String configLink = vm.searchLink("configurations").getHref() + "/" + network.getId(); + + assertRequestLineEquals( + request, + "PUT http://localhost/api/cloud/virtualdatacenters/1/virtualappliances/1/virtualmachines/1/network/configurations HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, withHeader(""), LinksDto.class, LinksDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + /*********************** Virtual Machine Template ***********************/ + + public void testGetVirtualMachineTemplate() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("getVirtualMachineTemplate", VirtualMachineDto.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.virtualMachinePut()); + + assertRequestLineEquals(request, + "GET http://localhost/api/admin/enterprises/1/datacenterrepositories/1/virtualmachinetemplates/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + VirtualMachineTemplateDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testListAttachedVolumes() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("listAttachedVolumes", VirtualMachineDto.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.virtualMachinePut()); + + assertRequestLineEquals(request, + "GET http://localhost/api/cloud/virtualdatacenters/1/virtualappliances/1/virtualmachines/1/storage/volumes HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + VolumesManagementDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testDetachAllVolumes() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("detachAllVolumes", VirtualMachineDto.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.virtualMachinePut()); + + assertRequestLineEquals(request, + "DELETE http://localhost/api/cloud/virtualdatacenters/1/virtualappliances/1/virtualmachines/1/storage/volumes HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + AcceptedRequestDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ReturnTaskReferenceOrNull.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testReplaceVolumes() throws SecurityException, NoSuchMethodException, IOException { + VolumeManagementDto first = CloudResources.volumePut(); + VolumeManagementDto second = CloudResources.volumePut(); + second.getEditLink().setHref(second.getEditLink().getHref() + "second"); + + Method method = CloudAsyncApi.class.getMethod("replaceVolumes", VirtualMachineDto.class, + VirtualMachineOptions.class, VolumeManagementDto[].class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.virtualMachinePut(), + VirtualMachineOptions.builder().force(true).build(), new VolumeManagementDto[] { first, second }); + + String editLink = CloudResources.volumePut().getEditLink().getHref(); + assertRequestLineEquals( + request, + "PUT http://localhost/api/cloud/virtualdatacenters/1/virtualappliances/1/virtualmachines/1/storage/volumes?force=true HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + AcceptedRequestDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(""), LinksDto.class, LinksDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ReturnTaskReferenceOrNull.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testListAttachedHardDisks() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("listAttachedHardDisks", VirtualMachineDto.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.virtualMachinePut()); + + assertRequestLineEquals(request, + "GET http://localhost/api/cloud/virtualdatacenters/1/virtualappliances/1/virtualmachines/1/storage/disks HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + DisksManagementDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testDetachAllHardDisks() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("detachAllHardDisks", VirtualMachineDto.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.virtualMachinePut()); + + assertRequestLineEquals(request, + "DELETE http://localhost/api/cloud/virtualdatacenters/1/virtualappliances/1/virtualmachines/1/storage/disks HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + AcceptedRequestDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ReturnTaskReferenceOrNull.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testReplaceHardDisks() throws SecurityException, NoSuchMethodException, IOException { + DiskManagementDto first = CloudResources.hardDiskPut(); + DiskManagementDto second = CloudResources.hardDiskPut(); + second.getEditLink().setHref(second.getEditLink().getHref() + "second"); + + Method method = CloudAsyncApi.class.getMethod("replaceHardDisks", VirtualMachineDto.class, + DiskManagementDto[].class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.virtualMachinePut(), + new DiskManagementDto[] { first, second }); + + String editLink = CloudResources.hardDiskPut().getEditLink().getHref(); + assertRequestLineEquals(request, + "PUT http://localhost/api/cloud/virtualdatacenters/1/virtualappliances/1/virtualmachines/1/storage/disks HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + AcceptedRequestDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(""), LinksDto.class, LinksDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ReturnTaskReferenceOrNull.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + /*********************** Hard disks ***********************/ + + public void testListHardDisks() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("listHardDisks", VirtualDatacenterDto.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.virtualDatacenterPut()); + + assertRequestLineEquals(request, "GET http://localhost/api/cloud/virtualdatacenters/1/disks HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + DisksManagementDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testGetHardDisk() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("getHardDisk", VirtualDatacenterDto.class, Integer.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.virtualDatacenterPut(), 1); + + assertRequestLineEquals(request, "GET http://localhost/api/cloud/virtualdatacenters/1/disks/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + DiskManagementDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); + + checkFilters(request); + } + + public void testCreateHardDisk() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("createHardDisk", VirtualDatacenterDto.class, + DiskManagementDto.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.virtualDatacenterPut(), + CloudResources.hardDiskPost()); + + assertRequestLineEquals(request, "POST http://localhost/api/cloud/virtualdatacenters/1/disks HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + DiskManagementDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(CloudResources.hardDiskPostPayload()), DiskManagementDto.class, + DiskManagementDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testDeleteHardDisk() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("deleteHardDisk", DiskManagementDto.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.hardDiskPut()); + + assertRequestLineEquals(request, "DELETE http://localhost/api/cloud/virtualdatacenters/1/disks/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + /*********************** Volumes ***********************/ + + public void testListVolumes() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("listVolumes", VirtualDatacenterDto.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.virtualDatacenterPut()); + + assertRequestLineEquals(request, "GET http://localhost/api/cloud/virtualdatacenters/1/volumes HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + VolumesManagementDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testListVolumesWithOptions() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("listVolumes", VirtualDatacenterDto.class, VolumeOptions.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.virtualDatacenterPut(), + VolumeOptions.builder().onlyAvailable(true).build()); + + assertRequestLineEquals(request, + "GET http://localhost/api/cloud/virtualdatacenters/1/volumes?available=true HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + VolumesManagementDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testListVolumesWithFilterOptions() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("listVolumes", VirtualDatacenterDto.class, VolumeOptions.class); + + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.virtualDatacenterPut(), + VolumeOptions.builder().has("vol").orderBy(OrderBy.NAME).ascendant(true).build()); + + assertRequestLineEquals(request, + "GET http://localhost/api/cloud/virtualdatacenters/1/volumes?has=vol&by=name&asc=true HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + VolumesManagementDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testGetVolume() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("getVolume", VirtualDatacenterDto.class, Integer.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.virtualDatacenterPut(), 1); + + assertRequestLineEquals(request, "GET http://localhost/api/cloud/virtualdatacenters/1/volumes/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + VolumeManagementDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); + + checkFilters(request); + } + + public void testCreateVolume() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("createVolume", VirtualDatacenterDto.class, + VolumeManagementDto.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.virtualDatacenterPut(), + CloudResources.volumePost()); + + assertRequestLineEquals(request, "POST http://localhost/api/cloud/virtualdatacenters/1/volumes HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + VolumeManagementDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(CloudResources.volumePostPayload()), VolumeManagementDto.class, + VolumeManagementDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testUpdateVolume() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("updateVolume", VolumeManagementDto.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.volumePut()); + + assertRequestLineEquals(request, "PUT http://localhost/api/cloud/virtualdatacenters/1/volumes/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + AcceptedRequestDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(CloudResources.volumePutPayload()), VolumeManagementDto.class, + VolumeManagementDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ReturnTaskReferenceOrNull.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testDeleteVolume() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class.getMethod("deleteVolume", VolumeManagementDto.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.volumePut()); + + assertRequestLineEquals(request, "DELETE http://localhost/api/cloud/virtualdatacenters/1/volumes/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testMoveVolume() throws SecurityException, NoSuchMethodException, IOException { + Method method = CloudAsyncApi.class + .getMethod("moveVolume", VolumeManagementDto.class, VirtualDatacenterDto.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.volumePut(), + CloudResources.virtualDatacenterPut()); + + assertRequestLineEquals(request, + "POST http://localhost/api/cloud/virtualdatacenters/1/volumes/1/action/move HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + MovedVolumeDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(CloudResources.virtualDatacenterRefPayload()), LinksDto.class, + LinksDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnMovedVolume.class); + + checkFilters(request); + } + + @Override + protected TypeLiteral> createTypeLiteral() { + return new TypeLiteral>() { + }; + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/features/ConfigAsyncApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/features/ConfigAsyncApiTest.java new file mode 100644 index 0000000000..816bd59dee --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/features/ConfigAsyncApiTest.java @@ -0,0 +1,283 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.features; + +import static org.jclouds.abiquo.domain.DomainUtils.withHeader; + +import java.io.IOException; +import java.lang.reflect.Method; + +import org.jclouds.abiquo.domain.ConfigResources; +import org.jclouds.abiquo.domain.config.options.LicenseOptions; +import org.jclouds.abiquo.domain.config.options.PropertyOptions; +import org.jclouds.http.functions.ParseXMLWithJAXB; +import org.jclouds.http.functions.ReleasePayloadAndReturn; +import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; +import org.jclouds.rest.internal.GeneratedHttpRequest; +import org.jclouds.rest.internal.RestAnnotationProcessor; +import org.testng.annotations.Test; + +import com.abiquo.server.core.appslibrary.CategoriesDto; +import com.abiquo.server.core.appslibrary.CategoryDto; +import com.abiquo.server.core.config.LicenseDto; +import com.abiquo.server.core.config.LicensesDto; +import com.abiquo.server.core.config.SystemPropertiesDto; +import com.abiquo.server.core.config.SystemPropertyDto; +import com.abiquo.server.core.enterprise.PrivilegeDto; +import com.abiquo.server.core.enterprise.PrivilegesDto; +import com.google.inject.TypeLiteral; + +/** + * Tests annotation parsing of {@code AdminAsyncApi}. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +@Test(groups = "unit", testName = "ConfigAsyncApiTest") +public class ConfigAsyncApiTest extends BaseAbiquoAsyncApiTest { + /*********************** License ***********************/ + + public void testListLicenses() throws SecurityException, NoSuchMethodException, IOException { + Method method = ConfigAsyncApi.class.getMethod("listLicenses"); + GeneratedHttpRequest request = processor.createRequest(method); + + assertRequestLineEquals(request, "GET http://localhost/api/config/licenses HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + LicensesDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testListLicenseWithOptions() throws SecurityException, NoSuchMethodException, IOException { + Method method = ConfigAsyncApi.class.getMethod("listLicenses", LicenseOptions.class); + GeneratedHttpRequest request = processor.createRequest(method, LicenseOptions.builder().active(true).build()); + + assertRequestLineEquals(request, "GET http://localhost/api/config/licenses?active=true HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + LicensesDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testAddLicense() throws SecurityException, NoSuchMethodException, IOException { + Method method = ConfigAsyncApi.class.getMethod("addLicense", LicenseDto.class); + GeneratedHttpRequest request = processor.createRequest(method, ConfigResources.licensePost()); + + assertRequestLineEquals(request, "POST http://localhost/api/config/licenses HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + LicenseDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(ConfigResources.licensePostPayload()), LicenseDto.class, + LicenseDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testRemoveLicense() throws SecurityException, NoSuchMethodException, IOException { + Method method = ConfigAsyncApi.class.getMethod("removeLicense", LicenseDto.class); + GeneratedHttpRequest request = processor.createRequest(method, ConfigResources.licensePut()); + + assertRequestLineEquals(request, "DELETE http://localhost/api/config/licenses/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + /*********************** Privilege ***********************/ + + public void testListPrivileges() throws SecurityException, NoSuchMethodException, IOException { + Method method = ConfigAsyncApi.class.getMethod("listPrivileges"); + GeneratedHttpRequest request = processor.createRequest(method); + + assertRequestLineEquals(request, "GET http://localhost/api/config/privileges HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + PrivilegesDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testGetPrivilege() throws SecurityException, NoSuchMethodException, IOException { + Method method = ConfigAsyncApi.class.getMethod("getPrivilege", Integer.class); + GeneratedHttpRequest request = processor.createRequest(method, 1); + + assertRequestLineEquals(request, "GET http://localhost/api/config/privileges/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + PrivilegeDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); + + checkFilters(request); + } + + /*********************** System Properties ***********************/ + + public void testListSystemProperties() throws SecurityException, NoSuchMethodException, IOException { + Method method = ConfigAsyncApi.class.getMethod("listSystemProperties"); + GeneratedHttpRequest request = processor.createRequest(method); + + assertRequestLineEquals(request, "GET http://localhost/api/config/properties HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + SystemPropertiesDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testListSystemPropertiesWithOptions() throws SecurityException, NoSuchMethodException, IOException { + Method method = ConfigAsyncApi.class.getMethod("listSystemProperties", PropertyOptions.class); + GeneratedHttpRequest request = processor + .createRequest(method, PropertyOptions.builder().component("api").build()); + + assertRequestLineEquals(request, "GET http://localhost/api/config/properties?component=api HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + SystemPropertiesDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testUpdateSystemProperty() throws SecurityException, NoSuchMethodException, IOException { + Method method = ConfigAsyncApi.class.getMethod("updateSystemProperty", SystemPropertyDto.class); + GeneratedHttpRequest request = processor.createRequest(method, ConfigResources.propertyPut()); + + assertRequestLineEquals(request, "PUT http://localhost/api/config/properties/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + SystemPropertyDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(ConfigResources.propertyPutPayload()), SystemPropertyDto.class, + SystemPropertyDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + /*********************** Category ***********************/ + + public void testListCategories() throws SecurityException, NoSuchMethodException, IOException { + Method method = ConfigAsyncApi.class.getMethod("listCategories"); + GeneratedHttpRequest request = processor.createRequest(method); + + assertRequestLineEquals(request, "GET http://localhost/api/config/categories HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + CategoriesDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testGetCategory() throws SecurityException, NoSuchMethodException, IOException { + Method method = ConfigAsyncApi.class.getMethod("getCategory", Integer.class); + GeneratedHttpRequest request = processor.createRequest(method, 1); + + assertRequestLineEquals(request, "GET http://localhost/api/config/categories/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + CategoryDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); + + checkFilters(request); + } + + public void testCreateCategory() throws SecurityException, NoSuchMethodException, IOException { + Method method = ConfigAsyncApi.class.getMethod("createCategory", CategoryDto.class); + GeneratedHttpRequest request = processor.createRequest(method, ConfigResources.categoryPost()); + + assertRequestLineEquals(request, "POST http://localhost/api/config/categories HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + CategoryDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(ConfigResources.categoryPostPayload()), CategoryDto.class, + CategoryDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testUpdateCategory() throws SecurityException, NoSuchMethodException, IOException { + Method method = ConfigAsyncApi.class.getMethod("updateCategory", CategoryDto.class); + GeneratedHttpRequest request = processor.createRequest(method, ConfigResources.categoryPut()); + + assertRequestLineEquals(request, "PUT http://localhost/api/config/categories/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + CategoryDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(ConfigResources.categoryPutPayload()), CategoryDto.class, + CategoryDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testDeleteCategory() throws SecurityException, NoSuchMethodException { + Method method = ConfigAsyncApi.class.getMethod("deleteCategory", CategoryDto.class); + GeneratedHttpRequest request = processor.createRequest(method, ConfigResources.categoryPut()); + + assertRequestLineEquals(request, "DELETE http://localhost/api/config/categories/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + @Override + protected TypeLiteral> createTypeLiteral() { + return new TypeLiteral>() { + }; + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/features/EnterpriseAsyncApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/features/EnterpriseAsyncApiTest.java new file mode 100644 index 0000000000..a38cbc7c32 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/features/EnterpriseAsyncApiTest.java @@ -0,0 +1,661 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.features; + +import static org.jclouds.abiquo.domain.DomainUtils.withHeader; + +import java.io.IOException; +import java.lang.reflect.Method; + +import org.jclouds.abiquo.domain.EnterpriseResources; +import org.jclouds.abiquo.domain.InfrastructureResources; +import org.jclouds.abiquo.domain.enterprise.options.EnterpriseOptions; +import org.jclouds.abiquo.domain.options.search.reference.OrderBy; +import org.jclouds.http.functions.ParseXMLWithJAXB; +import org.jclouds.http.functions.ReleasePayloadAndReturn; +import org.jclouds.rest.functions.MapHttp4xxCodesToExceptions; +import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; +import org.jclouds.rest.internal.GeneratedHttpRequest; +import org.jclouds.rest.internal.RestAnnotationProcessor; +import org.testng.annotations.Test; + +import com.abiquo.am.model.TemplatesStateDto; +import com.abiquo.server.core.appslibrary.DatacenterRepositoryDto; +import com.abiquo.server.core.appslibrary.TemplateDefinitionListDto; +import com.abiquo.server.core.appslibrary.TemplateDefinitionListsDto; +import com.abiquo.server.core.cloud.VirtualAppliancesDto; +import com.abiquo.server.core.cloud.VirtualDatacentersDto; +import com.abiquo.server.core.cloud.VirtualMachinesWithNodeExtendedDto; +import com.abiquo.server.core.enterprise.DatacenterLimitsDto; +import com.abiquo.server.core.enterprise.DatacentersLimitsDto; +import com.abiquo.server.core.enterprise.EnterpriseDto; +import com.abiquo.server.core.enterprise.EnterprisePropertiesDto; +import com.abiquo.server.core.enterprise.EnterprisesDto; +import com.abiquo.server.core.enterprise.UserDto; +import com.abiquo.server.core.enterprise.UsersDto; +import com.abiquo.server.core.infrastructure.DatacenterDto; +import com.abiquo.server.core.infrastructure.DatacentersDto; +import com.abiquo.server.core.infrastructure.MachinesDto; +import com.abiquo.server.core.infrastructure.network.VLANNetworksDto; +import com.google.inject.TypeLiteral; + +/** + * Tests annotation parsing of {@code EnterpriseAsyncApi} + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +@Test(groups = "unit", testName = "EnterpriseAsyncApiTest") +public class EnterpriseAsyncApiTest extends BaseAbiquoAsyncApiTest { + /*********************** Enterprise ********************** */ + + public void testListEnterprises() throws SecurityException, NoSuchMethodException, IOException { + Method method = EnterpriseAsyncApi.class.getMethod("listEnterprises"); + GeneratedHttpRequest request = processor.createRequest(method); + + assertRequestLineEquals(request, "GET http://localhost/api/admin/enterprises HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + EnterprisesDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testListEnterprisesWithOptions() throws SecurityException, NoSuchMethodException, IOException { + EnterpriseOptions options = EnterpriseOptions.builder().has("abi").orderBy(OrderBy.NAME).ascendant(true).build(); + + Method method = EnterpriseAsyncApi.class.getMethod("listEnterprises", EnterpriseOptions.class); + GeneratedHttpRequest request = processor.createRequest(method, options); + + assertRequestLineEquals(request, "GET http://localhost/api/admin/enterprises?has=abi&by=name&asc=true HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + EnterprisesDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testListEnterprisesByDatacenter() throws SecurityException, NoSuchMethodException, IOException { + EnterpriseOptions options = EnterpriseOptions.builder().startWith(0).limit(25).network(true).build(); + + Method method = EnterpriseAsyncApi.class.getMethod("listEnterprises", DatacenterDto.class, + EnterpriseOptions.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.datacenterPut(), options); + + assertRequestLineEquals(request, + "GET http://localhost/api/admin/datacenters/1/action/enterprises?network=true&startwith=0&limit=25 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + EnterprisesDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testCreateEnterprise() throws SecurityException, NoSuchMethodException, IOException { + Method method = EnterpriseAsyncApi.class.getMethod("createEnterprise", EnterpriseDto.class); + GeneratedHttpRequest request = processor.createRequest(method, EnterpriseResources.enterprisePost()); + + assertRequestLineEquals(request, "POST http://localhost/api/admin/enterprises HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + EnterpriseDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(EnterpriseResources.enterprisePostPayload()), EnterpriseDto.class, + EnterpriseDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testGetEnterprise() throws SecurityException, NoSuchMethodException, IOException { + Method method = EnterpriseAsyncApi.class.getMethod("getEnterprise", Integer.class); + GeneratedHttpRequest request = processor.createRequest(method, 1); + + assertRequestLineEquals(request, "GET http://localhost/api/admin/enterprises/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + EnterpriseDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); + + checkFilters(request); + } + + public void testUpdateEnterprise() throws SecurityException, NoSuchMethodException, IOException { + Method method = EnterpriseAsyncApi.class.getMethod("updateEnterprise", EnterpriseDto.class); + GeneratedHttpRequest request = processor.createRequest(method, EnterpriseResources.enterprisePut()); + + assertRequestLineEquals(request, "PUT http://localhost/api/admin/enterprises/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + EnterpriseDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(EnterpriseResources.enterprisePutPayload()), EnterpriseDto.class, + EnterpriseDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testDeleteEnterprise() throws SecurityException, NoSuchMethodException { + Method method = EnterpriseAsyncApi.class.getMethod("deleteEnterprise", EnterpriseDto.class); + GeneratedHttpRequest request = processor.createRequest(method, EnterpriseResources.enterprisePut()); + + assertRequestLineEquals(request, "DELETE http://localhost/api/admin/enterprises/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testListAllowedDatacenters() throws SecurityException, NoSuchMethodException, IOException { + Method method = EnterpriseAsyncApi.class.getMethod("listAllowedDatacenters", Integer.class); + GeneratedHttpRequest request = processor.createRequest(method, 1); + + assertRequestLineEquals(request, "GET http://localhost/api/admin/datacenters?idEnterprise=1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + DatacentersDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testListVirtualDatacentersFromEnterprise() throws SecurityException, NoSuchMethodException, IOException { + Method method = EnterpriseAsyncApi.class.getMethod("listVirtualDatacenters", EnterpriseDto.class); + GeneratedHttpRequest request = processor.createRequest(method, EnterpriseResources.enterprisePut()); + + assertRequestLineEquals(request, + "GET http://localhost/api/admin/enterprises/1/action/virtualdatacenters HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + VirtualDatacentersDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + /*********************** Enterprise Properties ********************** */ + + public void testGetEnterpriseProperties() throws SecurityException, NoSuchMethodException, IOException { + Method method = EnterpriseAsyncApi.class.getMethod("getEnterpriseProperties", EnterpriseDto.class); + GeneratedHttpRequest request = processor.createRequest(method, EnterpriseResources.enterprisePut()); + + assertRequestLineEquals(request, "GET http://localhost/api/admin/enterprises/1/properties HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + EnterprisePropertiesDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, MapHttp4xxCodesToExceptions.class); + + checkFilters(request); + } + + public void testUpdateEnterpriseProperties() throws SecurityException, NoSuchMethodException, IOException { + Method method = EnterpriseAsyncApi.class.getMethod("updateEnterpriseProperties", EnterprisePropertiesDto.class); + GeneratedHttpRequest request = processor.createRequest(method, EnterpriseResources.enterprisePropertiesPut()); + + assertRequestLineEquals(request, "PUT http://localhost/api/admin/enterprises/1/properties HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + EnterprisePropertiesDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(EnterpriseResources.enterprisePropertiesPutPayload()), + EnterprisePropertiesDto.class, EnterprisePropertiesDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + /*********************** Enterprise Limits ********************** */ + + public void testCreateLimits() throws SecurityException, NoSuchMethodException, IOException { + EnterpriseDto enterprise = EnterpriseResources.enterprisePut(); + DatacenterDto datacenter = InfrastructureResources.datacenterPut(); + DatacenterLimitsDto limits = EnterpriseResources.datacenterLimitsPost(); + + Method method = EnterpriseAsyncApi.class.getMethod("createLimits", EnterpriseDto.class, DatacenterDto.class, + DatacenterLimitsDto.class); + GeneratedHttpRequest request = processor.createRequest(method, enterprise, datacenter, limits); + + String limitsUri = enterprise.searchLink("limits").getHref(); + String requestURI = String.format("POST %s?datacenter=%d HTTP/1.1", limitsUri, datacenter.getId()); + + assertRequestLineEquals(request, requestURI); + assertNonPayloadHeadersEqual(request, "Accept: " + DatacenterLimitsDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(EnterpriseResources.datacenterLimitsPostPayload()), + DatacenterLimitsDto.class, DatacenterLimitsDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testGetLimits() throws SecurityException, NoSuchMethodException, IOException { + EnterpriseDto enterprise = EnterpriseResources.enterprisePut(); + DatacenterDto datacenter = InfrastructureResources.datacenterPut(); + + Method method = EnterpriseAsyncApi.class.getMethod("getLimits", EnterpriseDto.class, DatacenterDto.class); + GeneratedHttpRequest request = processor.createRequest(method, enterprise, datacenter); + + String limitsUri = enterprise.searchLink("limits").getHref(); + String requestURI = String.format("GET %s?datacenter=%d HTTP/1.1", limitsUri, datacenter.getId()); + + assertRequestLineEquals(request, requestURI); + assertNonPayloadHeadersEqual(request, "Accept: " + DatacentersLimitsDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); + + checkFilters(request); + } + + public void testUpdateLimits() throws SecurityException, NoSuchMethodException, IOException { + EnterpriseDto enterprise = EnterpriseResources.enterprisePut(); + + Method method = EnterpriseAsyncApi.class.getMethod("updateLimits", DatacenterLimitsDto.class); + GeneratedHttpRequest request = processor.createRequest(method, + EnterpriseResources.datacenterLimitsPut(enterprise)); + + assertRequestLineEquals(request, "PUT http://localhost/api/admin/enterprises/1/limits/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + DatacenterLimitsDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(EnterpriseResources.datacenterLimitsPutPayload(enterprise)), + DatacenterLimitsDto.class, DatacenterLimitsDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testDeleteLimits() throws SecurityException, NoSuchMethodException { + EnterpriseDto enterprise = EnterpriseResources.enterprisePut(); + + Method method = EnterpriseAsyncApi.class.getMethod("deleteLimits", DatacenterLimitsDto.class); + GeneratedHttpRequest request = processor.createRequest(method, + EnterpriseResources.datacenterLimitsPut(enterprise)); + + assertRequestLineEquals(request, "DELETE http://localhost/api/admin/enterprises/1/limits/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testListLimitsEnterprise() throws SecurityException, NoSuchMethodException, IOException { + Method method = EnterpriseAsyncApi.class.getMethod("listLimits", EnterpriseDto.class); + GeneratedHttpRequest request = processor.createRequest(method, EnterpriseResources.enterprisePut()); + + assertRequestLineEquals(request, "GET http://localhost/api/admin/enterprises/1/limits HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + DatacentersLimitsDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + /*********************** User ***********************/ + + public void testGetUser() throws SecurityException, NoSuchMethodException, IOException { + Method method = EnterpriseAsyncApi.class.getMethod("getUser", EnterpriseDto.class, Integer.class); + GeneratedHttpRequest request = processor.createRequest(method, EnterpriseResources.enterprisePut(), 1); + + assertRequestLineEquals(request, "GET http://localhost/api/admin/enterprises/1/users/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + UserDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); + + checkFilters(request); + } + + public void testListUsers() throws SecurityException, NoSuchMethodException, IOException { + Method method = EnterpriseAsyncApi.class.getMethod("listUsers", EnterpriseDto.class); + GeneratedHttpRequest request = processor.createRequest(method, EnterpriseResources.enterprisePut()); + + assertRequestLineEquals(request, "GET http://localhost/api/admin/enterprises/1/users HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + UsersDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testCreateUser() throws SecurityException, NoSuchMethodException, IOException { + EnterpriseDto enterprise = EnterpriseResources.enterprisePut(); + UserDto user = EnterpriseResources.userPost(); + + Method method = EnterpriseAsyncApi.class.getMethod("createUser", EnterpriseDto.class, UserDto.class); + GeneratedHttpRequest request = processor.createRequest(method, enterprise, user); + + assertRequestLineEquals(request, "POST http://localhost/api/admin/enterprises/1/users HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + UserDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(EnterpriseResources.userPostPayload()), UserDto.class, + UserDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testUpdateUser() throws SecurityException, NoSuchMethodException, IOException { + Method method = EnterpriseAsyncApi.class.getMethod("updateUser", UserDto.class); + GeneratedHttpRequest request = processor.createRequest(method, EnterpriseResources.userPut()); + + assertRequestLineEquals(request, "PUT http://localhost/api/admin/enterprises/1/users/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + UserDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(EnterpriseResources.userPutPayload()), UserDto.class, + UserDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testDeleteUser() throws SecurityException, NoSuchMethodException { + Method method = EnterpriseAsyncApi.class.getMethod("deleteUser", UserDto.class); + GeneratedHttpRequest request = processor.createRequest(method, EnterpriseResources.userPut()); + + assertRequestLineEquals(request, "DELETE http://localhost/api/admin/enterprises/1/users/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testListVirtualMachinesByUser() throws SecurityException, NoSuchMethodException, IOException { + Method method = EnterpriseAsyncApi.class.getMethod("listVirtualMachines", UserDto.class); + GeneratedHttpRequest request = processor.createRequest(method, EnterpriseResources.userPut()); + + assertRequestLineEquals(request, + "GET http://localhost/api/admin/enterprises/1/users/1/action/virtualmachines HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + VirtualMachinesWithNodeExtendedDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + /*********************** Datacenter Repository ********************** */ + + public void testGetDatacenterRepository() throws SecurityException, NoSuchMethodException, IOException { + Method method = EnterpriseAsyncApi.class.getMethod("getDatacenterRepository", EnterpriseDto.class, Integer.class); + GeneratedHttpRequest request = processor.createRequest(method, EnterpriseResources.enterprisePut(), + InfrastructureResources.datacenterPut().getId()); + + assertRequestLineEquals(request, "GET http://localhost/api/admin/enterprises/1/datacenterrepositories/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + DatacenterRepositoryDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); + + checkFilters(request); + } + + public void testRefreshTemplateRepository() throws SecurityException, NoSuchMethodException, IOException { + Method method = EnterpriseAsyncApi.class.getMethod("refreshTemplateRepository", Integer.class, Integer.class); + GeneratedHttpRequest request = processor.createRequest(method, EnterpriseResources.enterprisePut().getId(), + InfrastructureResources.datacenterPut().getId()); + + assertRequestLineEquals(request, + "PUT http://localhost/api/admin/enterprises/1/datacenterrepositories/1/actions/refresh HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + /*********************** External Network ********************** */ + + public void testListExternalNetworks() throws SecurityException, NoSuchMethodException, IOException { + Method method = EnterpriseAsyncApi.class.getMethod("listExternalNetworks", EnterpriseDto.class); + GeneratedHttpRequest request = processor.createRequest(method, EnterpriseResources.enterprisePut()); + + assertRequestLineEquals(request, "GET http://localhost/api/admin/enterprises/1/action/externalnetworks HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + VLANNetworksDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + /*********************** Cloud ********************** */ + + public void testListVirtualMachines() throws SecurityException, NoSuchMethodException, IOException { + Method method = EnterpriseAsyncApi.class.getMethod("listVirtualMachines", EnterpriseDto.class); + GeneratedHttpRequest request = processor.createRequest(method, EnterpriseResources.enterprisePut()); + + assertRequestLineEquals(request, "GET http://localhost/api/admin/enterprises/1/action/virtualmachines HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + VirtualMachinesWithNodeExtendedDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testListVirtualAppliances() throws SecurityException, NoSuchMethodException, IOException { + Method method = EnterpriseAsyncApi.class.getMethod("listVirtualAppliances", EnterpriseDto.class); + GeneratedHttpRequest request = processor.createRequest(method, EnterpriseResources.enterprisePut()); + + assertRequestLineEquals(request, "GET http://localhost/api/admin/enterprises/1/action/virtualappliances HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + VirtualAppliancesDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + /*********************** Machine ********************** */ + + public void testListReservedMachines() throws SecurityException, NoSuchMethodException, IOException { + Method method = EnterpriseAsyncApi.class.getMethod("listReservedMachines", EnterpriseDto.class); + GeneratedHttpRequest request = processor.createRequest(method, EnterpriseResources.enterprisePut()); + + assertRequestLineEquals(request, "GET http://localhost/api/admin/enterprises/1/reservedmachines HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + MachinesDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + /*********************** Template definition list ***********************/ + + public void testListTemplateDefinitionLists() throws SecurityException, NoSuchMethodException, IOException { + Method method = EnterpriseAsyncApi.class.getMethod("listTemplateDefinitionLists", EnterpriseDto.class); + GeneratedHttpRequest request = processor.createRequest(method, EnterpriseResources.enterprisePut()); + + assertRequestLineEquals(request, + "GET http://localhost/api/admin/enterprises/1/appslib/templateDefinitionLists HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + TemplateDefinitionListsDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testCreateTemplateDefinitionList() throws SecurityException, NoSuchMethodException, IOException { + EnterpriseDto enterprise = EnterpriseResources.enterprisePut(); + TemplateDefinitionListDto template = EnterpriseResources.templateListPost(); + + Method method = EnterpriseAsyncApi.class.getMethod("createTemplateDefinitionList", EnterpriseDto.class, + TemplateDefinitionListDto.class); + GeneratedHttpRequest request = processor.createRequest(method, enterprise, template); + + assertRequestLineEquals(request, + "POST http://localhost/api/admin/enterprises/1/appslib/templateDefinitionLists HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + TemplateDefinitionListDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(EnterpriseResources.templateListPostPayload()), + TemplateDefinitionListDto.class, TemplateDefinitionListDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testUpdateTemplateDefinitionList() throws SecurityException, NoSuchMethodException, IOException { + TemplateDefinitionListDto template = EnterpriseResources.templateListPut(); + + Method method = EnterpriseAsyncApi.class.getMethod("updateTemplateDefinitionList", + TemplateDefinitionListDto.class); + GeneratedHttpRequest request = processor.createRequest(method, template); + + assertRequestLineEquals(request, + "PUT http://localhost/api/admin/enterprises/1/appslib/templateDefinitionLists/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + TemplateDefinitionListDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(EnterpriseResources.templateListPutPayload()), + TemplateDefinitionListDto.class, TemplateDefinitionListDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testDeleteTemplateDefinitionList() throws SecurityException, NoSuchMethodException { + Method method = EnterpriseAsyncApi.class.getMethod("deleteTemplateDefinitionList", + TemplateDefinitionListDto.class); + GeneratedHttpRequest request = processor.createRequest(method, EnterpriseResources.templateListPut()); + + assertRequestLineEquals(request, + "DELETE http://localhost/api/admin/enterprises/1/appslib/templateDefinitionLists/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testGetTemplateDefinitionList() throws SecurityException, NoSuchMethodException, IOException { + Method method = EnterpriseAsyncApi.class.getMethod("getTemplateDefinitionList", EnterpriseDto.class, + Integer.class); + GeneratedHttpRequest request = processor.createRequest(method, EnterpriseResources.enterprisePut(), 1); + + assertRequestLineEquals(request, + "GET http://localhost/api/admin/enterprises/1/appslib/templateDefinitionLists/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + TemplateDefinitionListDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); + + checkFilters(request); + } + + public void testListTemplateListStatus() throws SecurityException, NoSuchMethodException, IOException { + Method method = EnterpriseAsyncApi.class.getMethod("listTemplateListStatus", TemplateDefinitionListDto.class, + DatacenterDto.class); + GeneratedHttpRequest request = processor.createRequest(method, EnterpriseResources.templateListPut(), + InfrastructureResources.datacenterPut()); + + assertRequestLineEquals( + request, + "GET http://localhost/api/admin/enterprises/1/appslib/templateDefinitionLists/1/actions/repositoryStatus?datacenterId=1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + TemplatesStateDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + @Override + protected TypeLiteral> createTypeLiteral() { + return new TypeLiteral>() { + }; + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/features/EventAsyncApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/features/EventAsyncApiTest.java new file mode 100644 index 0000000000..5934affe84 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/features/EventAsyncApiTest.java @@ -0,0 +1,61 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.features; + +import java.io.IOException; +import java.lang.reflect.Method; + +import org.jclouds.http.functions.ParseXMLWithJAXB; +import org.jclouds.rest.internal.GeneratedHttpRequest; +import org.jclouds.rest.internal.RestAnnotationProcessor; +import org.testng.annotations.Test; + +import com.abiquo.server.core.event.EventsDto; +import com.google.inject.TypeLiteral; + +/** + * Tests annotation parsing of {@code EventAsyncApi} + * + * @author Ignasi Barrera + * @author Vivien Mahé + */ +@Test(groups = "unit", testName = "EventAsyncApiTest") +public class EventAsyncApiTest extends BaseAbiquoAsyncApiTest { + public void testListEvents() throws SecurityException, NoSuchMethodException, IOException { + Method method = EventAsyncApi.class.getMethod("listEvents"); + GeneratedHttpRequest request = processor.createRequest(method); + + assertRequestLineEquals(request, "GET http://localhost/api/events HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + EventsDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + @Override + protected TypeLiteral> createTypeLiteral() { + return new TypeLiteral>() { + }; + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/features/FeatureCoverageTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/features/FeatureCoverageTest.java new file mode 100644 index 0000000000..a7193ca9d2 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/features/FeatureCoverageTest.java @@ -0,0 +1,103 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.features; + +import static org.testng.Assert.assertTrue; +import static org.testng.Assert.fail; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; + +import org.jclouds.abiquo.config.AbiquoRestClientModule; +import org.jclouds.abiquo.rest.internal.AbiquoHttpAsyncClient; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import com.google.common.base.Function; +import com.google.common.base.Joiner; +import com.google.common.base.Predicate; +import com.google.common.collect.Iterables; + +/** + * Tests that all features have a unit test. + * + * @author Ignasi Barrera + */ +@Test(groups = "unit", testName = "FeatureCoverageTest") +public class FeatureCoverageTest { + /** A collection with all async api classes. */ + private Collection> featureClasses; + + @BeforeMethod + public void setup() { + featureClasses = new ArrayList>(); + featureClasses.addAll(AbiquoRestClientModule.DELEGATE_MAP.values()); + featureClasses.add(AbiquoHttpAsyncClient.class); + } + + public void testAllFeaturesHaveTest() throws ClassNotFoundException { + List missingTests = new ArrayList(); + + for (Class featureClass : featureClasses) { + try { + Class testClass = loadTestClass(featureClass); + Iterable testMethodNames = methodNames(testClass); + + for (Method method : featureClass.getMethods()) { + if (!hasTest(testMethodNames, method)) { + missingTests.add(method.getDeclaringClass().getSimpleName() + "." + method.getName()); + } + } + } catch (ClassNotFoundException ex) { + fail("Missing tests for class: " + featureClass.getName()); + } + } + + assertTrue(missingTests.isEmpty(), "Missing tests: " + Joiner.on(", ").join(missingTests)); + } + + private Class loadTestClass(final Class featureClass) throws ClassNotFoundException { + String testClassName = featureClass.getName() + "Test"; + return Thread.currentThread().getContextClassLoader().loadClass(testClassName); + } + + private static Iterable methodNames(final Class clazz) { + return Iterables.transform(Arrays.asList(clazz.getMethods()), new Function() { + @Override + public String apply(final Method input) { + return input.getName(); + } + }); + } + + private static boolean hasTest(final Iterable testMethodNames, final Method method) { + String testMethod = Iterables.find(testMethodNames, new Predicate() { + @Override + public boolean apply(final String input) { + return input.toLowerCase().contains(method.getName().toLowerCase()); + } + }, null); + + return testMethod != null; + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/features/InfrastructureAsyncApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/features/InfrastructureAsyncApiTest.java new file mode 100644 index 0000000000..de782c849a --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/features/InfrastructureAsyncApiTest.java @@ -0,0 +1,1731 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.features; + +import static org.jclouds.abiquo.domain.DomainUtils.withHeader; + +import java.io.IOException; +import java.lang.reflect.Method; + +import javax.ws.rs.core.MediaType; + +import org.jclouds.abiquo.domain.EnterpriseResources; +import org.jclouds.abiquo.domain.InfrastructureResources; +import org.jclouds.abiquo.domain.NetworkResources; +import org.jclouds.abiquo.domain.infrastructure.options.DatacenterOptions; +import org.jclouds.abiquo.domain.infrastructure.options.IpmiOptions; +import org.jclouds.abiquo.domain.infrastructure.options.MachineOptions; +import org.jclouds.abiquo.domain.infrastructure.options.StoragePoolOptions; +import org.jclouds.abiquo.domain.network.options.IpOptions; +import org.jclouds.abiquo.domain.network.options.NetworkOptions; +import org.jclouds.abiquo.domain.options.search.FilterOptions; +import org.jclouds.abiquo.functions.ReturnAbiquoExceptionOnNotFoundOr4xx; +import org.jclouds.abiquo.functions.ReturnFalseIfNotAvailable; +import org.jclouds.http.functions.ParseXMLWithJAXB; +import org.jclouds.http.functions.ReleasePayloadAndReturn; +import org.jclouds.http.functions.ReturnStringIf2xx; +import org.jclouds.http.functions.ReturnTrueIf2xx; +import org.jclouds.rest.functions.MapHttp4xxCodesToExceptions; +import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; +import org.jclouds.rest.internal.GeneratedHttpRequest; +import org.jclouds.rest.internal.RestAnnotationProcessor; +import org.testng.annotations.Test; + +import com.abiquo.model.enumerator.HypervisorType; +import com.abiquo.model.enumerator.NetworkType; +import com.abiquo.model.enumerator.RemoteServiceType; +import com.abiquo.server.core.cloud.HypervisorTypesDto; +import com.abiquo.server.core.cloud.VirtualMachineWithNodeExtendedDto; +import com.abiquo.server.core.cloud.VirtualMachinesWithNodeExtendedDto; +import com.abiquo.server.core.enterprise.DatacentersLimitsDto; +import com.abiquo.server.core.enterprise.EnterpriseDto; +import com.abiquo.server.core.infrastructure.BladeLocatorLedDto; +import com.abiquo.server.core.infrastructure.DatacenterDto; +import com.abiquo.server.core.infrastructure.DatacentersDto; +import com.abiquo.server.core.infrastructure.FsmsDto; +import com.abiquo.server.core.infrastructure.LogicServerDto; +import com.abiquo.server.core.infrastructure.LogicServersDto; +import com.abiquo.server.core.infrastructure.MachineDto; +import com.abiquo.server.core.infrastructure.MachineIpmiStateDto; +import com.abiquo.server.core.infrastructure.MachineStateDto; +import com.abiquo.server.core.infrastructure.MachinesDto; +import com.abiquo.server.core.infrastructure.OrganizationDto; +import com.abiquo.server.core.infrastructure.OrganizationsDto; +import com.abiquo.server.core.infrastructure.RackDto; +import com.abiquo.server.core.infrastructure.RacksDto; +import com.abiquo.server.core.infrastructure.RemoteServiceDto; +import com.abiquo.server.core.infrastructure.RemoteServicesDto; +import com.abiquo.server.core.infrastructure.UcsRackDto; +import com.abiquo.server.core.infrastructure.UcsRacksDto; +import com.abiquo.server.core.infrastructure.network.ExternalIpDto; +import com.abiquo.server.core.infrastructure.network.ExternalIpsDto; +import com.abiquo.server.core.infrastructure.network.PublicIpDto; +import com.abiquo.server.core.infrastructure.network.PublicIpsDto; +import com.abiquo.server.core.infrastructure.network.UnmanagedIpDto; +import com.abiquo.server.core.infrastructure.network.UnmanagedIpsDto; +import com.abiquo.server.core.infrastructure.network.VLANNetworkDto; +import com.abiquo.server.core.infrastructure.network.VLANNetworksDto; +import com.abiquo.server.core.infrastructure.network.VlanTagAvailabilityDto; +import com.abiquo.server.core.infrastructure.storage.StorageDeviceDto; +import com.abiquo.server.core.infrastructure.storage.StorageDevicesDto; +import com.abiquo.server.core.infrastructure.storage.StorageDevicesMetadataDto; +import com.abiquo.server.core.infrastructure.storage.StoragePoolDto; +import com.abiquo.server.core.infrastructure.storage.StoragePoolsDto; +import com.abiquo.server.core.infrastructure.storage.TierDto; +import com.abiquo.server.core.infrastructure.storage.TiersDto; +import com.google.inject.TypeLiteral; + +/** + * Tests annotation parsing of {@code InfrastructureAsyncApi} + * + * @author Ignasi Barrera + */ +@Test(groups = "unit", testName = "InfrastructureAsyncApiTest") +public class InfrastructureAsyncApiTest extends BaseAbiquoAsyncApiTest { + /*********************** Datacenter ***********************/ + + public void testListDatacenters() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("listDatacenters"); + GeneratedHttpRequest request = processor.createRequest(method); + + assertRequestLineEquals(request, "GET http://localhost/api/admin/datacenters HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + DatacentersDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testCreateDatacenter() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("createDatacenter", DatacenterDto.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.datacenterPost()); + + assertRequestLineEquals(request, "POST http://localhost/api/admin/datacenters HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + DatacenterDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(InfrastructureResources.datacenterPostPayload()), DatacenterDto.class, + DatacenterDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testGetDatacenter() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("getDatacenter", Integer.class); + GeneratedHttpRequest request = processor.createRequest(method, 1); + + assertRequestLineEquals(request, "GET http://localhost/api/admin/datacenters/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + DatacenterDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); + + checkFilters(request); + } + + public void testUpdateDatacenter() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("updateDatacenter", DatacenterDto.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.datacenterPut()); + + assertRequestLineEquals(request, "PUT http://localhost/api/admin/datacenters/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + DatacenterDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(InfrastructureResources.datacenterPutPayload()), DatacenterDto.class, + DatacenterDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testDeleteDatacenter() throws SecurityException, NoSuchMethodException { + Method method = InfrastructureAsyncApi.class.getMethod("deleteDatacenter", DatacenterDto.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.datacenterPut()); + + assertRequestLineEquals(request, "DELETE http://localhost/api/admin/datacenters/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testListLimitsDatacenter() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("listLimits", DatacenterDto.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.datacenterPut()); + + assertRequestLineEquals(request, "GET http://localhost/api/admin/datacenters/1/action/getLimits HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + DatacentersLimitsDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + /*********************** Hypervisor ***********************/ + + public void testGetHypervisorTypeFromMachine() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("getHypervisorTypeFromMachine", DatacenterDto.class, + DatacenterOptions.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.datacenterPut(), + DatacenterOptions.builder().ip("10.60.1.120").build()); + + assertRequestLineEquals(request, + "GET http://localhost/api/admin/datacenters/1/action/hypervisor?ip=10.60.1.120 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + MediaType.TEXT_PLAIN + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ReturnStringIf2xx.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testGetHypervisorTypesFromDatacenter() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("getHypervisorTypes", DatacenterDto.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.datacenterPut()); + + assertRequestLineEquals(request, "GET http://localhost/api/admin/datacenters/1/hypervisors HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + HypervisorTypesDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + /*********************** Managed Rack ***********************/ + + public void testListRacks() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("listRacks", DatacenterDto.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.datacenterPut()); + + assertRequestLineEquals(request, "GET http://localhost/api/admin/datacenters/1/racks HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + RacksDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testCreateRack() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("createRack", DatacenterDto.class, RackDto.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.datacenterPut(), + InfrastructureResources.rackPost()); + + assertRequestLineEquals(request, "POST http://localhost/api/admin/datacenters/1/racks HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + RackDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(InfrastructureResources.rackPostPayload()), RackDto.class, + RackDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testGetRack() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("getRack", DatacenterDto.class, Integer.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.datacenterPut(), 1); + + assertRequestLineEquals(request, "GET http://localhost/api/admin/datacenters/1/racks/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + RackDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); + + checkFilters(request); + } + + public void testUpdateRack() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("updateRack", RackDto.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.rackPut()); + + assertRequestLineEquals(request, "PUT http://localhost/api/admin/datacenters/1/racks/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + RackDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(InfrastructureResources.rackPutPayload()), RackDto.class, + RackDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testDeleteRack() throws SecurityException, NoSuchMethodException { + Method method = InfrastructureAsyncApi.class.getMethod("deleteRack", RackDto.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.rackPut()); + + assertRequestLineEquals(request, "DELETE http://localhost/api/admin/datacenters/1/racks/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + /*********************** Managed Rack ***********************/ + + public void testListManagedRacks() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("listManagedRacks", DatacenterDto.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.datacenterPut()); + + assertRequestLineEquals(request, "GET http://localhost/api/admin/datacenters/1/racks HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + UcsRacksDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testCreateManagedRack() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class + .getMethod("createManagedRack", DatacenterDto.class, UcsRackDto.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.datacenterPut(), + InfrastructureResources.managedRackPost()); + + assertRequestLineEquals(request, "POST http://localhost/api/admin/datacenters/1/racks HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + UcsRackDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(InfrastructureResources.managedRackPostPayload()), UcsRackDto.class, + UcsRackDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testGetManagedRack() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("getManagedRack", DatacenterDto.class, Integer.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.datacenterPut(), 1); + + assertRequestLineEquals(request, "GET http://localhost/api/admin/datacenters/1/racks/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + UcsRackDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); + + checkFilters(request); + } + + public void testUpdateManagedRack() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("updateManagedRack", UcsRackDto.class); + + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.managedRackPut()); + + assertRequestLineEquals(request, "PUT http://localhost/api/admin/datacenters/1/racks/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + UcsRackDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(InfrastructureResources.managedRackPutPayload()), UcsRackDto.class, + UcsRackDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testListServiceProfiles() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("listServiceProfiles", UcsRackDto.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.managedRackPut()); + + assertRequestLineEquals(request, "GET http://localhost/api/admin/datacenters/1/racks/1/logicservers HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + LogicServersDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testListServiceProfilesWithOptions() throws SecurityException, NoSuchMethodException, IOException { + FilterOptions options = FilterOptions.builder().startWith(1).limit(2).build(); + + Method method = InfrastructureAsyncApi.class.getMethod("listServiceProfiles", UcsRackDto.class, + FilterOptions.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.managedRackPut(), options); + + assertRequestLineEquals(request, + "GET http://localhost/api/admin/datacenters/1/racks/1/logicservers?startwith=1&limit=2 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + LogicServersDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testListOrganizations() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("listOrganizations", UcsRackDto.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.managedRackPut()); + + assertRequestLineEquals(request, "GET http://localhost/api/admin/datacenters/1/racks/1/organizations HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + OrganizationsDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testListOrganizationsWithOptions() throws SecurityException, NoSuchMethodException, IOException { + FilterOptions options = FilterOptions.builder().has("org").build(); + + Method method = InfrastructureAsyncApi.class + .getMethod("listOrganizations", UcsRackDto.class, FilterOptions.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.managedRackPut(), options); + + assertRequestLineEquals(request, + "GET http://localhost/api/admin/datacenters/1/racks/1/organizations?has=org HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + OrganizationsDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testListServiceProfileTemplates() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("listServiceProfileTemplates", UcsRackDto.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.managedRackPut()); + + assertRequestLineEquals(request, "GET http://localhost/api/admin/datacenters/1/racks/1/lstemplates HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + LogicServersDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testListServiceProfileTemplatesWithOptions() throws SecurityException, NoSuchMethodException, + IOException { + FilterOptions options = FilterOptions.builder().ascendant(true).build(); + + Method method = InfrastructureAsyncApi.class.getMethod("listServiceProfileTemplates", UcsRackDto.class, + FilterOptions.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.managedRackPut(), options); + + assertRequestLineEquals(request, + "GET http://localhost/api/admin/datacenters/1/racks/1/lstemplates?asc=true HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + LogicServersDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testAssociateLogicServer() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("associateLogicServer", UcsRackDto.class, + LogicServerDto.class, OrganizationDto.class, String.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.managedRackPut(), + InfrastructureResources.logicServerPut(), InfrastructureResources.organizationPut(), "blade"); + + assertRequestLineEquals( + request, + "POST http://localhost/api/admin/datacenters/1/racks/1/logicservers/associate?bladeDn=blade&org=org-root%2Forg-Finance&lsName=server HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testAssociateTemplate() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("associateTemplate", UcsRackDto.class, + LogicServerDto.class, OrganizationDto.class, String.class, String.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.managedRackPut(), + InfrastructureResources.logicServerPut(), InfrastructureResources.organizationPut(), "newname", "blade"); + + assertRequestLineEquals( + request, + "POST http://localhost/api/admin/datacenters/1/racks/1/logicservers/associatetemplate?newName=newname&bladeDn=blade&org=org-root%2Forg-Finance&lsName=server HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testCloneAndAssociateLogicServer() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("cloneAndAssociateLogicServer", UcsRackDto.class, + LogicServerDto.class, OrganizationDto.class, String.class, String.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.managedRackPut(), + InfrastructureResources.logicServerPut(), InfrastructureResources.organizationPut(), "newname", "blade"); + + assertRequestLineEquals( + request, + "POST http://localhost/api/admin/datacenters/1/racks/1/logicservers/assocclone?newName=newname&bladeDn=blade&org=org-root%2Forg-Finance&lsName=server HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testDissociateLogicServer() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("dissociateLogicServer", UcsRackDto.class, + LogicServerDto.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.managedRackPut(), + InfrastructureResources.logicServerPut(), InfrastructureResources.organizationPut()); + + assertRequestLineEquals(request, + "POST http://localhost/api/admin/datacenters/1/racks/1/logicservers/dissociate?lsName=server HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testCloneLogicServer() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("cloneLogicServer", UcsRackDto.class, + LogicServerDto.class, OrganizationDto.class, String.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.managedRackPut(), + InfrastructureResources.logicServerPut(), InfrastructureResources.organizationPut(), "name"); + + assertRequestLineEquals( + request, + "POST http://localhost/api/admin/datacenters/1/racks/1/logicservers/clone?newName=name&org=org-root%2Forg-Finance&lsName=server HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testDeleteLogicServer() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("deleteLogicServer", UcsRackDto.class, + LogicServerDto.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.managedRackPut(), + InfrastructureResources.logicServerPut()); + + assertRequestLineEquals(request, + "POST http://localhost/api/admin/datacenters/1/racks/1/logicservers/delete?lsName=server HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testListFsms() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("listFsms", UcsRackDto.class, String.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.managedRackPut(), "dn"); + + assertRequestLineEquals(request, "GET http://localhost/api/admin/datacenters/1/racks/1/fsm?dn=dn HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + FsmsDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + /*********************** Remote Service **********************/ + + public void testListRemoteServices() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("listRemoteServices", DatacenterDto.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.datacenterPut()); + + assertRequestLineEquals(request, "GET http://localhost/api/admin/datacenters/1/remoteservices HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + RemoteServicesDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testCreateRemoteService() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("createRemoteService", DatacenterDto.class, + RemoteServiceDto.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.datacenterPut(), + InfrastructureResources.remoteServicePost()); + + assertRequestLineEquals(request, "POST http://localhost/api/admin/datacenters/1/remoteservices HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + RemoteServiceDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(InfrastructureResources.remoteServicePostPayload()), + RemoteServiceDto.class, RemoteServiceDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testGetRemoteService() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("getRemoteService", DatacenterDto.class, + RemoteServiceType.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.datacenterPut(), + RemoteServiceType.STORAGE_SYSTEM_MONITOR); + + assertRequestLineEquals(request, + "GET http://localhost/api/admin/datacenters/1/remoteservices/storagesystemmonitor HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + RemoteServiceDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); + + checkFilters(request); + } + + public void testUpdateRemoteService() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("updateRemoteService", RemoteServiceDto.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.remoteServicePut()); + + assertRequestLineEquals(request, + "PUT http://localhost/api/admin/datacenters/1/remoteservices/nodecollector HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + RemoteServiceDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(InfrastructureResources.remoteServicePutPayload()), + RemoteServiceDto.class, RemoteServiceDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testDeleteRemoteService() throws SecurityException, NoSuchMethodException { + Method method = InfrastructureAsyncApi.class.getMethod("deleteRemoteService", RemoteServiceDto.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.remoteServicePut()); + + assertRequestLineEquals(request, + "DELETE http://localhost/api/admin/datacenters/1/remoteservices/nodecollector HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testIsAvailableRemoteService() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("isAvailable", RemoteServiceDto.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.remoteServicePut()); + + String checkUri = InfrastructureResources.remoteServicePut().searchLink("check").getHref(); + assertRequestLineEquals(request, String.format("GET %s HTTP/1.1", checkUri)); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ReturnTrueIf2xx.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnFalseIfNotAvailable.class); + + checkFilters(request); + } + + /*********************** Machine ***********************/ + + public void testDiscoverSingleMachineWithoutOptions() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("discoverSingleMachine", DatacenterDto.class, + String.class, HypervisorType.class, String.class, String.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.datacenterPut(), + "10.60.1.222", HypervisorType.XENSERVER, "user", "pass"); + + String baseUrl = "http://localhost/api/admin/datacenters/1/action/discoversingle"; + String query = "hypervisor=XENSERVER&ip=10.60.1.222&user=user&password=pass"; + String expectedRequest = String.format("GET %s?%s HTTP/1.1", baseUrl, query); + + assertRequestLineEquals(request, expectedRequest); + assertNonPayloadHeadersEqual(request, "Accept: " + MachineDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnAbiquoExceptionOnNotFoundOr4xx.class); + + checkFilters(request); + } + + public void testDiscoverSingleMachineAllParams() throws SecurityException, NoSuchMethodException { + Method method = InfrastructureAsyncApi.class.getMethod("discoverSingleMachine", DatacenterDto.class, + String.class, HypervisorType.class, String.class, String.class, MachineOptions.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.datacenterPut(), + "80.80.80.80", HypervisorType.KVM, "user", "pass", MachineOptions.builder().port(8889).build()); + + String baseUrl = "http://localhost/api/admin/datacenters/1/action/discoversingle"; + String query = "hypervisor=KVM&ip=80.80.80.80&user=user&password=pass&port=8889"; + String expectedRequest = String.format("GET %s?%s HTTP/1.1", baseUrl, query); + + assertRequestLineEquals(request, expectedRequest); + assertNonPayloadHeadersEqual(request, "Accept: " + MachineDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnAbiquoExceptionOnNotFoundOr4xx.class); + + checkFilters(request); + } + + public void testDiscoverSingleMachineDefaultValues() throws SecurityException, NoSuchMethodException { + Method method = InfrastructureAsyncApi.class.getMethod("discoverSingleMachine", DatacenterDto.class, + String.class, HypervisorType.class, String.class, String.class, MachineOptions.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.datacenterPut(), + "80.80.80.80", HypervisorType.KVM, "user", "pass", MachineOptions.builder().build()); + + String baseUrl = "http://localhost/api/admin/datacenters/1/action/discoversingle"; + String query = "hypervisor=KVM&ip=80.80.80.80&user=user&password=pass"; + String expectedRequest = String.format("GET %s?%s HTTP/1.1", baseUrl, query); + + assertRequestLineEquals(request, expectedRequest); + assertNonPayloadHeadersEqual(request, "Accept: " + MachineDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnAbiquoExceptionOnNotFoundOr4xx.class); + + checkFilters(request); + } + + public void testDiscoverMultipleMachinesWithoutOptions() throws SecurityException, NoSuchMethodException, + IOException { + Method method = InfrastructureAsyncApi.class.getMethod("discoverMultipleMachines", DatacenterDto.class, + String.class, String.class, HypervisorType.class, String.class, String.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.datacenterPut(), + "10.60.1.222", "10.60.1.250", HypervisorType.XENSERVER, "user", "pass"); + + String baseUrl = "http://localhost/api/admin/datacenters/1/action/discovermultiple"; + String query = "password=pass&ipTo=10.60.1.250&ipFrom=10.60.1.222&hypervisor=XENSERVER&user=user"; + String expectedRequest = String.format("GET %s?%s HTTP/1.1", baseUrl, query); + + assertRequestLineEquals(request, expectedRequest); + assertNonPayloadHeadersEqual(request, "Accept: " + MachinesDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnAbiquoExceptionOnNotFoundOr4xx.class); + + checkFilters(request); + } + + public void testDiscoverMultipleMachinesAllParams() throws SecurityException, NoSuchMethodException { + Method method = InfrastructureAsyncApi.class.getMethod("discoverMultipleMachines", DatacenterDto.class, + String.class, String.class, HypervisorType.class, String.class, String.class, MachineOptions.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.datacenterPut(), + "80.80.80.80", "80.80.80.86", HypervisorType.KVM, "user", "pass", MachineOptions.builder().port(8889) + .build()); + + String baseUrl = "http://localhost/api/admin/datacenters/1/action/discovermultiple"; + String query = "password=pass&ipTo=80.80.80.86&ipFrom=80.80.80.80&hypervisor=KVM&user=user&port=8889"; + String expectedRequest = String.format("GET %s?%s HTTP/1.1", baseUrl, query); + + assertRequestLineEquals(request, expectedRequest); + assertNonPayloadHeadersEqual(request, "Accept: " + MachinesDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnAbiquoExceptionOnNotFoundOr4xx.class); + + checkFilters(request); + } + + public void testCheckMachineStateWithoutOptions() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("checkMachineState", DatacenterDto.class, String.class, + HypervisorType.class, String.class, String.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.datacenterPut(), + "10.60.1.222", HypervisorType.XENSERVER, "user", "pass"); + + String baseUrl = "http://localhost/api/admin/datacenters/1/action/checkmachinestate"; + String query = "hypervisor=XENSERVER&ip=10.60.1.222&user=user&password=pass"; + String expectedRequest = String.format("GET %s?%s HTTP/1.1", baseUrl, query); + + assertRequestLineEquals(request, expectedRequest); + assertNonPayloadHeadersEqual(request, "Accept: " + MachineStateDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnAbiquoExceptionOnNotFoundOr4xx.class); + + checkFilters(request); + } + + public void testCheckMachineStateAllParams() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("checkMachineState", DatacenterDto.class, String.class, + HypervisorType.class, String.class, String.class, MachineOptions.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.datacenterPut(), + "10.60.1.222", HypervisorType.XENSERVER, "user", "pass", MachineOptions.builder().port(8889).build()); + + String baseUrl = "http://localhost/api/admin/datacenters/1/action/checkmachinestate"; + String query = "hypervisor=XENSERVER&ip=10.60.1.222&user=user&password=pass&port=8889"; + String expectedRequest = String.format("GET %s?%s HTTP/1.1", baseUrl, query); + + assertRequestLineEquals(request, expectedRequest); + assertNonPayloadHeadersEqual(request, "Accept: " + MachineStateDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnAbiquoExceptionOnNotFoundOr4xx.class); + + checkFilters(request); + } + + public void testCheckMachineIpmiStateWithoutOptions() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("checkMachineIpmiState", DatacenterDto.class, + String.class, String.class, String.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.datacenterPut(), + "10.60.1.222", "user", "pass"); + + String baseUrl = "http://localhost/api/admin/datacenters/1/action/checkmachineipmistate"; + String query = "user=user&ip=10.60.1.222&password=pass"; + String expectedRequest = String.format("GET %s?%s HTTP/1.1", baseUrl, query); + + assertRequestLineEquals(request, expectedRequest); + assertNonPayloadHeadersEqual(request, "Accept: " + MachineIpmiStateDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnAbiquoExceptionOnNotFoundOr4xx.class); + + checkFilters(request); + } + + public void testCheckMachineIpmiStateWithALLOptions() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("checkMachineIpmiState", DatacenterDto.class, + String.class, String.class, String.class, IpmiOptions.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.datacenterPut(), + "10.60.1.222", "user", "pass", IpmiOptions.builder().port(8889).build()); + + String baseUrl = "http://localhost/api/admin/datacenters/1/action/checkmachineipmistate"; + String query = "user=user&ip=10.60.1.222&password=pass&port=8889"; + String expectedRequest = String.format("GET %s?%s HTTP/1.1", baseUrl, query); + + assertRequestLineEquals(request, expectedRequest); + assertNonPayloadHeadersEqual(request, "Accept: " + MachineIpmiStateDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnAbiquoExceptionOnNotFoundOr4xx.class); + + checkFilters(request); + } + + public void testListMachines() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("listMachines", RackDto.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.rackPut()); + + assertRequestLineEquals(request, "GET http://localhost/api/admin/datacenters/1/racks/1/machines HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + MachinesDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testGetMachine() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("getMachine", RackDto.class, Integer.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.rackPut(), 1); + + assertRequestLineEquals(request, "GET http://localhost/api/admin/datacenters/1/racks/1/machines/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + MachineDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); + + checkFilters(request); + } + + public void testCheckMachineState() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("checkMachineState", MachineDto.class, boolean.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.machinePut(), true); + + assertRequestLineEquals(request, + "GET http://localhost/api/admin/datacenters/1/racks/1/machines/1/action/checkstate?sync=true HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + MachineStateDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testCheckMachineIpmiState() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("checkMachineIpmiState", MachineDto.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.machinePut()); + + assertRequestLineEquals(request, + "GET http://localhost/api/admin/datacenters/1/racks/1/machines/1/action/checkipmistate HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + MachineIpmiStateDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testCreateMachine() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("createMachine", RackDto.class, MachineDto.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.rackPut(), + InfrastructureResources.machinePost()); + + assertRequestLineEquals(request, "POST http://localhost/api/admin/datacenters/1/racks/1/machines HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + MachineDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(InfrastructureResources.machinePostPayload()), MachineDto.class, + MachineDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testUpdateMachine() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("updateMachine", MachineDto.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.machinePut()); + + assertRequestLineEquals(request, "PUT http://localhost/api/admin/datacenters/1/racks/1/machines/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + MachineDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(InfrastructureResources.machinePutPayload()), MachineDto.class, + MachineDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testDeleteMachine() throws SecurityException, NoSuchMethodException { + Method method = InfrastructureAsyncApi.class.getMethod("deleteMachine", MachineDto.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.machinePut()); + + assertRequestLineEquals(request, "DELETE http://localhost/api/admin/datacenters/1/racks/1/machines/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testReserveMachine() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("reserveMachine", EnterpriseDto.class, MachineDto.class); + GeneratedHttpRequest request = processor.createRequest(method, EnterpriseResources.enterprisePut(), + InfrastructureResources.machinePut()); + + assertRequestLineEquals(request, "POST http://localhost/api/admin/enterprises/1/reservedmachines HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + MachineDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(InfrastructureResources.machinePutPayload()), MachineDto.class, + MachineDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testCancelReservation() throws SecurityException, NoSuchMethodException { + Method method = InfrastructureAsyncApi.class + .getMethod("cancelReservation", EnterpriseDto.class, MachineDto.class); + GeneratedHttpRequest request = processor.createRequest(method, EnterpriseResources.enterprisePut(), + InfrastructureResources.machinePut()); + + assertRequestLineEquals(request, "DELETE http://localhost/api/admin/enterprises/1/reservedmachines/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testListVirtualMachinesByMachine() throws SecurityException, NoSuchMethodException, IOException { + MachineOptions options = MachineOptions.builder().sync(true).build(); + + Method method = InfrastructureAsyncApi.class.getMethod("listVirtualMachinesByMachine", MachineDto.class, + MachineOptions.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.machinePut(), options); + + assertRequestLineEquals(request, + "GET http://localhost/api/admin/datacenters/1/racks/1/machines/1/virtualmachines?sync=true HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + VirtualMachinesWithNodeExtendedDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testGetVirtualMachineByMachine() throws SecurityException, NoSuchMethodException, IOException { + + Method method = InfrastructureAsyncApi.class.getMethod("getVirtualMachine", MachineDto.class, Integer.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.machinePut(), 1); + + assertRequestLineEquals(request, + "GET http://localhost/api/admin/datacenters/1/racks/1/machines/1/virtualmachines/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + VirtualMachineWithNodeExtendedDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); + + checkFilters(request); + } + + /*********************** Blade ***********************/ + + public void testPowerOff() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("powerOff", MachineDto.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.machinePut()); + + assertRequestLineEquals(request, + "PUT http://localhost/api/admin/datacenters/1/racks/1/machines/1/action/poweroff HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testPowerOn() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("powerOn", MachineDto.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.machinePut()); + + assertRequestLineEquals(request, + "PUT http://localhost/api/admin/datacenters/1/racks/1/machines/1/action/poweron HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testGetLogicServer() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("getLogicServer", MachineDto.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.machinePut()); + + assertRequestLineEquals(request, + "GET http://localhost/api/admin/datacenters/1/racks/1/machines/1/logicserver HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + LogicServerDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testLedOn() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("ledOn", MachineDto.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.machinePut()); + + assertRequestLineEquals(request, + "POST http://localhost/api/admin/datacenters/1/racks/1/machines/1/action/ledon HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testLedOff() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("ledOff", MachineDto.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.machinePut()); + + assertRequestLineEquals(request, + "POST http://localhost/api/admin/datacenters/1/racks/1/machines/1/action/ledoff HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testGetLocatorLed() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("getLocatorLed", MachineDto.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.machinePut()); + + assertRequestLineEquals(request, "GET http://localhost/api/admin/datacenters/1/racks/1/machines/1/led HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + BladeLocatorLedDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + /*********************** Storage Device ***********************/ + + public void testListStorageDevices() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("listStorageDevices", DatacenterDto.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.datacenterPut()); + + assertRequestLineEquals(request, "GET http://localhost/api/admin/datacenters/1/storage/devices HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + StorageDevicesDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testListSupportedStorageDevices() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("listSupportedStorageDevices", DatacenterDto.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.datacenterPut()); + + assertRequestLineEquals(request, + "GET http://localhost/api/admin/datacenters/1/storage/devices/action/supported HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + StorageDevicesMetadataDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testCreateStorageDevice() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("createStorageDevice", DatacenterDto.class, + StorageDeviceDto.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.datacenterPut(), + InfrastructureResources.storageDevicePost()); + + assertRequestLineEquals(request, "POST http://localhost/api/admin/datacenters/1/storage/devices HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + StorageDeviceDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(InfrastructureResources.storageDevicePostPayload()), + StorageDeviceDto.class, StorageDeviceDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testDeleteStorageDevice() throws SecurityException, NoSuchMethodException { + Method method = InfrastructureAsyncApi.class.getMethod("deleteStorageDevice", StorageDeviceDto.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.storageDevicePut()); + + assertRequestLineEquals(request, "DELETE http://localhost/api/admin/datacenters/1/storage/devices/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testUpdateStorageDevice() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("updateStorageDevice", StorageDeviceDto.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.storageDevicePut()); + + assertRequestLineEquals(request, "PUT http://localhost/api/admin/datacenters/1/storage/devices/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + StorageDeviceDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(InfrastructureResources.storageDevicePutPayload()), + StorageDeviceDto.class, StorageDeviceDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testGetStorageDevice() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("getStorageDevice", DatacenterDto.class, Integer.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.datacenterPut(), 1); + + assertRequestLineEquals(request, "GET http://localhost/api/admin/datacenters/1/storage/devices/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + StorageDeviceDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); + + checkFilters(request); + } + + /*********************** Tier ***********************/ + + public void testListTiers() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("listTiers", DatacenterDto.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.datacenterPut()); + + assertRequestLineEquals(request, "GET http://localhost/api/admin/datacenters/1/storage/tiers HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + TiersDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testUpdateTier() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("updateTier", TierDto.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.tierPut()); + + assertRequestLineEquals(request, "PUT http://localhost/api/admin/datacenters/1/storage/tiers/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + TierDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(InfrastructureResources.tierPutPayload()), TierDto.class, + TierDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testGetTier() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("getTier", DatacenterDto.class, Integer.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.datacenterPut(), 1); + + assertRequestLineEquals(request, "GET http://localhost/api/admin/datacenters/1/storage/tiers/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + TierDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); + + checkFilters(request); + } + + /*********************** StoragePool ***********************/ + + public void testListSyncStoragePools() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("listStoragePools", StorageDeviceDto.class, + StoragePoolOptions.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.storageDevicePut(), + StoragePoolOptions.builder().sync(true).build()); + + assertRequestLineEquals(request, + "GET http://localhost/api/admin/datacenters/1/storage/devices/1/pools?sync=true HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + StoragePoolsDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testListStoragePoolsFromTier() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("listStoragePools", TierDto.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.tierPut(), + StoragePoolOptions.builder().sync(true).build()); + + assertRequestLineEquals(request, "GET http://localhost/api/admin/datacenters/1/storage/tiers/1/pools HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + StoragePoolsDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testListStoragePoolsNoParams() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("listStoragePools", StorageDeviceDto.class, + StoragePoolOptions.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.storageDevicePut(), + StoragePoolOptions.builder().build()); + + assertRequestLineEquals(request, "GET http://localhost/api/admin/datacenters/1/storage/devices/1/pools HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + StoragePoolsDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testCreateStoragePool() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("createStoragePool", StorageDeviceDto.class, + StoragePoolDto.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.storageDevicePut(), + InfrastructureResources.storagePoolPost()); + + assertRequestLineEquals(request, "POST http://localhost/api/admin/datacenters/1/storage/devices/1/pools HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + StoragePoolDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(InfrastructureResources.storagePoolPostPayload()), StoragePoolDto.class, + StoragePoolDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testUpdateStoragePool() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("updateStoragePool", StoragePoolDto.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.storagePoolPut()); + + assertRequestLineEquals(request, + "PUT http://localhost/api/admin/datacenters/1/storage/devices/1/pools/tururututu HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + StoragePoolDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(InfrastructureResources.storagePoolPutPayload()), StoragePoolDto.class, + StoragePoolDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testDeleteStoragePool() throws SecurityException, NoSuchMethodException { + Method method = InfrastructureAsyncApi.class.getMethod("deleteStoragePool", StoragePoolDto.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.storagePoolPut()); + + assertRequestLineEquals(request, + "DELETE http://localhost/api/admin/datacenters/1/storage/devices/1/pools/tururututu HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testGetStoragePool() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("getStoragePool", StorageDeviceDto.class, String.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.storageDevicePut(), + InfrastructureResources.storagePoolPut().getIdStorage()); + + assertRequestLineEquals(request, + "GET http://localhost/api/admin/datacenters/1/storage/devices/1/pools/tururututu HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + StoragePoolDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); + + checkFilters(request); + } + + public void testRefreshStoragePool() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("refreshStoragePool", StoragePoolDto.class, + StoragePoolOptions.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.storagePoolPut(), + StoragePoolOptions.builder().sync(true).build()); + + assertRequestLineEquals(request, + "GET http://localhost/api/admin/datacenters/1/storage/devices/1/pools/tururututu?sync=true HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + StoragePoolDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, MapHttp4xxCodesToExceptions.class); + + checkFilters(request); + } + + /*********************** Network ***********************/ + + public void testListNetworks() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("listNetworks", DatacenterDto.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.datacenterPut()); + + assertRequestLineEquals(request, "GET http://localhost/api/admin/datacenters/1/network HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + VLANNetworksDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testListNetworksWithOptions() throws SecurityException, NoSuchMethodException, IOException { + NetworkOptions options = NetworkOptions.builder().type(NetworkType.PUBLIC).build(); + + Method method = InfrastructureAsyncApi.class.getMethod("listNetworks", DatacenterDto.class, NetworkOptions.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.datacenterPut(), options); + + assertRequestLineEquals(request, "GET http://localhost/api/admin/datacenters/1/network?type=PUBLIC HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + VLANNetworksDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testGetNetworks() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("getNetwork", DatacenterDto.class, Integer.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.datacenterPut(), 1); + + assertRequestLineEquals(request, "GET http://localhost/api/admin/datacenters/1/network/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + VLANNetworkDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); + + checkFilters(request); + } + + public void testCreateNetwork() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class + .getMethod("createNetwork", DatacenterDto.class, VLANNetworkDto.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.datacenterPut(), + NetworkResources.vlanPost()); + + assertRequestLineEquals(request, "POST http://localhost/api/admin/datacenters/1/network HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + VLANNetworkDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(NetworkResources.vlanNetworkPostPayload()), VLANNetworkDto.class, + VLANNetworkDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testUpdateNetwork() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("updateNetwork", VLANNetworkDto.class); + GeneratedHttpRequest request = processor.createRequest(method, NetworkResources.publicNetworkPut()); + + assertRequestLineEquals(request, "PUT http://localhost/api/admin/datacenters/1/network/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + VLANNetworkDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(NetworkResources.publicNetworkPutPayload()), VLANNetworkDto.class, + VLANNetworkDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testDeleteNetwork() throws SecurityException, NoSuchMethodException { + Method method = InfrastructureAsyncApi.class.getMethod("deleteNetwork", VLANNetworkDto.class); + GeneratedHttpRequest request = processor.createRequest(method, NetworkResources.publicNetworkPut()); + + assertRequestLineEquals(request, "DELETE http://localhost/api/admin/datacenters/1/network/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testCheckTagAvailability() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class + .getMethod("checkTagAvailability", DatacenterDto.class, Integer.class); + GeneratedHttpRequest request = processor.createRequest(method, InfrastructureResources.datacenterPut(), 2); + + assertRequestLineEquals(request, + "GET http://localhost/api/admin/datacenters/1/network/action/checkavailability?tag=2 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + VlanTagAvailabilityDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, MapHttp4xxCodesToExceptions.class); + + checkFilters(request); + } + + /*********************** Network IPs ***********************/ + + public void testListPublicIps() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("listPublicIps", VLANNetworkDto.class); + GeneratedHttpRequest request = processor.createRequest(method, NetworkResources.publicNetworkPut()); + + assertRequestLineEquals(request, "GET http://localhost/api/admin/datacenters/1/network/1/ips HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + PublicIpsDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testListPublicIpsWithOptions() throws SecurityException, NoSuchMethodException, IOException { + IpOptions options = IpOptions.builder().startWith(10).build(); + Method method = InfrastructureAsyncApi.class.getMethod("listPublicIps", VLANNetworkDto.class, IpOptions.class); + GeneratedHttpRequest request = processor.createRequest(method, NetworkResources.publicNetworkPut(), options); + + assertRequestLineEquals(request, + "GET http://localhost/api/admin/datacenters/1/network/1/ips?startwith=10 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + PublicIpsDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testGetPublicIp() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("getPublicIp", VLANNetworkDto.class, Integer.class); + GeneratedHttpRequest request = processor.createRequest(method, NetworkResources.publicNetworkPut(), 1); + + assertRequestLineEquals(request, "GET http://localhost/api/admin/datacenters/1/network/1/ips/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + PublicIpDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testListExternalIps() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("listExternalIps", VLANNetworkDto.class); + GeneratedHttpRequest request = processor.createRequest(method, NetworkResources.externalNetworkPut()); + + assertRequestLineEquals(request, + "GET http://localhost/api/admin/enterprises/1/limits/1/externalnetworks/1/ips HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + ExternalIpsDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testListExternalIpsWithOptions() throws SecurityException, NoSuchMethodException, IOException { + IpOptions options = IpOptions.builder().startWith(10).build(); + Method method = InfrastructureAsyncApi.class.getMethod("listExternalIps", VLANNetworkDto.class, IpOptions.class); + GeneratedHttpRequest request = processor.createRequest(method, NetworkResources.externalNetworkPut(), options); + + assertRequestLineEquals(request, + "GET http://localhost/api/admin/enterprises/1/limits/1/externalnetworks/1/ips?startwith=10 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + ExternalIpsDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testGetExternalIp() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("getExternalIp", VLANNetworkDto.class, Integer.class); + GeneratedHttpRequest request = processor.createRequest(method, NetworkResources.externalNetworkPut(), 1); + + assertRequestLineEquals(request, + "GET http://localhost/api/admin/enterprises/1/limits/1/externalnetworks/1/ips/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + ExternalIpDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testListUnmanagedIps() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("listUnmanagedIps", VLANNetworkDto.class); + GeneratedHttpRequest request = processor.createRequest(method, NetworkResources.unmanagedNetworkPut()); + + assertRequestLineEquals(request, + "GET http://localhost/api/admin/enterprises/1/limits/1/externalnetworks/1/ips HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + UnmanagedIpsDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testListUnmanagedIpsWithOptions() throws SecurityException, NoSuchMethodException, IOException { + IpOptions options = IpOptions.builder().startWith(10).build(); + Method method = InfrastructureAsyncApi.class.getMethod("listUnmanagedIps", VLANNetworkDto.class, IpOptions.class); + GeneratedHttpRequest request = processor.createRequest(method, NetworkResources.unmanagedNetworkPut(), options); + + assertRequestLineEquals(request, + "GET http://localhost/api/admin/enterprises/1/limits/1/externalnetworks/1/ips?startwith=10 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + UnmanagedIpsDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testGetUnmanagedIp() throws SecurityException, NoSuchMethodException, IOException { + Method method = InfrastructureAsyncApi.class.getMethod("getUnmanagedIp", VLANNetworkDto.class, Integer.class); + GeneratedHttpRequest request = processor.createRequest(method, NetworkResources.externalNetworkPut(), 1); + + assertRequestLineEquals(request, + "GET http://localhost/api/admin/enterprises/1/limits/1/externalnetworks/1/ips/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + UnmanagedIpDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + @Override + protected TypeLiteral> createTypeLiteral() { + return new TypeLiteral>() { + }; + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/features/PricingAsyncApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/features/PricingAsyncApiTest.java new file mode 100644 index 0000000000..728cd4d981 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/features/PricingAsyncApiTest.java @@ -0,0 +1,430 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.features; + +import static org.jclouds.abiquo.domain.DomainUtils.withHeader; + +import java.io.IOException; +import java.lang.reflect.Method; + +import org.jclouds.abiquo.domain.PricingResources; +import org.jclouds.http.functions.ParseXMLWithJAXB; +import org.jclouds.http.functions.ReleasePayloadAndReturn; +import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; +import org.jclouds.rest.internal.GeneratedHttpRequest; +import org.jclouds.rest.internal.RestAnnotationProcessor; +import org.testng.annotations.Test; + +import com.abiquo.server.core.pricing.CostCodeCurrenciesDto; +import com.abiquo.server.core.pricing.CostCodeDto; +import com.abiquo.server.core.pricing.CostCodesDto; +import com.abiquo.server.core.pricing.CurrenciesDto; +import com.abiquo.server.core.pricing.CurrencyDto; +import com.abiquo.server.core.pricing.PricingCostCodeDto; +import com.abiquo.server.core.pricing.PricingCostCodesDto; +import com.abiquo.server.core.pricing.PricingTemplateDto; +import com.abiquo.server.core.pricing.PricingTemplatesDto; +import com.abiquo.server.core.pricing.PricingTierDto; +import com.abiquo.server.core.pricing.PricingTiersDto; +import com.google.inject.TypeLiteral; + +/** + * Tests annotation parsing of {@code PricingAsyncApi}. + * + * @author Ignasi Barrera + * @author Susana Acedo + */ +@Test(groups = "unit", singleThreaded = true, testName = "PricingAsyncApiTest") +public class PricingAsyncApiTest extends BaseAbiquoAsyncApiTest { + /*********************** Currency ***********************/ + + public void testListCurrencies() throws SecurityException, NoSuchMethodException, IOException { + Method method = PricingAsyncApi.class.getMethod("listCurrencies"); + GeneratedHttpRequest request = processor.createRequest(method); + + assertRequestLineEquals(request, "GET http://localhost/api/config/currencies HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + CurrenciesDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testGetCurrency() throws SecurityException, NoSuchMethodException, IOException { + Method method = PricingAsyncApi.class.getMethod("getCurrency", Integer.class); + GeneratedHttpRequest request = processor.createRequest(method, 1); + + assertRequestLineEquals(request, "GET http://localhost/api/config/currencies/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + CurrencyDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); + + checkFilters(request); + } + + public void testCreateCurrency() throws SecurityException, NoSuchMethodException, IOException { + Method method = PricingAsyncApi.class.getMethod("createCurrency", CurrencyDto.class); + GeneratedHttpRequest request = processor.createRequest(method, PricingResources.currencyPost()); + + assertRequestLineEquals(request, "POST http://localhost/api/config/currencies HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + CurrencyDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(PricingResources.currencyPostPayload()), CurrencyDto.class, + CurrencyDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testUpdateCurrency() throws SecurityException, NoSuchMethodException, IOException { + Method method = PricingAsyncApi.class.getMethod("updateCurrency", CurrencyDto.class); + GeneratedHttpRequest request = processor.createRequest(method, PricingResources.currencyPut()); + + assertRequestLineEquals(request, "PUT http://localhost/api/config/currencies/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + CurrencyDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(PricingResources.currencyPutPayload()), CurrencyDto.class, + CurrencyDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testDeleteCurrency() throws SecurityException, NoSuchMethodException { + Method method = PricingAsyncApi.class.getMethod("deleteCurrency", CurrencyDto.class); + GeneratedHttpRequest request = processor.createRequest(method, PricingResources.currencyPut()); + + assertRequestLineEquals(request, "DELETE http://localhost/api/config/currencies/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + /*********************** Cost Code ***********************/ + + public void testListCostCodes() throws SecurityException, NoSuchMethodException, IOException { + Method method = PricingAsyncApi.class.getMethod("listCostCodes"); + GeneratedHttpRequest request = processor.createRequest(method); + + assertRequestLineEquals(request, "GET http://localhost/api/config/costcodes HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + CostCodesDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testGetCostCode() throws SecurityException, NoSuchMethodException, IOException { + Method method = PricingAsyncApi.class.getMethod("getCostCode", Integer.class); + GeneratedHttpRequest request = processor.createRequest(method, 1); + + assertRequestLineEquals(request, "GET http://localhost/api/config/costcodes/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + CostCodeDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); + + checkFilters(request); + } + + public void testCreateCostCode() throws SecurityException, NoSuchMethodException, IOException { + Method method = PricingAsyncApi.class.getMethod("createCostCode", CostCodeDto.class); + GeneratedHttpRequest request = processor.createRequest(method, PricingResources.costcodePost()); + + assertRequestLineEquals(request, "POST http://localhost/api/config/costcodes HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + CostCodeDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(PricingResources.costcodePostPayload()), CostCodeDto.class, + CostCodeDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testUpdateCostCode() throws SecurityException, NoSuchMethodException, IOException { + Method method = PricingAsyncApi.class.getMethod("updateCostCode", CostCodeDto.class); + GeneratedHttpRequest request = processor.createRequest(method, PricingResources.costcodePut()); + + assertRequestLineEquals(request, "PUT http://localhost/api/config/costcodes/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + CostCodeDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(PricingResources.costcodePutPayload()), CostCodeDto.class, + CostCodeDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testDeleteCostCode() throws SecurityException, NoSuchMethodException { + Method method = PricingAsyncApi.class.getMethod("deleteCostCode", CostCodeDto.class); + GeneratedHttpRequest request = processor.createRequest(method, PricingResources.costcodePut()); + + assertRequestLineEquals(request, "DELETE http://localhost/api/config/costcodes/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + /*********************** Pricing Template ***********************/ + + public void testListPricingTemplates() throws SecurityException, NoSuchMethodException, IOException { + Method method = PricingAsyncApi.class.getMethod("listPricingTemplates"); + GeneratedHttpRequest request = processor.createRequest(method); + + assertRequestLineEquals(request, "GET http://localhost/api/config/pricingtemplates HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + PricingTemplatesDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testGetPricingTemplate() throws SecurityException, NoSuchMethodException, IOException { + Method method = PricingAsyncApi.class.getMethod("getPricingTemplate", Integer.class); + GeneratedHttpRequest request = processor.createRequest(method, 1); + + assertRequestLineEquals(request, "GET http://localhost/api/config/pricingtemplates/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + PricingTemplateDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); + + checkFilters(request); + } + + public void testCreatePricingTemplate() throws SecurityException, NoSuchMethodException, IOException { + Method method = PricingAsyncApi.class.getMethod("createPricingTemplate", PricingTemplateDto.class); + GeneratedHttpRequest request = processor.createRequest(method, PricingResources.pricingtemplatePost()); + + assertRequestLineEquals(request, "POST http://localhost/api/config/pricingtemplates HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + PricingTemplateDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(PricingResources.pricingtemplatePostPayload()), PricingTemplateDto.class, + PricingTemplateDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testUpdatePricingTemplate() throws SecurityException, NoSuchMethodException, IOException { + Method method = PricingAsyncApi.class.getMethod("updatePricingTemplate", PricingTemplateDto.class); + GeneratedHttpRequest request = processor.createRequest(method, PricingResources.pricingtemplatePut()); + + assertRequestLineEquals(request, "PUT http://localhost/api/config/pricingtemplates/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + PricingTemplateDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(PricingResources.pricingtemplatePutPayload()), PricingTemplateDto.class, + PricingTemplateDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testDeletePricingTemplate() throws SecurityException, NoSuchMethodException { + Method method = PricingAsyncApi.class.getMethod("deletePricingTemplate", PricingTemplateDto.class); + GeneratedHttpRequest request = processor.createRequest(method, PricingResources.pricingtemplatePut()); + + assertRequestLineEquals(request, "DELETE http://localhost/api/config/pricingtemplates/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + @Override + protected TypeLiteral> createTypeLiteral() { + return new TypeLiteral>() { + }; + } + + /*********************** Cost Code Currency ***********************/ + + public void testGetCostCodeCurrencies() throws SecurityException, NoSuchMethodException, IOException { + Method method = PricingAsyncApi.class.getMethod("getCostCodeCurrencies", Integer.class, Integer.class); + GeneratedHttpRequest request = processor.createRequest(method, 1, 1); + + assertRequestLineEquals(request, "GET http://localhost/api/config/costcodes/1/currencies?idCurrency=1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + CostCodeCurrenciesDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); + + checkFilters(request); + } + + public void testUpdateCostCodeCurrencies() throws SecurityException, NoSuchMethodException, IOException { + Method method = PricingAsyncApi.class.getMethod("updateCostCodeCurrencies", Integer.class, + CostCodeCurrenciesDto.class); + GeneratedHttpRequest request = processor.createRequest(method, 1, PricingResources.costcodecurrencyPut()); + + assertRequestLineEquals(request, "PUT http://localhost/api/config/costcodes/1/currencies HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + CostCodeCurrenciesDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(PricingResources.costcodecurrencyPutPayload()), + CostCodeCurrenciesDto.class, CostCodeCurrenciesDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + /*********************** Pricing Cost Code ***********************/ + + public void testGetPricingCostCodes() throws SecurityException, NoSuchMethodException, IOException { + Method method = PricingAsyncApi.class.getMethod("getPricingCostCodes", Integer.class); + GeneratedHttpRequest request = processor.createRequest(method, 1); + + assertRequestLineEquals(request, "GET http://localhost/api/config/pricingtemplates/1/costcodes HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + PricingCostCodesDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); + + checkFilters(request); + } + + public void testGetPricingCostCode() throws SecurityException, NoSuchMethodException, IOException { + Method method = PricingAsyncApi.class.getMethod("getPricingCostCode", Integer.class, Integer.class); + GeneratedHttpRequest request = processor.createRequest(method, 1, 1); + + assertRequestLineEquals(request, "GET http://localhost/api/config/pricingtemplates/1/costcodes/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + PricingCostCodeDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); + + checkFilters(request); + } + + public void testUpdatePricingCostCode() throws SecurityException, NoSuchMethodException, IOException { + Method method = PricingAsyncApi.class.getMethod("updatePricingCostCode", PricingCostCodeDto.class, Integer.class, + Integer.class); + GeneratedHttpRequest request = processor.createRequest(method, PricingResources.pricingCostcodePut(), 1, 1); + + assertRequestLineEquals(request, "PUT http://localhost/api/config/pricingtemplates/1/costcodes/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + PricingCostCodeDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(PricingResources.pricingCostCodePutPayload()), PricingCostCodeDto.class, + PricingCostCodeDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + /*********************** Pricing Tier ***************************/ + + public void testGetPricingTiers() throws SecurityException, NoSuchMethodException, IOException { + Method method = PricingAsyncApi.class.getMethod("getPricingTiers", Integer.class); + GeneratedHttpRequest request = processor.createRequest(method, 1); + + assertRequestLineEquals(request, "GET http://localhost/api/config/pricingtemplates/1/tiers HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + PricingTiersDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); + + checkFilters(request); + } + + public void testGetPricingTier() throws SecurityException, NoSuchMethodException, IOException { + Method method = PricingAsyncApi.class.getMethod("getPricingTier", Integer.class, Integer.class); + GeneratedHttpRequest request = processor.createRequest(method, 1, 1); + + assertRequestLineEquals(request, "GET http://localhost/api/config/pricingtemplates/1/tiers/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + PricingTierDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); + + checkFilters(request); + } + + public void testUpdatePricingTier() throws SecurityException, NoSuchMethodException, IOException { + Method method = PricingAsyncApi.class.getMethod("updatePricingTier", PricingTierDto.class, Integer.class, + Integer.class); + GeneratedHttpRequest request = processor.createRequest(method, PricingResources.pricingTierPut(), 1, 2); + + assertRequestLineEquals(request, "PUT http://localhost/api/config/pricingtemplates/1/tiers/2 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + PricingTierDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(PricingResources.pricingTierPutPayload()), PricingTierDto.class, + PricingTierDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/features/TaskAsyncApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/features/TaskAsyncApiTest.java new file mode 100644 index 0000000000..5a14254387 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/features/TaskAsyncApiTest.java @@ -0,0 +1,130 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.features; + +import java.io.IOException; +import java.lang.reflect.Method; + +import org.jclouds.abiquo.domain.CloudResources; +import org.jclouds.abiquo.domain.TemplateResources; +import org.jclouds.abiquo.functions.ReturnNullOn303; +import org.jclouds.http.functions.ParseXMLWithJAXB; +import org.jclouds.rest.internal.GeneratedHttpRequest; +import org.jclouds.rest.internal.RestAnnotationProcessor; +import org.testng.annotations.Test; + +import com.abiquo.model.rest.RESTLink; +import com.abiquo.model.transport.SingleResourceTransportDto; +import com.abiquo.server.core.task.TaskDto; +import com.abiquo.server.core.task.TasksDto; +import com.google.inject.TypeLiteral; + +/** + * Tests annotation parsing of {@code TaskAsyncApi} + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +@Test(groups = "unit", testName = "TaskAsyncApiTest") +public class TaskAsyncApiTest extends BaseAbiquoAsyncApiTest { + /*********************** Task ***********************/ + + public void testGetTaskVirtualMachine() throws SecurityException, NoSuchMethodException, IOException { + Method method = TaskAsyncApi.class.getMethod("getTask", RESTLink.class); + GeneratedHttpRequest request = processor + .createRequest( + method, + new RESTLink( + "task", + "http://localhost/api/cloud/virtualdatacenters/1/virtualappliances/1/virtualmachines/1/tasks/169f1877-5f17-4f62-9563-974001295c54")); + + assertRequestLineEquals( + request, + "GET http://localhost/api/cloud/virtualdatacenters/1/virtualappliances/1/virtualmachines/1/tasks/169f1877-5f17-4f62-9563-974001295c54 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + TaskDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnNullOn303.class); + + checkFilters(request); + } + + public void testListTasksVirtualMachine() throws SecurityException, NoSuchMethodException, IOException { + Method method = TaskAsyncApi.class.getMethod("listTasks", SingleResourceTransportDto.class); + GeneratedHttpRequest request = processor.createRequest(method, CloudResources.virtualMachinePut()); + + assertRequestLineEquals(request, + "GET http://localhost/api/cloud/virtualdatacenters/1/virtualappliances/1/virtualmachines/1/tasks HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + TasksDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testGetTaskVirtualMachineTemplate() throws SecurityException, NoSuchMethodException, IOException { + Method method = TaskAsyncApi.class.getMethod("getTask", RESTLink.class); + GeneratedHttpRequest request = processor + .createRequest( + method, + new RESTLink( + "task", + "http://localhost/api/admin/enterprises/1/datacenterrepositories/1/virtualmachinetemplates/1/tasks/169f1877-5f17-4f62-9563-974001295c54")); + + assertRequestLineEquals( + request, + "GET http://localhost/api/admin/enterprises/1/datacenterrepositories/1/virtualmachinetemplates/1/tasks/169f1877-5f17-4f62-9563-974001295c54 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + TaskDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnNullOn303.class); + + checkFilters(request); + } + + public void testListTasksVirtualMachineTemplate() throws SecurityException, NoSuchMethodException, IOException { + Method method = TaskAsyncApi.class.getMethod("listTasks", SingleResourceTransportDto.class); + GeneratedHttpRequest request = processor.createRequest(method, TemplateResources.virtualMachineTemplatePut()); + + assertRequestLineEquals(request, + "GET http://localhost/api/admin/enterprises/1/datacenterrepositories/1/virtualmachinetemplates/1/tasks HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + TasksDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + @Override + protected TypeLiteral> createTypeLiteral() { + return new TypeLiteral>() { + }; + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/features/VirtualMachineTemplateAsyncApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/features/VirtualMachineTemplateAsyncApiTest.java new file mode 100644 index 0000000000..648cefe877 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/features/VirtualMachineTemplateAsyncApiTest.java @@ -0,0 +1,254 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.features; + +import static org.jclouds.abiquo.domain.DomainUtils.withHeader; + +import java.io.IOException; +import java.lang.reflect.Method; + +import org.jclouds.abiquo.domain.TemplateResources; +import org.jclouds.abiquo.domain.cloud.options.ConversionOptions; +import org.jclouds.abiquo.domain.cloud.options.VirtualMachineTemplateOptions; +import org.jclouds.abiquo.functions.ReturnTaskReferenceOrNull; +import org.jclouds.http.functions.ParseXMLWithJAXB; +import org.jclouds.http.functions.ReleasePayloadAndReturn; +import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; +import org.jclouds.rest.internal.GeneratedHttpRequest; +import org.jclouds.rest.internal.RestAnnotationProcessor; +import org.testng.annotations.Test; + +import com.abiquo.model.enumerator.ConversionState; +import com.abiquo.model.enumerator.DiskFormatType; +import com.abiquo.model.enumerator.HypervisorType; +import com.abiquo.model.transport.AcceptedRequestDto; +import com.abiquo.server.core.appslibrary.ConversionDto; +import com.abiquo.server.core.appslibrary.ConversionsDto; +import com.abiquo.server.core.appslibrary.VirtualMachineTemplateDto; +import com.abiquo.server.core.appslibrary.VirtualMachineTemplatePersistentDto; +import com.abiquo.server.core.appslibrary.VirtualMachineTemplatesDto; +import com.google.inject.TypeLiteral; + +/** + * Tests annotation parsing of {@code VirtualMachineTemplateAsyncApi} + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +@Test(groups = "unit", testName = "VirtualMachineTemplateAsyncApiTest") +public class VirtualMachineTemplateAsyncApiTest extends BaseAbiquoAsyncApiTest { + /*********************** Virtual Machine Template ***********************/ + + public void testListVirtualMachineTemplates() throws SecurityException, NoSuchMethodException, IOException { + Method method = VirtualMachineTemplateAsyncApi.class.getMethod("listVirtualMachineTemplates", Integer.class, + Integer.class); + GeneratedHttpRequest request = processor.createRequest(method, 1, 1); + + assertRequestLineEquals(request, + "GET http://localhost/api/admin/enterprises/1/datacenterrepositories/1/virtualmachinetemplates HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + VirtualMachineTemplatesDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testListVirtualMachineTemplatesWithOptions() throws SecurityException, NoSuchMethodException, + IOException { + Method method = VirtualMachineTemplateAsyncApi.class.getMethod("listVirtualMachineTemplates", Integer.class, + Integer.class, VirtualMachineTemplateOptions.class); + GeneratedHttpRequest request = processor.createRequest(method, 1, 1, VirtualMachineTemplateOptions.builder() + .hypervisorType(HypervisorType.XENSERVER).categoryName("Firewalls").build()); + + assertRequestLineEquals(request, + "GET http://localhost/api/admin/enterprises/1/datacenterrepositories/1/virtualmachinetemplates" + + "?hypervisorTypeName=XENSERVER&categoryName=Firewalls HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + VirtualMachineTemplatesDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testGetVirtualMachineTemplate() throws SecurityException, NoSuchMethodException, IOException { + Method method = VirtualMachineTemplateAsyncApi.class.getMethod("getVirtualMachineTemplate", Integer.class, + Integer.class, Integer.class); + GeneratedHttpRequest request = processor.createRequest(method, 1, 1, 1); + + assertRequestLineEquals(request, + "GET http://localhost/api/admin/enterprises/1/datacenterrepositories/1/virtualmachinetemplates/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + VirtualMachineTemplateDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); + + checkFilters(request); + } + + public void testUpdateVirtualMachineTemplate() throws SecurityException, NoSuchMethodException, IOException { + Method method = VirtualMachineTemplateAsyncApi.class.getMethod("updateVirtualMachineTemplate", + VirtualMachineTemplateDto.class); + GeneratedHttpRequest request = processor.createRequest(method, TemplateResources.virtualMachineTemplatePut()); + + assertRequestLineEquals(request, + "PUT http://localhost/api/admin/enterprises/1/datacenterrepositories/1/virtualmachinetemplates/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + VirtualMachineTemplateDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(TemplateResources.virtualMachineTemplatePutPayload()), + VirtualMachineTemplateDto.class, VirtualMachineTemplateDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testDeleteVirtualMachineTemplate() throws SecurityException, NoSuchMethodException { + Method method = VirtualMachineTemplateAsyncApi.class.getMethod("deleteVirtualMachineTemplate", + VirtualMachineTemplateDto.class); + GeneratedHttpRequest request = processor.createRequest(method, TemplateResources.virtualMachineTemplatePut()); + + assertRequestLineEquals(request, + "DELETE http://localhost/api/admin/enterprises/1/datacenterrepositories/1/virtualmachinetemplates/1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testCreatePersistentVirtualMachineTemplate() throws SecurityException, NoSuchMethodException, + IOException { + Method method = VirtualMachineTemplateAsyncApi.class.getMethod("createPersistentVirtualMachineTemplate", + Integer.class, Integer.class, VirtualMachineTemplatePersistentDto.class); + GeneratedHttpRequest request = processor.createRequest(method, 1, 1, TemplateResources.persistentData()); + + assertRequestLineEquals(request, + "POST http://localhost/api/admin/enterprises/1/datacenterrepositories/1/virtualmachinetemplates HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + AcceptedRequestDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(TemplateResources.persistentPayload()), + VirtualMachineTemplatePersistentDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + /*********************** Conversions ***********************/ + + public void testRequestConversion() throws SecurityException, NoSuchMethodException, IOException { + Method method = VirtualMachineTemplateAsyncApi.class.getMethod("requestConversion", + VirtualMachineTemplateDto.class, DiskFormatType.class, ConversionDto.class); + + GeneratedHttpRequest request = processor.createRequest(method, TemplateResources.virtualMachineTemplatePut(), + DiskFormatType.VMDK_STREAM_OPTIMIZED, TemplateResources.conversionPut()); + + assertRequestLineEquals( + request, + "PUT http://localhost/api/admin/enterprises/1/datacenterrepositories/1/virtualmachinetemplates/1/conversions/VMDK_STREAM_OPTIMIZED HTTP/1.1"); + + assertNonPayloadHeadersEqual(request, "Accept: " + AcceptedRequestDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, withHeader(TemplateResources.conversionPutPlayload()), + ConversionDto.BASE_MEDIA_TYPE, false); + + assertResponseParserClassEquals(method, request, ReturnTaskReferenceOrNull.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testListConversions() throws SecurityException, NoSuchMethodException, IOException { + Method method = VirtualMachineTemplateAsyncApi.class + .getMethod("listConversions", VirtualMachineTemplateDto.class); + GeneratedHttpRequest request = processor.createRequest(method, TemplateResources.virtualMachineTemplatePut()); + + assertRequestLineEquals(request, + "GET http://localhost/api/admin/enterprises/1/datacenterrepositories/1/virtualmachinetemplates/1/conversions HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + ConversionsDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testListConversionsWithOptions() throws SecurityException, NoSuchMethodException, IOException { + Method method = VirtualMachineTemplateAsyncApi.class.getMethod("listConversions", + VirtualMachineTemplateDto.class, ConversionOptions.class); + GeneratedHttpRequest request = processor.createRequest( + method, + TemplateResources.virtualMachineTemplatePut(), + ConversionOptions.builder().hypervisorType(HypervisorType.XENSERVER) + .conversionState(ConversionState.FINISHED).build()); + + assertRequestLineEquals(request, + "GET http://localhost/api/admin/enterprises/1/datacenterrepositories/1/virtualmachinetemplates/1/conversions" + + "?hypervisor=XENSERVER&state=FINISHED HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + ConversionsDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testGetConversion() throws SecurityException, NoSuchMethodException, IOException { + Method method = VirtualMachineTemplateAsyncApi.class.getMethod("getConversion", VirtualMachineTemplateDto.class, + DiskFormatType.class); + GeneratedHttpRequest request = processor.createRequest(method, TemplateResources.virtualMachineTemplatePut(), + DiskFormatType.RAW); + + assertRequestLineEquals( + request, + "GET http://localhost/api/admin/enterprises/1/datacenterrepositories/1/virtualmachinetemplates/1/conversions/RAW HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + ConversionDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, ParseXMLWithJAXB.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); + + checkFilters(request); + } + + @Override + protected TypeLiteral> createTypeLiteral() { + return new TypeLiteral>() { + }; + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/functions/AppendApiVersionToAbiquoMimeTypeTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/functions/AppendApiVersionToAbiquoMimeTypeTest.java new file mode 100644 index 0000000000..1867008fc1 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/functions/AppendApiVersionToAbiquoMimeTypeTest.java @@ -0,0 +1,64 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.functions; + +import static org.testng.Assert.assertEquals; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.testng.annotations.Test; + +import com.google.common.base.Function; + +/** + * Unit tests for the {@link AppendApiVersionToAbiquoMimeType} function. + * + * @author Ignasi Barrera + */ +@Test(groups = "unit", testName = "AppendApiVersionToAbiquoMimeTypeTest") +public class AppendApiVersionToAbiquoMimeTypeTest { + @Test(expectedExceptions = NullPointerException.class) + public void testApplyWithNullInput() { + Function function = new AppendApiVersionToAbiquoMimeType(AbiquoAsyncApi.API_VERSION); + function.apply(null); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testApplyWithInvalidMediaType() { + Function function = new AppendApiVersionToAbiquoMimeType(AbiquoAsyncApi.API_VERSION); + function.apply("foo"); + } + + public void testApplyToStandardMediaType() { + Function function = new AppendApiVersionToAbiquoMimeType(AbiquoAsyncApi.API_VERSION); + assertEquals(function.apply("application/xml"), "application/xml"); + } + + public void testApplyToAbiquoMediaTypeWithVersion() { + Function function = new AppendApiVersionToAbiquoMimeType(AbiquoAsyncApi.API_VERSION); + assertEquals(function.apply("application/vnd.abiquo.datacenters+xml;version=1.8.5"), + "application/vnd.abiquo.datacenters+xml;version=1.8.5"); + } + + public void testApplyToAbiquoMediaTypeWithoutVersion() { + Function function = new AppendApiVersionToAbiquoMimeType(AbiquoAsyncApi.API_VERSION); + assertEquals(function.apply("application/vnd.abiquo.datacenters+xml"), + "application/vnd.abiquo.datacenters+xml;version=" + AbiquoAsyncApi.API_VERSION); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/functions/ReturnAbiquoExceptionOnNotFoundOr4xxTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/functions/ReturnAbiquoExceptionOnNotFoundOr4xxTest.java new file mode 100644 index 0000000000..2bcd2ec9e8 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/functions/ReturnAbiquoExceptionOnNotFoundOr4xxTest.java @@ -0,0 +1,73 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.functions; + +import static org.testng.Assert.assertEquals; + +import javax.ws.rs.core.Response.Status; + +import org.jclouds.abiquo.domain.exception.AbiquoException; +import org.jclouds.rest.ResourceNotFoundException; +import org.testng.annotations.Test; + +import com.abiquo.model.transport.error.ErrorsDto; +import com.google.common.base.Function; + +/** + * Unit tests for the {@link ReturnAbiquoExceptionOnNotFoundOr4xx} function. + * + * @author Ignasi Barrera + */ +@Test(groups = "unit", testName = "ReturnAbiquoExceptionOnNotFoundOr4xxTest") +public class ReturnAbiquoExceptionOnNotFoundOr4xxTest { + public void testReturnOriginalExceptionIfNotResourceNotFound() { + Function function = new ReturnAbiquoExceptionOnNotFoundOr4xx(); + RuntimeException exception = new RuntimeException(); + + try { + function.apply(exception); + } catch (Exception ex) { + assertEquals(ex, exception); + } + } + + public void testReturnOriginalExceptionIfNotAbiquoException() { + Function function = new ReturnAbiquoExceptionOnNotFoundOr4xx(); + ResourceNotFoundException exception = new ResourceNotFoundException(); + + try { + function.apply(exception); + } catch (Exception ex) { + assertEquals(ex, exception); + } + } + + public void testReturnAbiquoException() { + Function function = new ReturnAbiquoExceptionOnNotFoundOr4xx(); + AbiquoException abiquoException = new AbiquoException(Status.NOT_FOUND, new ErrorsDto()); + ResourceNotFoundException exception = new ResourceNotFoundException(abiquoException); + + try { + function.apply(exception); + } catch (Exception ex) { + assertEquals(ex, abiquoException); + } + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/functions/ReturnFalseIfNotAvailableTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/functions/ReturnFalseIfNotAvailableTest.java new file mode 100644 index 0000000000..a4bc6f978d --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/functions/ReturnFalseIfNotAvailableTest.java @@ -0,0 +1,110 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.functions; + +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; +import static org.testng.Assert.assertEquals; + +import org.easymock.EasyMock; +import org.jclouds.http.HttpResponse; +import org.jclouds.http.HttpResponseException; +import org.jclouds.rest.ResourceNotFoundException; +import org.testng.annotations.Test; + +import com.google.common.base.Function; + +/** + * Unit tests for the {@link ReturnFalseIfNotAvailable} function. + * + * @author Ignasi Barrera + */ +@Test(groups = "unit", testName = "ReturnFalseIfNotAvailableTest") +public class ReturnFalseIfNotAvailableTest { + public void testReturnOriginalExceptionIfUnknownException() { + Function function = new ReturnFalseIfNotAvailable(); + RuntimeException exception = new RuntimeException(); + + try { + function.apply(exception); + } catch (Exception ex) { + assertEquals(ex, exception); + } + } + + public void testReturnFalseIf5xx() { + Function function = new ReturnFalseIfNotAvailable(); + HttpResponse response = EasyMock.createMock(HttpResponse.class); + HttpResponseException exception = EasyMock.createMock(HttpResponseException.class); + + // Status code is called twice + expect(response.getStatusCode()).andReturn(503); + expect(response.getStatusCode()).andReturn(503); + // Get response gets called twice + expect(exception.getResponse()).andReturn(response); + expect(exception.getResponse()).andReturn(response); + // Get cause is called to determine the root cause + expect(exception.getCause()).andReturn(null); + + replay(response); + replay(exception); + + assertEquals(function.apply(exception), false); + + verify(response); + verify(exception); + } + + public void testReturnExceptionIfNot5xx() { + Function function = new ReturnFalseIfNotAvailable(); + HttpResponse response = EasyMock.createMock(HttpResponse.class); + HttpResponseException exception = EasyMock.createMock(HttpResponseException.class); + + // Status code is called twice + expect(response.getStatusCode()).andReturn(600); + expect(response.getStatusCode()).andReturn(600); + // Get response gets called twice + expect(exception.getResponse()).andReturn(response); + expect(exception.getResponse()).andReturn(response); + // Get cause is called to determine the root cause + expect(exception.getCause()).andReturn(null); + + replay(response); + replay(exception); + + try { + function.apply(exception); + } catch (Exception ex) { + assertEquals(ex, exception); + } + + verify(response); + verify(exception); + } + + public void testReturnFalseIfResourceNotFound() { + Function function = new ReturnFalseIfNotAvailable(); + ResourceNotFoundException exception = new ResourceNotFoundException(); + + assertEquals(function.apply(exception), false); + } + +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/functions/ReturnFalseOn5xxTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/functions/ReturnFalseOn5xxTest.java new file mode 100644 index 0000000000..745793408f --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/functions/ReturnFalseOn5xxTest.java @@ -0,0 +1,101 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.functions; + +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; +import static org.testng.Assert.assertEquals; + +import org.easymock.EasyMock; +import org.jclouds.http.HttpResponse; +import org.jclouds.http.HttpResponseException; +import org.testng.annotations.Test; + +import com.google.common.base.Function; + +/** + * Unit tests for the {@link ReturnFalseOn5xx} function. + * + * @author Ignasi Barrera + */ +@Test(groups = "unit", testName = "ReturnFalseOn5xxTest") +public class ReturnFalseOn5xxTest { + public void testReturnOriginalExceptionIfNotHttpResponseException() { + Function function = new ReturnFalseOn5xx(); + RuntimeException exception = new RuntimeException(); + + try { + function.apply(exception); + } catch (Exception ex) { + assertEquals(ex, exception); + } + } + + public void testReturnFalseIf5xx() { + Function function = new ReturnFalseOn5xx(); + HttpResponse response = EasyMock.createMock(HttpResponse.class); + HttpResponseException exception = EasyMock.createMock(HttpResponseException.class); + + // Status code is called twice + expect(response.getStatusCode()).andReturn(503); + expect(response.getStatusCode()).andReturn(503); + // Get response gets called twice + expect(exception.getResponse()).andReturn(response); + expect(exception.getResponse()).andReturn(response); + // Get cause is called to determine the root cause + expect(exception.getCause()).andReturn(null); + + replay(response); + replay(exception); + + assertEquals(function.apply(exception), false); + + verify(response); + verify(exception); + } + + public void testReturnExceptionIfNot5xx() { + Function function = new ReturnFalseOn5xx(); + HttpResponse response = EasyMock.createMock(HttpResponse.class); + HttpResponseException exception = EasyMock.createMock(HttpResponseException.class); + + // Status code is called twice + expect(response.getStatusCode()).andReturn(600); + expect(response.getStatusCode()).andReturn(600); + // Get response gets called twice + expect(exception.getResponse()).andReturn(response); + expect(exception.getResponse()).andReturn(response); + // Get cause is called to determine the root cause + expect(exception.getCause()).andReturn(null); + + replay(response); + replay(exception); + + try { + function.apply(exception); + } catch (Exception ex) { + assertEquals(ex, exception); + } + + verify(response); + verify(exception); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/functions/ReturnNullOn303Test.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/functions/ReturnNullOn303Test.java new file mode 100644 index 0000000000..b3ba8dc182 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/functions/ReturnNullOn303Test.java @@ -0,0 +1,100 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.functions; + +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNull; + +import org.easymock.EasyMock; +import org.jclouds.http.HttpResponse; +import org.jclouds.http.HttpResponseException; +import org.testng.annotations.Test; + +import com.google.common.base.Function; + +/** + * Unit tests for the {@link ReturnNullOn303} function. + * + * @author Ignasi Barrera + */ +@Test(groups = "unit", testName = "ReturnNullOn303Test") +public class ReturnNullOn303Test { + public void testReturnOriginalExceptionIfNotHttpResponseException() { + Function function = new ReturnNullOn303(); + RuntimeException exception = new RuntimeException(); + + try { + function.apply(exception); + } catch (Exception ex) { + assertEquals(ex, exception); + } + } + + public void testReturnNullIf303() { + Function function = new ReturnNullOn303(); + HttpResponse response = EasyMock.createMock(HttpResponse.class); + HttpResponseException exception = EasyMock.createMock(HttpResponseException.class); + + // Status code is called once + expect(response.getStatusCode()).andReturn(303); + // Get response gets called twice + expect(exception.getResponse()).andReturn(response); + expect(exception.getResponse()).andReturn(response); + // Get cause is called to determine the root cause + expect(exception.getCause()).andReturn(null); + + replay(response); + replay(exception); + + assertNull(function.apply(exception)); + + verify(response); + verify(exception); + } + + public void testReturnExceptionIfNot303() { + Function function = new ReturnNullOn303(); + HttpResponse response = EasyMock.createMock(HttpResponse.class); + HttpResponseException exception = EasyMock.createMock(HttpResponseException.class); + + // Status code is called once + expect(response.getStatusCode()).andReturn(600); + // Get response gets called twice + expect(exception.getResponse()).andReturn(response); + expect(exception.getResponse()).andReturn(response); + // Get cause is called to determine the root cause + expect(exception.getCause()).andReturn(null); + + replay(response); + replay(exception); + + try { + function.apply(exception); + } catch (Exception ex) { + assertEquals(ex, exception); + } + + verify(response); + verify(exception); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/functions/ReturnTaskReferenceOrNullTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/functions/ReturnTaskReferenceOrNullTest.java new file mode 100644 index 0000000000..fcaf2eda6d --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/functions/ReturnTaskReferenceOrNullTest.java @@ -0,0 +1,94 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.functions; + +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertTrue; + +import java.io.IOException; + +import javax.ws.rs.core.Response.Status; + +import org.easymock.EasyMock; +import org.jclouds.http.HttpResponse; +import org.jclouds.io.Payload; +import org.jclouds.io.Payloads; +import org.jclouds.xml.internal.JAXBParser; +import org.testng.annotations.Test; + +import com.abiquo.model.transport.AcceptedRequestDto; +import com.google.common.base.Function; +import com.google.inject.TypeLiteral; + +/** + * Unit tests for the {@link ReturnTaskReferenceOrNull} function. + * + * @author Ignasi Barrera + */ +@Test(groups = "unit", testName = "ReturnTaskReferenceOrNullTest") +public class ReturnTaskReferenceOrNullTest { + public void testReturnNullIfNoContent() { + Function> function = new ReturnTaskReferenceOrNull(new JAXBParser( + "false"), createTypeLiteral()); + + HttpResponse response = EasyMock.createMock(HttpResponse.class); + + expect(response.getStatusCode()).andReturn(Status.NO_CONTENT.getStatusCode()); + expect(response.getPayload()).andReturn(null); + + replay(response); + + assertNull(function.apply(response)); + + verify(response); + } + + public void testReturnTaskIfAccepted() throws IOException { + JAXBParser parser = new JAXBParser("false"); + AcceptedRequestDto task = new AcceptedRequestDto(); + Payload payload = Payloads.newPayload(parser.toXML(task)); + + Function> function = new ReturnTaskReferenceOrNull(parser, + createTypeLiteral()); + + HttpResponse response = EasyMock.createMock(HttpResponse.class); + + expect(response.getStatusCode()).andReturn(Status.ACCEPTED.getStatusCode()); + // Get payload is called three times: one to deserialize it, and twice to + // release it + expect(response.getPayload()).andReturn(payload); + expect(response.getPayload()).andReturn(payload); + expect(response.getPayload()).andReturn(payload); + + replay(response); + + assertTrue(function.apply(response) instanceof AcceptedRequestDto); + + verify(response); + } + + private static TypeLiteral> createTypeLiteral() { + return new TypeLiteral>() { + }; + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/functions/cloud/ReturnMovedVolumeTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/functions/cloud/ReturnMovedVolumeTest.java new file mode 100644 index 0000000000..628b384bdf --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/functions/cloud/ReturnMovedVolumeTest.java @@ -0,0 +1,99 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.functions.cloud; + +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; +import static org.testng.Assert.assertEquals; + +import java.io.IOException; + +import javax.ws.rs.core.Response.Status; + +import org.easymock.EasyMock; +import org.jclouds.http.HttpResponse; +import org.jclouds.http.HttpResponseException; +import org.jclouds.io.Payload; +import org.jclouds.io.Payloads; +import org.jclouds.xml.internal.JAXBParser; +import org.testng.annotations.Test; + +import com.abiquo.server.core.infrastructure.storage.MovedVolumeDto; +import com.abiquo.server.core.infrastructure.storage.VolumeManagementDto; +import com.google.common.base.Function; +import com.google.inject.TypeLiteral; + +/** + * Unit tests for the {@link ReturnMovedVolume} function. + * + * @author Ignasi Barrera + */ +@Test(groups = "unit", testName = "ReturnMovedVolumeTest") +public class ReturnMovedVolumeTest { + public void testReturnOriginalExceptionIfNotHttpResponseException() { + Function function = new ReturnMovedVolume(new ReturnMoveVolumeReference( + new JAXBParser("false"), TypeLiteral.get(MovedVolumeDto.class))); + + RuntimeException exception = new RuntimeException(); + + try { + function.apply(exception); + } catch (Exception ex) { + assertEquals(ex, exception); + } + } + + public void testReturnVolume() throws IOException { + JAXBParser xmlParser = new JAXBParser("false"); + Function function = new ReturnMovedVolume(new ReturnMoveVolumeReference( + new JAXBParser("false"), TypeLiteral.get(MovedVolumeDto.class))); + + VolumeManagementDto volume = new VolumeManagementDto(); + volume.setName("Test volume"); + MovedVolumeDto movedRef = new MovedVolumeDto(); + movedRef.setVolume(volume); + + HttpResponse response = EasyMock.createMock(HttpResponse.class); + HttpResponseException exception = EasyMock.createMock(HttpResponseException.class); + Payload payload = Payloads.newPayload(xmlParser.toXML(movedRef)); + + // Status code is called once + expect(response.getStatusCode()).andReturn(Status.MOVED_PERMANENTLY.getStatusCode()); + // Get response gets called twice + expect(exception.getResponse()).andReturn(response); + expect(exception.getResponse()).andReturn(response); + // Get payload is called three times: one to deserialize it, and twice to + // release it + expect(response.getPayload()).andReturn(payload); + expect(response.getPayload()).andReturn(payload); + expect(response.getPayload()).andReturn(payload); + // Get cause is called to determine the root cause + expect(exception.getCause()).andReturn(null); + + replay(response); + replay(exception); + + function.apply(exception); + + verify(response); + verify(exception); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/functions/enterprise/ParseEnterpriseIdTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/functions/enterprise/ParseEnterpriseIdTest.java new file mode 100644 index 0000000000..5f034ef0b1 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/functions/enterprise/ParseEnterpriseIdTest.java @@ -0,0 +1,61 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.functions.enterprise; + +import static org.testng.Assert.assertEquals; + +import org.testng.annotations.Test; + +import com.abiquo.server.core.enterprise.EnterpriseDto; +import com.google.common.base.Function; + +/** + * Unit tests for the {@link ParseEnterpriseId} function. + * + * @author Francesc Montserrat + */ +@Test(groups = "unit", testName = "ParseEnterpriseIdTest") +public class ParseEnterpriseIdTest { + @Test(expectedExceptions = NullPointerException.class) + public void testInvalidNullInput() { + Function parser = new ParseEnterpriseId(); + parser.apply(null); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testInvalidInputType() { + Function parser = new ParseEnterpriseId(); + parser.apply(new Object()); + } + + @Test(expectedExceptions = NullPointerException.class) + public void testInvalidId() { + Function parser = new ParseEnterpriseId(); + parser.apply(new EnterpriseDto()); + } + + public void testValidId() { + Function parser = new ParseEnterpriseId(); + + EnterpriseDto enterprise = new EnterpriseDto(); + enterprise.setId(5); + assertEquals(parser.apply(enterprise), "5"); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/functions/infrastructure/ParseDatacenterIdTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/functions/infrastructure/ParseDatacenterIdTest.java new file mode 100644 index 0000000000..48aca7b9fc --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/functions/infrastructure/ParseDatacenterIdTest.java @@ -0,0 +1,61 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.functions.infrastructure; + +import static org.testng.Assert.assertEquals; + +import org.testng.annotations.Test; + +import com.abiquo.server.core.infrastructure.DatacenterDto; +import com.google.common.base.Function; + +/** + * Unit tests for the {@link ParseDatacenterId} function. + * + * @author Francesc Montserrat + */ +@Test(groups = "unit", testName = "ParseDatacenterIdTest") +public class ParseDatacenterIdTest { + @Test(expectedExceptions = NullPointerException.class) + public void testInvalidNullInput() { + Function parser = new ParseDatacenterId(); + parser.apply(null); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testInvalidInputType() { + Function parser = new ParseDatacenterId(); + parser.apply(new Object()); + } + + @Test(expectedExceptions = NullPointerException.class) + public void testInvalidId() { + Function parser = new ParseDatacenterId(); + parser.apply(new DatacenterDto()); + } + + public void testValidId() { + Function parser = new ParseDatacenterId(); + + DatacenterDto datacenter = new DatacenterDto(); + datacenter.setId(5); + assertEquals(parser.apply(datacenter), "5"); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/functions/infrastructure/ParseMachineIdTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/functions/infrastructure/ParseMachineIdTest.java new file mode 100644 index 0000000000..27647d8775 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/functions/infrastructure/ParseMachineIdTest.java @@ -0,0 +1,61 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.functions.infrastructure; + +import static org.testng.Assert.assertEquals; + +import org.testng.annotations.Test; + +import com.abiquo.server.core.infrastructure.MachineDto; +import com.google.common.base.Function; + +/** + * Unit tests for the {@link ParseMachineId} function. + * + * @author Ignasi Barrera + */ +@Test(groups = "unit", testName = "ParseMachineIdTest") +public class ParseMachineIdTest { + @Test(expectedExceptions = NullPointerException.class) + public void testInvalidNullInput() { + Function parser = new ParseMachineId(); + parser.apply(null); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testInvalidInputType() { + Function parser = new ParseMachineId(); + parser.apply(new Object()); + } + + @Test(expectedExceptions = NullPointerException.class) + public void testInvalidId() { + Function parser = new ParseMachineId(); + parser.apply(new MachineDto()); + } + + public void testValidId() { + Function parser = new ParseMachineId(); + + MachineDto machine = new MachineDto(); + machine.setId(5); + assertEquals(parser.apply(machine), "5"); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/functions/infrastructure/ParseRemoteServiceTypeTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/functions/infrastructure/ParseRemoteServiceTypeTest.java new file mode 100644 index 0000000000..072e0147f5 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/functions/infrastructure/ParseRemoteServiceTypeTest.java @@ -0,0 +1,52 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.functions.infrastructure; + +import static org.testng.Assert.assertEquals; + +import org.testng.annotations.Test; + +import com.abiquo.model.enumerator.RemoteServiceType; +import com.google.common.base.Function; + +/** + * Unit tests for the {@link ParseRemoteServiceType} functions. + * + * @author Francesc Montserrat + */ +@Test(groups = "unit", testName = "ParseRemoteServiceTypeTest") +public class ParseRemoteServiceTypeTest { + @Test(expectedExceptions = NullPointerException.class) + public void testInvalidNullInput() { + Function parser = new ParseRemoteServiceType(); + parser.apply(null); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testInvalidInputType() { + Function parser = new ParseRemoteServiceType(); + parser.apply(new Object()); + } + + public void testValidId() { + Function parser = new ParseRemoteServiceType(); + assertEquals(parser.apply(RemoteServiceType.BPM_SERVICE), "bpmservice"); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/http/filters/AbiquoAuthenticationLiveApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/http/filters/AbiquoAuthenticationLiveApiTest.java new file mode 100644 index 0000000000..5ed7e84b82 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/http/filters/AbiquoAuthenticationLiveApiTest.java @@ -0,0 +1,176 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.http.filters; + +import static com.google.common.base.Preconditions.checkNotNull; +import static org.jclouds.http.HttpUtils.releasePayload; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.fail; + +import java.io.IOException; +import java.net.URI; +import java.util.Collection; +import java.util.Properties; + +import javax.ws.rs.core.Cookie; +import javax.ws.rs.core.HttpHeaders; + +import org.jclouds.ContextBuilder; +import org.jclouds.abiquo.AbiquoApiMetadata; +import org.jclouds.abiquo.AbiquoContext; +import org.jclouds.abiquo.config.AbiquoProperties; +import org.jclouds.http.HttpRequest; +import org.jclouds.http.HttpResponse; +import org.jclouds.logging.slf4j.config.SLF4JLoggingModule; +import org.jclouds.rest.AuthorizationException; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import com.abiquo.server.core.enterprise.UserDto; +import com.google.common.collect.ImmutableSet; +import com.google.inject.Module; + +/** + * Live tests for the {@link AbiquoAuthentication} filter. + * + * @author Ignasi Barrera + */ +@Test(groups = "api", testName = "AbiquoAuthenticationLiveApiTest") +public class AbiquoAuthenticationLiveApiTest { + private String identity; + + private String credential; + + private String endpoint; + + @BeforeMethod + public void setupToken() { + identity = checkNotNull(System.getProperty("test.abiquo.identity"), "test.abiquo.identity"); + credential = checkNotNull(System.getProperty("test.abiquo.credential"), "test.abiquo.credential"); + endpoint = checkNotNull(System.getProperty("test.abiquo.endpoint"), "test.abiquo.endpoint"); + } + + @Test + public void testAuthenticateWithToken() throws IOException { + String token = getAuthtenticationToken(); + + Properties props = new Properties(); + props.setProperty(AbiquoProperties.CREDENTIAL_IS_TOKEN, "true"); + + // Create a new context that uses the generated token to perform the API + // calls + AbiquoContext tokenContext = ContextBuilder.newBuilder(new AbiquoApiMetadata()) // + .endpoint(endpoint) // + .credentials("token", token) // + .modules(ImmutableSet. of(new SLF4JLoggingModule())) // + .overrides(props) // + .build(AbiquoContext.class); + + try { + // Perform a call to get the logged user and verify the identity + UserDto user = tokenContext.getApiContext().getApi().getAdminApi().getCurrentUser(); + assertNotNull(user); + assertEquals(user.getNick(), identity); + } finally { + if (tokenContext != null) { + tokenContext.close(); + } + } + } + + @Test + public void testAuthenticateWithInvalidToken() throws IOException { + String token = getAuthtenticationToken() + "INVALID"; + + Properties props = new Properties(); + props.setProperty(AbiquoProperties.CREDENTIAL_IS_TOKEN, "true"); + + // Create a new context that uses the generated token to perform the API + // calls + AbiquoContext tokenContext = ContextBuilder.newBuilder(new AbiquoApiMetadata()) // + .endpoint(endpoint) // + .credentials("token", token) // + .modules(ImmutableSet. of(new SLF4JLoggingModule())) // + .overrides(props) // + .build(AbiquoContext.class); + + // Perform a call to get the logged user. It should fail + try { + tokenContext.getApiContext().getApi().getAdminApi().getCurrentUser(); + } catch (AuthorizationException ex) { + // Test succeeded + return; + } finally { + if (tokenContext != null) { + tokenContext.close(); + } + } + + fail("Token authentication should have failed"); + } + + private String getAuthtenticationToken() { + String token = null; + + AbiquoContext context = ContextBuilder.newBuilder(new AbiquoApiMetadata()) // + .endpoint(endpoint) // + .credentials(identity, credential) // + .modules(ImmutableSet. of(new SLF4JLoggingModule())) // + .build(AbiquoContext.class); + + try { + // Create a request to authenticate to the API and generate the token + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create(endpoint)).build(); + String auth = AbiquoAuthentication.basicAuth(identity, credential); + request = request.toBuilder().replaceHeader(HttpHeaders.AUTHORIZATION, auth).build(); + + // Execute the request and read the generated token + HttpResponse response = context.utils().http().invoke(request); + assertEquals(response.getStatusCode(), 200); + + token = readAuthenticationToken(response); + assertNotNull(token); + + releasePayload(response); + } finally { + if (context != null) { + context.close(); + } + } + + return token; + } + + private String readAuthenticationToken(final HttpResponse response) { + Collection cookies = response.getHeaders().get(HttpHeaders.SET_COOKIE); + assertFalse(cookies.isEmpty()); + + for (String cookie : cookies) { + Cookie c = Cookie.valueOf(cookie); + if (c.getName().equals(AbiquoAuthentication.AUTH_TOKEN_NAME)) { + return c.getValue(); + } + } + + return null; + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/http/filters/AbiquoAuthenticationTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/http/filters/AbiquoAuthenticationTest.java new file mode 100644 index 0000000000..e93258e787 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/http/filters/AbiquoAuthenticationTest.java @@ -0,0 +1,81 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.http.filters; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; + +import java.net.URI; +import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateException; + +import javax.ws.rs.core.HttpHeaders; + +import org.jclouds.http.HttpRequest; +import org.testng.annotations.Test; + +/** + * Unit tests for the {@link AbiquoAuthentication} filter. + * + * @author Ignasi Barrera + */ +@Test(groups = "unit", testName = "AbiquoAuthenticationTest") +public class AbiquoAuthenticationTest { + + public void testBasicAuthentication() throws NoSuchAlgorithmException, CertificateException { + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://foo")).build(); + + AbiquoAuthentication filter = new AbiquoAuthentication("identity", "credential", "false"); + HttpRequest filtered = filter.filter(request); + HttpRequest expected = request.toBuilder() + .replaceHeader(HttpHeaders.AUTHORIZATION, AbiquoAuthentication.basicAuth("identity", "credential")).build(); + + assertFalse(filtered.getHeaders().containsKey(HttpHeaders.COOKIE)); + assertEquals(filtered, expected); + } + + @Test(expectedExceptions = NullPointerException.class) + public void testBasicAuthenticationWithoutIdentity() throws NoSuchAlgorithmException, CertificateException { + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://foo")).build(); + + AbiquoAuthentication filter = new AbiquoAuthentication(null, "credential", "false"); + filter.filter(request); + } + + @Test(expectedExceptions = NullPointerException.class) + public void testBasicAuthenticationWithoutCredential() throws NoSuchAlgorithmException, CertificateException { + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://foo")).build(); + + AbiquoAuthentication filter = new AbiquoAuthentication("identity", null, "false"); + filter.filter(request); + } + + public void testTokenAuthentication() throws NoSuchAlgorithmException, CertificateException { + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://foo")).build(); + + AbiquoAuthentication filter = new AbiquoAuthentication("token-identity", "token", "true"); + HttpRequest filtered = filter.filter(request); + HttpRequest expected = request.toBuilder() + .replaceHeader(HttpHeaders.COOKIE, AbiquoAuthentication.tokenAuth("token")).build(); + + assertFalse(filtered.getHeaders().containsKey(HttpHeaders.AUTHORIZATION)); + assertEquals(filtered, expected); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/http/filters/AppendApiVersionToMediaTypeTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/http/filters/AppendApiVersionToMediaTypeTest.java new file mode 100644 index 0000000000..73a29dd41c --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/http/filters/AppendApiVersionToMediaTypeTest.java @@ -0,0 +1,274 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.http.filters; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertTrue; + +import java.net.URI; +import java.util.Collection; + +import javax.ws.rs.core.HttpHeaders; + +import org.jclouds.abiquo.AbiquoAsyncApi; +import org.jclouds.abiquo.functions.AppendApiVersionToAbiquoMimeType; +import org.jclouds.http.HttpRequest; +import org.jclouds.io.Payload; +import org.jclouds.io.Payloads; +import org.testng.annotations.Test; + +import com.google.common.collect.LinkedHashMultimap; +import com.google.common.collect.Multimap; + +/** + * Unit tests for the {@link AppendApiVersionToMediaType} filter. + * + * @author Ignasi Barrera + */ +@Test(groups = "unit", testName = "AppendApiVersionToMediaTypeTest") +public class AppendApiVersionToMediaTypeTest { + + public void testAppendVersionToNonPayloadHeadersWithoutHeaders() { + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://foo")).build(); + + AppendApiVersionToMediaType filter = new AppendApiVersionToMediaType(new AppendApiVersionToAbiquoMimeType( + AbiquoAsyncApi.API_VERSION)); + + HttpRequest filtered = filter.appendVersionToNonPayloadHeaders(request); + + assertTrue(filtered.getHeaders().get(HttpHeaders.ACCEPT).isEmpty()); + } + + public void testAppendVersionToNonPayloadHeadersWithStandardMediaType() { + Multimap headers = LinkedHashMultimap. create(); + headers.put(HttpHeaders.ACCEPT, "application/xml"); + + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://foo")).headers(headers) + .build(); + + AppendApiVersionToMediaType filter = new AppendApiVersionToMediaType(new AppendApiVersionToAbiquoMimeType( + AbiquoAsyncApi.API_VERSION)); + + HttpRequest filtered = filter.appendVersionToNonPayloadHeaders(request); + + Collection contentType = filtered.getHeaders().get(HttpHeaders.ACCEPT); + assertEquals(contentType.size(), 1); + assertEquals(contentType.iterator().next(), "application/xml"); + } + + public void testAppendVersionToNonPayloadHeadersWithVersionInMediaType() { + Multimap headers = LinkedHashMultimap. create(); + headers.put(HttpHeaders.ACCEPT, "application/vnd.abiquo.racks+xml;version=2.1-SNAPSHOT"); + + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://foo")).headers(headers) + .build(); + + AppendApiVersionToMediaType filter = new AppendApiVersionToMediaType(new AppendApiVersionToAbiquoMimeType( + AbiquoAsyncApi.API_VERSION)); + + HttpRequest filtered = filter.appendVersionToNonPayloadHeaders(request); + + Collection contentType = filtered.getHeaders().get(HttpHeaders.ACCEPT); + assertEquals(contentType.size(), 1); + assertEquals(contentType.iterator().next(), "application/vnd.abiquo.racks+xml;version=2.1-SNAPSHOT"); + } + + public void testAppendVersionToNonPayloadHeadersWithoutVersionInMediaType() { + Multimap headers = LinkedHashMultimap. create(); + headers.put(HttpHeaders.ACCEPT, "application/vnd.abiquo.racks+xml"); + + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://foo")).headers(headers) + .build(); + + AppendApiVersionToMediaType filter = new AppendApiVersionToMediaType(new AppendApiVersionToAbiquoMimeType( + AbiquoAsyncApi.API_VERSION)); + + HttpRequest filtered = filter.appendVersionToNonPayloadHeaders(request); + + Collection accept = filtered.getHeaders().get(HttpHeaders.ACCEPT); + assertEquals(accept.size(), 1); + assertEquals(accept.iterator().next(), "application/vnd.abiquo.racks+xml;version=" + AbiquoAsyncApi.API_VERSION); + } + + public void testAppendVersionToPayloadHeadersWithoutPayload() { + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://foo")).build(); + + AppendApiVersionToMediaType filter = new AppendApiVersionToMediaType(new AppendApiVersionToAbiquoMimeType( + AbiquoAsyncApi.API_VERSION)); + + HttpRequest filtered = filter.appendVersionToPayloadHeaders(request); + + assertNull(filtered.getPayload()); + } + + public void testAppendVersionToPayloadHeadersWithStandardPayload() { + Payload payload = Payloads.newByteArrayPayload(new byte[] {}); + payload.getContentMetadata().setContentType("application/xml"); + + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://foo")).payload(payload) + .build(); + + AppendApiVersionToMediaType filter = new AppendApiVersionToMediaType(new AppendApiVersionToAbiquoMimeType( + AbiquoAsyncApi.API_VERSION)); + + HttpRequest filtered = filter.appendVersionToPayloadHeaders(request); + + assertEquals(filtered.getPayload().getContentMetadata().getContentType(), "application/xml"); + } + + public void testAppendVersionToPayloadHeadersWithDefaultPayload() { + Payload payload = Payloads.newByteArrayPayload(new byte[] {}); + + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://foo")).payload(payload) + .build(); + + AppendApiVersionToMediaType filter = new AppendApiVersionToMediaType(new AppendApiVersionToAbiquoMimeType( + AbiquoAsyncApi.API_VERSION)); + + HttpRequest filtered = filter.appendVersionToPayloadHeaders(request); + + assertEquals(filtered.getPayload().getContentMetadata().getContentType(), "application/unknown"); + } + + public void testAppendVersionToPayloadHeadersWithVersionInPayload() { + Payload payload = Payloads.newByteArrayPayload(new byte[] {}); + payload.getContentMetadata().setContentType("application/vnd.abiquo.racks+xml;version=1.8.5"); + + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://foo")).payload(payload) + .build(); + + AppendApiVersionToMediaType filter = new AppendApiVersionToMediaType(new AppendApiVersionToAbiquoMimeType( + AbiquoAsyncApi.API_VERSION)); + + HttpRequest filtered = filter.appendVersionToPayloadHeaders(request); + + assertEquals(filtered.getPayload().getContentMetadata().getContentType(), + "application/vnd.abiquo.racks+xml;version=1.8.5"); + } + + public void testAppendVersionToPayloadHeadersWithoutVersionInPayload() { + Payload payload = Payloads.newByteArrayPayload(new byte[] {}); + payload.getContentMetadata().setContentType("application/vnd.abiquo.racks+xml"); + + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://foo")).payload(payload) + .build(); + + AppendApiVersionToMediaType filter = new AppendApiVersionToMediaType(new AppendApiVersionToAbiquoMimeType( + AbiquoAsyncApi.API_VERSION)); + + HttpRequest filtered = filter.appendVersionToPayloadHeaders(request); + + assertEquals(filtered.getPayload().getContentMetadata().getContentType(), + "application/vnd.abiquo.racks+xml;version=" + AbiquoAsyncApi.API_VERSION); + } + + public void testFilterWithAcceptAndContentTypeWithVersion() { + Payload payload = Payloads.newByteArrayPayload(new byte[] {}); + payload.getContentMetadata().setContentType("application/vnd.abiquo.racks+xml;version=2.1-SNAPSHOT"); + + Multimap headers = LinkedHashMultimap. create(); + headers.put(HttpHeaders.ACCEPT, "application/vnd.abiquo.racks+xml;version=2.1-SNAPSHOT"); + + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://foo")).headers(headers) + .payload(payload).build(); + + AppendApiVersionToMediaType filter = new AppendApiVersionToMediaType(new AppendApiVersionToAbiquoMimeType( + AbiquoAsyncApi.API_VERSION)); + + HttpRequest filtered = filter.filter(request); + + Collection accept = filtered.getHeaders().get(HttpHeaders.ACCEPT); + assertEquals(accept.size(), 1); + assertEquals(accept.iterator().next(), "application/vnd.abiquo.racks+xml;version=2.1-SNAPSHOT"); + + assertEquals(filtered.getPayload().getContentMetadata().getContentType(), + "application/vnd.abiquo.racks+xml;version=2.1-SNAPSHOT"); + } + + public void testFilterWithAcceptAndContentTypeWithoutVersion() { + Payload payload = Payloads.newByteArrayPayload(new byte[] {}); + payload.getContentMetadata().setContentType("application/vnd.abiquo.racks+xml"); + + Multimap headers = LinkedHashMultimap. create(); + headers.put(HttpHeaders.ACCEPT, "application/vnd.abiquo.racks+xml"); + + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://foo")).headers(headers) + .payload(payload).build(); + + AppendApiVersionToMediaType filter = new AppendApiVersionToMediaType(new AppendApiVersionToAbiquoMimeType( + AbiquoAsyncApi.API_VERSION)); + + HttpRequest filtered = filter.filter(request); + + Collection accept = filtered.getHeaders().get(HttpHeaders.ACCEPT); + assertEquals(accept.size(), 1); + assertEquals(accept.iterator().next(), "application/vnd.abiquo.racks+xml;version=" + AbiquoAsyncApi.API_VERSION); + + assertEquals(filtered.getPayload().getContentMetadata().getContentType(), + "application/vnd.abiquo.racks+xml;version=" + AbiquoAsyncApi.API_VERSION); + } + + public void testFilterWithversionInAccept() { + Payload payload = Payloads.newByteArrayPayload(new byte[] {}); + payload.getContentMetadata().setContentType("application/vnd.abiquo.racks+xml"); + + Multimap headers = LinkedHashMultimap. create(); + headers.put(HttpHeaders.ACCEPT, "application/vnd.abiquo.racks+xml;version=1.8.5"); + + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://foo")).headers(headers) + .payload(payload).build(); + + AppendApiVersionToMediaType filter = new AppendApiVersionToMediaType(new AppendApiVersionToAbiquoMimeType( + AbiquoAsyncApi.API_VERSION)); + + HttpRequest filtered = filter.filter(request); + + Collection accept = filtered.getHeaders().get(HttpHeaders.ACCEPT); + assertEquals(accept.size(), 1); + assertEquals(accept.iterator().next(), "application/vnd.abiquo.racks+xml;version=1.8.5"); + + assertEquals(filtered.getPayload().getContentMetadata().getContentType(), + "application/vnd.abiquo.racks+xml;version=" + AbiquoAsyncApi.API_VERSION); + } + + public void testFilterWithversionInContentType() { + Payload payload = Payloads.newByteArrayPayload(new byte[] {}); + payload.getContentMetadata().setContentType("application/vnd.abiquo.racks+xml;version=1.8.5"); + + Multimap headers = LinkedHashMultimap. create(); + headers.put(HttpHeaders.ACCEPT, "application/vnd.abiquo.racks+xml"); + + HttpRequest request = HttpRequest.builder().method("GET").endpoint(URI.create("http://foo")).headers(headers) + .payload(payload).build(); + + AppendApiVersionToMediaType filter = new AppendApiVersionToMediaType(new AppendApiVersionToAbiquoMimeType( + AbiquoAsyncApi.API_VERSION)); + + HttpRequest filtered = filter.filter(request); + + Collection accept = filtered.getHeaders().get(HttpHeaders.ACCEPT); + assertEquals(accept.size(), 1); + assertEquals(accept.iterator().next(), "application/vnd.abiquo.racks+xml;version=" + AbiquoAsyncApi.API_VERSION); + + assertEquals(filtered.getPayload().getContentMetadata().getContentType(), + "application/vnd.abiquo.racks+xml;version=1.8.5"); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/internal/AsyncMonitorTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/internal/AsyncMonitorTest.java new file mode 100644 index 0000000000..b765fd0375 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/internal/AsyncMonitorTest.java @@ -0,0 +1,476 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.internal; + +import static org.easymock.EasyMock.anyLong; +import static org.easymock.EasyMock.anyObject; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertTrue; + +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; + +import org.easymock.EasyMock; +import org.jclouds.abiquo.events.monitor.MonitorEvent; +import org.jclouds.abiquo.internal.BaseMonitoringService.AsyncMonitor; +import org.jclouds.abiquo.monitor.MonitorStatus; +import org.jclouds.rest.RestContext; +import org.testng.annotations.Test; + +import com.google.common.base.Function; +import com.google.common.eventbus.EventBus; +import com.google.common.eventbus.Subscribe; + +/** + * Unit tests for the {@link AsyncMonitor} class. + * + * @author Ignasi Barrera + */ +@Test(groups = "unit", testName = "AsyncMonitorTest") +public class AsyncMonitorTest { + @SuppressWarnings({ "rawtypes", "unchecked" }) + public void testStartMonitoringWithoutTimeout() { + ScheduledFuture mockFuture = EasyMock.createMock(ScheduledFuture.class); + ScheduledExecutorService schedulerMock = EasyMock.createMock(ScheduledExecutorService.class); + expect( + schedulerMock.scheduleWithFixedDelay(anyObject(Runnable.class), anyLong(), anyLong(), + anyObject(TimeUnit.class))).andReturn(mockFuture); + + replay(mockFuture); + replay(schedulerMock); + + AsyncMonitor monitor = mockMonitor(schedulerMock, new Object(), mockFunction(MonitorStatus.DONE), + new EventBus()); + + assertNull(monitor.getFuture()); + assertNull(monitor.getTimeout()); + + monitor.startMonitoring(null); + + assertNotNull(monitor.getFuture()); + assertNull(monitor.getTimeout()); + + verify(mockFuture); + verify(schedulerMock); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + public void testStartMonitoringWithTimeout() { + ScheduledFuture mockFuture = EasyMock.createMock(ScheduledFuture.class); + ScheduledExecutorService schedulerMock = EasyMock.createMock(ScheduledExecutorService.class); + expect( + schedulerMock.scheduleWithFixedDelay(anyObject(Runnable.class), anyLong(), anyLong(), + anyObject(TimeUnit.class))).andReturn(mockFuture); + + replay(mockFuture); + replay(schedulerMock); + + AsyncMonitor monitor = mockMonitor(schedulerMock, new Object(), mockFunction(MonitorStatus.DONE), + new EventBus()); + + assertNull(monitor.getFuture()); + assertNull(monitor.getTimeout()); + + monitor.startMonitoring(100L); + + assertNotNull(monitor.getFuture()); + assertNotNull(monitor.getTimeout()); + assertTrue(monitor.getTimeout() > 100L); + + verify(mockFuture); + verify(schedulerMock); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + public void testIsTimeoutWhenNullTimeout() { + ScheduledFuture mockFuture = EasyMock.createMock(ScheduledFuture.class); + ScheduledExecutorService schedulerMock = EasyMock.createMock(ScheduledExecutorService.class); + expect( + schedulerMock.scheduleWithFixedDelay(anyObject(Runnable.class), anyLong(), anyLong(), + anyObject(TimeUnit.class))).andReturn(mockFuture); + + replay(mockFuture); + replay(schedulerMock); + + AsyncMonitor monitor = mockMonitor(schedulerMock, new Object(), mockFunction(MonitorStatus.DONE), + new EventBus()); + + assertNull(monitor.getFuture()); + assertNull(monitor.getTimeout()); + + monitor.startMonitoring(null); + assertNotNull(monitor.getFuture()); + assertNull(monitor.getTimeout()); + assertFalse(monitor.isTimeout()); + + verify(mockFuture); + verify(schedulerMock); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + public void testIsTimeoutReturnsFalseWhenNotFinished() { + ScheduledFuture mockFuture = EasyMock.createMock(ScheduledFuture.class); + ScheduledExecutorService schedulerMock = EasyMock.createMock(ScheduledExecutorService.class); + expect( + schedulerMock.scheduleWithFixedDelay(anyObject(Runnable.class), anyLong(), anyLong(), + anyObject(TimeUnit.class))).andReturn(mockFuture); + + replay(mockFuture); + replay(schedulerMock); + + AsyncMonitor monitor = mockMonitor(schedulerMock, new Object(), mockFunction(MonitorStatus.DONE), + new EventBus()); + + assertNull(monitor.getFuture()); + assertNull(monitor.getTimeout()); + + monitor.startMonitoring(60000L); + assertNotNull(monitor.getFuture()); + assertNotNull(monitor.getTimeout()); + assertFalse(monitor.isTimeout()); + + verify(mockFuture); + verify(schedulerMock); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + public void testIsTimeoutReturnsTrueWhenFinished() throws InterruptedException { + ScheduledFuture mockFuture = EasyMock.createMock(ScheduledFuture.class); + ScheduledExecutorService schedulerMock = EasyMock.createMock(ScheduledExecutorService.class); + expect( + schedulerMock.scheduleWithFixedDelay(anyObject(Runnable.class), anyLong(), anyLong(), + anyObject(TimeUnit.class))).andReturn(mockFuture); + + replay(mockFuture); + replay(schedulerMock); + + AsyncMonitor monitor = mockMonitor(schedulerMock, new Object(), mockFunction(MonitorStatus.DONE), + new EventBus()); + + assertNull(monitor.getFuture()); + assertNull(monitor.getTimeout()); + + monitor.startMonitoring(1L); + Thread.sleep(2L); + assertNotNull(monitor.getFuture()); + assertNotNull(monitor.getTimeout()); + assertTrue(monitor.isTimeout()); + + verify(mockFuture); + verify(schedulerMock); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + public void testStopMonitoringWhenFutureIsCancelled() { + ScheduledFuture mockFuture = EasyMock.createMock(ScheduledFuture.class); + expect(mockFuture.isCancelled()).andReturn(true); + + ScheduledExecutorService schedulerMock = EasyMock.createMock(ScheduledExecutorService.class); + expect( + schedulerMock.scheduleWithFixedDelay(anyObject(Runnable.class), anyLong(), anyLong(), + anyObject(TimeUnit.class))).andReturn(mockFuture); + + replay(mockFuture); + replay(schedulerMock); + + AsyncMonitor monitor = mockMonitor(schedulerMock, new Object(), mockFunction(MonitorStatus.DONE), + new EventBus()); + + assertNull(monitor.getFuture()); + assertNull(monitor.getTimeout()); + + monitor.startMonitoring(null); + assertNotNull(monitor.getFuture()); + assertNull(monitor.getTimeout()); + + monitor.stopMonitoring(); + + verify(mockFuture); + verify(schedulerMock); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + public void testStopMonitoringWhenFutureIsDone() { + ScheduledFuture mockFuture = EasyMock.createMock(ScheduledFuture.class); + expect(mockFuture.isCancelled()).andReturn(false); + expect(mockFuture.isDone()).andReturn(true); + + ScheduledExecutorService schedulerMock = EasyMock.createMock(ScheduledExecutorService.class); + expect( + schedulerMock.scheduleWithFixedDelay(anyObject(Runnable.class), anyLong(), anyLong(), + anyObject(TimeUnit.class))).andReturn(mockFuture); + + replay(mockFuture); + replay(schedulerMock); + + AsyncMonitor monitor = mockMonitor(schedulerMock, new Object(), mockFunction(MonitorStatus.DONE), + new EventBus()); + + assertNull(monitor.getFuture()); + assertNull(monitor.getTimeout()); + + monitor.startMonitoring(null); + assertNotNull(monitor.getFuture()); + assertNull(monitor.getTimeout()); + + monitor.stopMonitoring(); + + verify(mockFuture); + verify(schedulerMock); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + public void testStopMonitoringWhenFutureIsNotComplete() { + ScheduledFuture mockFuture = EasyMock.createMock(ScheduledFuture.class); + expect(mockFuture.isCancelled()).andReturn(false); + expect(mockFuture.isDone()).andReturn(false); + expect(mockFuture.cancel(false)).andReturn(true); + + ScheduledExecutorService schedulerMock = EasyMock.createMock(ScheduledExecutorService.class); + expect( + schedulerMock.scheduleWithFixedDelay(anyObject(Runnable.class), anyLong(), anyLong(), + anyObject(TimeUnit.class))).andReturn(mockFuture); + + replay(mockFuture); + replay(schedulerMock); + + AsyncMonitor monitor = mockMonitor(schedulerMock, new Object(), mockFunction(MonitorStatus.DONE), + new EventBus()); + + assertNull(monitor.getFuture()); + assertNull(monitor.getTimeout()); + + monitor.startMonitoring(null); + assertNotNull(monitor.getFuture()); + assertNull(monitor.getTimeout()); + + monitor.stopMonitoring(); + + verify(mockFuture); + verify(schedulerMock); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + public void testMonitorAndDone() { + ScheduledFuture mockFuture = EasyMock.createMock(ScheduledFuture.class); + expect(mockFuture.isCancelled()).andReturn(true); + + ScheduledExecutorService schedulerMock = EasyMock.createMock(ScheduledExecutorService.class); + expect( + schedulerMock.scheduleWithFixedDelay(anyObject(Runnable.class), anyLong(), anyLong(), + anyObject(TimeUnit.class))).andReturn(mockFuture); + + replay(mockFuture); + replay(schedulerMock); + + CoutingEventHandler handler = new CoutingEventHandler(); + EventBus eventBus = new EventBus(); + eventBus.register(handler); + + AsyncMonitor monitor = mockMonitor(schedulerMock, new Object(), mockFunction(MonitorStatus.DONE), + eventBus); + + assertNull(monitor.getFuture()); + assertNull(monitor.getTimeout()); + + monitor.startMonitoring(null); + assertNotNull(monitor.getFuture()); + assertNull(monitor.getTimeout()); + + monitor.run(); + assertEquals(handler.numCompletes, 1); + assertEquals(handler.numFailures, 0); + assertEquals(handler.numTimeouts, 0); + + verify(mockFuture); + verify(schedulerMock); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + public void testMonitorAndFail() { + ScheduledFuture mockFuture = EasyMock.createMock(ScheduledFuture.class); + expect(mockFuture.isCancelled()).andReturn(true); + + ScheduledExecutorService schedulerMock = EasyMock.createMock(ScheduledExecutorService.class); + expect( + schedulerMock.scheduleWithFixedDelay(anyObject(Runnable.class), anyLong(), anyLong(), + anyObject(TimeUnit.class))).andReturn(mockFuture); + + replay(mockFuture); + replay(schedulerMock); + + CoutingEventHandler handler = new CoutingEventHandler(); + EventBus eventBus = new EventBus(); + eventBus.register(handler); + + AsyncMonitor monitor = mockMonitor(schedulerMock, new Object(), mockFunction(MonitorStatus.FAILED), + eventBus); + + assertNull(monitor.getFuture()); + assertNull(monitor.getTimeout()); + + monitor.startMonitoring(null); + assertNotNull(monitor.getFuture()); + assertNull(monitor.getTimeout()); + + monitor.run(); + assertEquals(handler.numCompletes, 0); + assertEquals(handler.numFailures, 1); + assertEquals(handler.numTimeouts, 0); + + verify(mockFuture); + verify(schedulerMock); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + public void testMonitorAndContinueWithoutTimeout() { + ScheduledFuture mockFuture = EasyMock.createMock(ScheduledFuture.class); + ScheduledExecutorService schedulerMock = EasyMock.createMock(ScheduledExecutorService.class); + expect( + schedulerMock.scheduleWithFixedDelay(anyObject(Runnable.class), anyLong(), anyLong(), + anyObject(TimeUnit.class))).andReturn(mockFuture); + + replay(mockFuture); + replay(schedulerMock); + + CoutingEventHandler handler = new CoutingEventHandler(); + EventBus eventBus = new EventBus(); + eventBus.register(handler); + + AsyncMonitor monitor = mockMonitor(schedulerMock, new Object(), mockFunction(MonitorStatus.CONTINUE), + eventBus); + + assertNull(monitor.getFuture()); + assertNull(monitor.getTimeout()); + + monitor.startMonitoring(null); + assertNotNull(monitor.getFuture()); + assertNull(monitor.getTimeout()); + + monitor.run(); + assertEquals(handler.numCompletes, 0); + assertEquals(handler.numFailures, 0); + assertEquals(handler.numTimeouts, 0); + + verify(mockFuture); + verify(schedulerMock); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + public void testMonitorAndContinueWithtTimeout() throws InterruptedException { + ScheduledFuture mockFuture = EasyMock.createMock(ScheduledFuture.class); + expect(mockFuture.isCancelled()).andReturn(true); + + ScheduledExecutorService schedulerMock = EasyMock.createMock(ScheduledExecutorService.class); + expect( + schedulerMock.scheduleWithFixedDelay(anyObject(Runnable.class), anyLong(), anyLong(), + anyObject(TimeUnit.class))).andReturn(mockFuture); + + replay(mockFuture); + replay(schedulerMock); + + CoutingEventHandler handler = new CoutingEventHandler(); + EventBus eventBus = new EventBus(); + eventBus.register(handler); + + AsyncMonitor monitor = mockMonitor(schedulerMock, new Object(), mockFunction(MonitorStatus.CONTINUE), + eventBus); + + assertNull(monitor.getFuture()); + assertNull(monitor.getTimeout()); + + monitor.startMonitoring(1L); + assertNotNull(monitor.getFuture()); + assertNotNull(monitor.getTimeout()); + + Thread.sleep(2L); + monitor.run(); + assertEquals(handler.numCompletes, 0); + assertEquals(handler.numFailures, 0); + assertEquals(handler.numTimeouts, 1); + + verify(mockFuture); + verify(schedulerMock); + } + + @Test(expectedExceptions = NullPointerException.class) + public void testCreateMonitorWithNullObject() { + mockMonitor(null, null, new Function() { + @Override + public MonitorStatus apply(final Object input) { + return MonitorStatus.DONE; + } + }, new EventBus()); + } + + @Test(expectedExceptions = NullPointerException.class) + public void testCreateMonitorWithNullFunction() { + mockMonitor(null, new Object(), null, new EventBus()); + } + + @SuppressWarnings("unchecked") + private AsyncMonitor mockMonitor(final ScheduledExecutorService scheduler, final Object object, + final Function function, final EventBus eventBus) { + BaseMonitoringService monitorService = new BaseMonitoringService(EasyMock.createMock(RestContext.class), + scheduler, 100L, eventBus); + + return monitorService.new AsyncMonitor(object, function); + } + + private Function mockFunction(final MonitorStatus status) { + return new Function() { + @Override + public MonitorStatus apply(final Object input) { + return status; + } + }; + } + + private static class CoutingEventHandler { + public int numCompletes = 0; + + public int numFailures = 0; + + public int numTimeouts = 0; + + @Subscribe + @SuppressWarnings("unused") + public void handle(final MonitorEvent event) { + switch (event.getType()) { + case COMPLETED: + numCompletes++; + break; + case FAILED: + numFailures++; + break; + case TIMEOUT: + numTimeouts++; + break; + } + } + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/internal/BaseAbiquoApiLiveApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/internal/BaseAbiquoApiLiveApiTest.java new file mode 100644 index 0000000000..f79211a759 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/internal/BaseAbiquoApiLiveApiTest.java @@ -0,0 +1,89 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.internal; + +import org.jclouds.abiquo.environment.CloudTestEnvironment; +import org.testng.annotations.AfterSuite; +import org.testng.annotations.BeforeSuite; +import org.testng.annotations.Test; + +/** + * Base class for live and domain tests. + * + * @author Ignasi Barrera + */ +@Test(groups = "api", testName = "BaseAbiquoApiLiveApiTest", singleThreaded = true) +public abstract class BaseAbiquoApiLiveApiTest extends BaseAbiquoLiveApiTest { + /** The test environment. */ + protected static CloudTestEnvironment env; + + @Override + @BeforeSuite(groups = "api") + public void setupContext() { + super.setupContext(); + setupEnvironment(); + } + + // @BeforeSuite(groups = "ucs", dependsOnMethods = "setupContext") + protected void setupUcsEnvironment() throws Exception { + if (env != null) { + env.createUcsRack(); + } + } + + @Override + @AfterSuite(groups = "api") + protected void tearDownContext() { + try { + tearDownEnvironment(); + } finally { + // Make sure we close the context + super.tearDownContext(); + } + } + + protected void setupEnvironment() { + if (env == null) { + try { + env = new CloudTestEnvironment(view); + env.setup(); + } catch (Exception ex) { + super.tearDownContext(); // Make sure we close the context setup + // fails + throw new RuntimeException("Could not create environment", ex); + } + } + } + + protected void tearDownEnvironment() { + if (env != null) { + try { + env.tearDown(); + + // Wait a bit before closing context, to avoid executor shutdown + // while + // there are still open threads + Thread.sleep(1000L); + } catch (Exception ex) { + throw new RuntimeException("Could not tear down environment", ex); + } + } + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/internal/BaseAbiquoLiveApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/internal/BaseAbiquoLiveApiTest.java new file mode 100644 index 0000000000..62c7fe3c49 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/internal/BaseAbiquoLiveApiTest.java @@ -0,0 +1,67 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.internal; + +import java.util.Properties; + +import org.jclouds.Constants; +import org.jclouds.abiquo.AbiquoContext; +import org.jclouds.apis.BaseViewLiveTest; +import org.jclouds.logging.config.LoggingModule; +import org.jclouds.logging.slf4j.config.SLF4JLoggingModule; + +import com.google.common.reflect.TypeToken; + +/** + * Base class for Abiquo live tests. + * + * @author Ignasi Barrera + */ +public abstract class BaseAbiquoLiveApiTest extends BaseViewLiveTest { + public BaseAbiquoLiveApiTest() { + provider = "abiquo"; + } + + @Override + protected Properties setupProperties() { + Properties overrides = super.setupProperties(); + overrides.put(Constants.PROPERTY_MAX_RETRIES, "0"); + overrides.put(Constants.PROPERTY_MAX_REDIRECTS, "0"); + // Wait at most one minute in Machine discovery + overrides.put("jclouds.timeouts.InfrastructureApi.discoverSingleMachine", "60000"); + overrides.put("jclouds.timeouts.InfrastructureApi.discoverMultipleMachines", "60000"); + overrides.put("jclouds.timeouts.InfrastructureApi.createMachine", "60000"); + overrides.put("jclouds.timeouts.InfrastructureApi.updateMachine", "60000"); + overrides.put("jclouds.timeouts.InfrastructureApi.checkMachineState", "60000"); + overrides.put("jclouds.timeouts.CloudApi.listVirtualMachines", "60000"); + return overrides; + } + + @Override + protected LoggingModule getLoggingModule() { + return new SLF4JLoggingModule(); + } + + @Override + protected TypeToken viewType() { + return TypeToken.of(AbiquoContext.class); + } + +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/internal/BaseAdministrationServiceTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/internal/BaseAdministrationServiceTest.java new file mode 100644 index 0000000000..4a2b2122bc --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/internal/BaseAdministrationServiceTest.java @@ -0,0 +1,48 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.internal; + +import static org.testng.Assert.assertNotNull; + +import org.jclouds.abiquo.features.services.AdministrationService; +import org.testng.annotations.Test; + +/** + * Unit tests for the {@link BaseAdministrationService} class. + * + * @author Ignasi Barrera + */ +@Test(groups = "unit", testName = "BaseAdministrationServiceTest") +public class BaseAdministrationServiceTest extends BaseInjectionTest { + + public void testAllPropertiesInjected() { + BaseAdministrationService service = (BaseAdministrationService) injector.getInstance(AdministrationService.class); + + assertNotNull(service.context); + assertNotNull(service.listDatacenters); + assertNotNull(service.listMachines); + assertNotNull(service.listEnterprises); + assertNotNull(service.listLicenses); + assertNotNull(service.listPrivileges); + assertNotNull(service.listRoles); + assertNotNull(service.currentUser); + assertNotNull(service.currentEnterprise); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/internal/BaseCloudServiceTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/internal/BaseCloudServiceTest.java new file mode 100644 index 0000000000..c1e49628d1 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/internal/BaseCloudServiceTest.java @@ -0,0 +1,43 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.internal; + +import static org.testng.Assert.assertNotNull; + +import org.jclouds.abiquo.features.services.CloudService; +import org.testng.annotations.Test; + +/** + * Unit tests for the {@link BaseCloudService} class. + * + * @author Ignasi Barrera + */ +@Test(groups = "unit", testName = "BaseCloudServiceTest") +public class BaseCloudServiceTest extends BaseInjectionTest { + + public void testAllPropertiesInjected() { + BaseCloudService service = (BaseCloudService) injector.getInstance(CloudService.class); + + assertNotNull(service.context); + assertNotNull(service.listVirtualDatacenters); + assertNotNull(service.listVirtualAppliances); + assertNotNull(service.listVirtualMachines); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/internal/BaseEventServiceTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/internal/BaseEventServiceTest.java new file mode 100644 index 0000000000..137c88194b --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/internal/BaseEventServiceTest.java @@ -0,0 +1,40 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.internal; + +import static org.testng.Assert.assertNotNull; + +import org.jclouds.abiquo.features.services.EventService; +import org.testng.annotations.Test; + +/** + * Unit tests for the {@link BaseEventService} class. + * + * @author Vivien Mahé + */ +@Test(groups = "unit", testName = "BaseEventServiceTest") +public class BaseEventServiceTest extends BaseInjectionTest { + public void testAllPropertiesInjected() { + BaseEventService service = (BaseEventService) injector.getInstance(EventService.class); + + assertNotNull(service.context); + assertNotNull(service.listEvents); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/internal/BaseInjectionTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/internal/BaseInjectionTest.java new file mode 100644 index 0000000000..23bad0ed4a --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/internal/BaseInjectionTest.java @@ -0,0 +1,66 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.internal; + +import java.util.Properties; + +import org.jclouds.ContextBuilder; +import org.jclouds.abiquo.AbiquoApiMetadata; +import org.jclouds.abiquo.AbiquoContext; +import org.jclouds.lifecycle.Closer; +import org.jclouds.logging.config.NullLoggingModule; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableSet; +import com.google.inject.Injector; +import com.google.inject.Module; + +/** + * Unit tests for the {@link BaseCloudService} class. + * + * @author Ignasi Barrera + */ +@Test(groups = "unit", testName = "BaseEventServiceTest") +public class BaseInjectionTest { + protected Injector injector; + + @BeforeClass + public void setup() { + injector = ContextBuilder.newBuilder(new AbiquoApiMetadata()) // + .credentials("identity", "credential") // + .modules(ImmutableSet. of(new NullLoggingModule())) // + .overrides(buildProperties()) // + .build(AbiquoContext.class).getUtils().getInjector(); + } + + protected Properties buildProperties() { + return new Properties(); + } + + @AfterClass + public void tearDown() throws Exception { + if (injector != null) { + injector.getInstance(Closer.class).close(); + } + } + +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/internal/BaseMonitoringServiceTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/internal/BaseMonitoringServiceTest.java new file mode 100644 index 0000000000..075894805e --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/internal/BaseMonitoringServiceTest.java @@ -0,0 +1,95 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.internal; + +import static org.testng.Assert.assertNotNull; + +import org.jclouds.abiquo.features.services.MonitoringService; +import org.jclouds.abiquo.monitor.MonitorStatus; +import org.testng.annotations.Test; + +import com.google.common.base.Function; + +/** + * Unit tests for the {@link BaseMonitoringService} class. + * + * @author Ignasi Barrera + */ +@Test(groups = "unit", testName = "BaseMonitoringServiceTest") +public class BaseMonitoringServiceTest extends BaseInjectionTest { + public void testAllPropertiesInjected() { + BaseMonitoringService service = (BaseMonitoringService) injector.getInstance(MonitoringService.class); + + assertNotNull(service.context); + assertNotNull(service.scheduler); + assertNotNull(service.pollingDelay); + assertNotNull(service.eventBus); + } + + @Test(expectedExceptions = NullPointerException.class) + public void testAwaitCompletionWithNullFunction() { + monitoringService().awaitCompletion(null, new Object[] {}); + } + + public void testAwaitCompletionWithoutTasks() { + BaseMonitoringService service = monitoringService(); + + service.awaitCompletion(new MockMonitor()); + service.awaitCompletion(new MockMonitor(), (Object[]) null); + service.awaitCompletion(new MockMonitor(), new Object[] {}); + } + + @Test(expectedExceptions = NullPointerException.class) + public void testMonitorWithNullCompleteCondition() { + monitoringService().monitor(null, (Object[]) null); + } + + public void testMonitorWithoutTasks() { + monitoringService().monitor(new MockMonitor()); + } + + public void testDelegateToVirtualMachineMonitor() { + assertNotNull(monitoringService().getVirtualMachineMonitor()); + } + + public void testDelegateToVirtualApplianceMonitor() { + assertNotNull(monitoringService().getVirtualApplianceMonitor()); + } + + public void testDelegateToAsyncTaskMonitor() { + assertNotNull(monitoringService().getAsyncTaskMonitor()); + } + + public void testDelegateToConversioMonitor() { + assertNotNull(monitoringService().getConversionMonitor()); + } + + private BaseMonitoringService monitoringService() { + return injector.getInstance(BaseMonitoringService.class); + } + + private static class MockMonitor implements Function { + @Override + public MonitorStatus apply(final Object object) { + return MonitorStatus.DONE; + } + } + +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/internal/BaseSearchServiceTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/internal/BaseSearchServiceTest.java new file mode 100644 index 0000000000..27f9e15edc --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/internal/BaseSearchServiceTest.java @@ -0,0 +1,40 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.internal; + +import static org.testng.Assert.assertNotNull; + +import org.jclouds.abiquo.features.services.SearchService; +import org.testng.annotations.Test; + +/** + * Unit tests for the {@link BaseSearchService} class. + * + * @author Ignasi Barrera + */ +@Test(groups = "unit", testName = "BaseSearchServiceTest") +public class BaseSearchServiceTest extends BaseInjectionTest { + + public void testAllPropertiesInjected() { + BaseSearchService service = (BaseSearchService) injector.getInstance(SearchService.class); + + assertNotNull(service.context); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/monitor/functions/AsyncTaskStatusMonitorTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/monitor/functions/AsyncTaskStatusMonitorTest.java new file mode 100644 index 0000000000..90352de997 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/monitor/functions/AsyncTaskStatusMonitorTest.java @@ -0,0 +1,100 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.monitor.functions; + +import static org.testng.Assert.assertEquals; + +import org.easymock.EasyMock; +import org.jclouds.abiquo.domain.task.AsyncTask; +import org.jclouds.abiquo.monitor.MonitorStatus; +import org.jclouds.rest.RestContext; +import org.testng.annotations.Test; + +import com.abiquo.server.core.task.TaskDto; +import com.abiquo.server.core.task.enums.TaskState; +import com.google.common.base.Function; + +/** + * Unit tests for the {@link AsyncTaskStatusMonitor} function. + * + * @author Serafin Sedano + */ +@Test(groups = "unit", testName = "AsyncTaskStatusMonitorTest") +public class AsyncTaskStatusMonitorTest { + + @Test(expectedExceptions = NullPointerException.class) + public void testInvalidNullArgument() { + Function function = new AsyncTaskStatusMonitor(); + function.apply(null); + } + + public void testReturnDone() { + TaskState[] states = { TaskState.FINISHED_SUCCESSFULLY }; + + checkStatesReturn(new MockAsyncTask(), new AsyncTaskStatusMonitor(), states, MonitorStatus.DONE); + } + + public void testReturnFail() { + TaskState[] states = { TaskState.ABORTED, TaskState.FINISHED_UNSUCCESSFULLY }; + + checkStatesReturn(new MockAsyncTask(), new AsyncTaskStatusMonitor(), states, MonitorStatus.FAILED); + } + + public void testReturnContinue() { + TaskState[] states = { TaskState.STARTED, TaskState.PENDING }; + + checkStatesReturn(new MockAsyncTask(), new AsyncTaskStatusMonitor(), states, MonitorStatus.CONTINUE); + + checkStatesReturn(new MockAsyncTaskFailing(), new AsyncTaskStatusMonitor(), states, MonitorStatus.CONTINUE); + } + + private void checkStatesReturn(final MockAsyncTask task, final Function function, + final TaskState[] states, final MonitorStatus expectedStatus) { + for (TaskState state : states) { + task.setState(state); + assertEquals(function.apply(task), expectedStatus); + } + } + + private static class MockAsyncTask extends AsyncTask { + @SuppressWarnings("unchecked") + public MockAsyncTask() { + super(EasyMock.createMock(RestContext.class), new TaskDto()); + } + + @Override + public void refresh() { + // Do not perform any API call + } + + public void setState(final TaskState state) { + target.setState(state); + } + } + + private static class MockAsyncTaskFailing extends MockAsyncTask { + @Override + public void refresh() { + throw new RuntimeException("This mock class always fails to refresh"); + } + + } + +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/monitor/functions/ConversionStatusMonitorTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/monitor/functions/ConversionStatusMonitorTest.java new file mode 100644 index 0000000000..40007eef2d --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/monitor/functions/ConversionStatusMonitorTest.java @@ -0,0 +1,100 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.monitor.functions; + +import static org.testng.Assert.assertEquals; + +import org.easymock.EasyMock; +import org.jclouds.abiquo.domain.cloud.Conversion; +import org.jclouds.abiquo.monitor.MonitorStatus; +import org.jclouds.rest.RestContext; +import org.testng.annotations.Test; + +import com.abiquo.model.enumerator.ConversionState; +import com.abiquo.server.core.appslibrary.ConversionDto; +import com.google.common.base.Function; + +/** + * Unit tests for the {@link ConversionStatusMonitor} function. + * + * @author Sergi Castro + */ +@Test(groups = "unit", testName = "ConversionStatusMonitorTest") +public class ConversionStatusMonitorTest { + + @Test(expectedExceptions = NullPointerException.class) + public void testInvalidNullArgument() { + Function function = new ConversionStatusMonitor(); + function.apply(null); + } + + public void testReturnDone() { + ConversionState[] states = { ConversionState.FINISHED }; + + checkStatesReturn(new MockConversion(), new ConversionStatusMonitor(), states, MonitorStatus.DONE); + } + + public void testReturnFail() { + ConversionState[] states = { ConversionState.FAILED }; + + checkStatesReturn(new MockConversion(), new ConversionStatusMonitor(), states, MonitorStatus.FAILED); + } + + public void testReturnContinue() { + ConversionState[] states = { ConversionState.ENQUEUED }; + + checkStatesReturn(new MockConversion(), new ConversionStatusMonitor(), states, MonitorStatus.CONTINUE); + + checkStatesReturn(new MockConversionFailing(), new ConversionStatusMonitor(), states, MonitorStatus.CONTINUE); + } + + private void checkStatesReturn(final MockConversion task, final Function function, + final ConversionState[] states, final MonitorStatus expectedStatus) { + for (ConversionState state : states) { + task.setState(state); + assertEquals(function.apply(task), expectedStatus); + } + } + + private static class MockConversion extends Conversion { + @SuppressWarnings("unchecked") + public MockConversion() { + super(EasyMock.createMock(RestContext.class), new ConversionDto()); + } + + @Override + public void refresh() { + // Do not perform any API call + } + + public void setState(final ConversionState state) { + target.setState(state); + } + } + + private static class MockConversionFailing extends MockConversion { + @Override + public void refresh() { + throw new RuntimeException("This mock class always fails to refresh"); + } + + } + +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/monitor/functions/VirtualApplianceDeployMonitorTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/monitor/functions/VirtualApplianceDeployMonitorTest.java new file mode 100644 index 0000000000..31c2831304 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/monitor/functions/VirtualApplianceDeployMonitorTest.java @@ -0,0 +1,104 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.monitor.functions; + +import static org.testng.Assert.assertEquals; + +import org.easymock.EasyMock; +import org.jclouds.abiquo.domain.cloud.VirtualAppliance; +import org.jclouds.abiquo.monitor.MonitorStatus; +import org.jclouds.rest.RestContext; +import org.testng.annotations.Test; + +import com.abiquo.server.core.cloud.VirtualApplianceDto; +import com.abiquo.server.core.cloud.VirtualApplianceState; +import com.google.common.base.Function; + +/** + * Unit tests for the {@link VirtualApplianceDeployMonitor} function. + * + * @author Serafin Sedano + */ +@Test(groups = "unit", testName = "VirtualApplianceDeployMonitorTest") +public class VirtualApplianceDeployMonitorTest { + + @Test(expectedExceptions = NullPointerException.class) + public void testInvalidNullArgument() { + Function function = new VirtualApplianceDeployMonitor(); + function.apply(null); + } + + public void testReturnDone() { + VirtualApplianceState[] states = { VirtualApplianceState.DEPLOYED }; + + checkStatesReturn(new MockVirtualAppliance(), new VirtualApplianceDeployMonitor(), states, MonitorStatus.DONE); + } + + public void testReturnFail() { + VirtualApplianceState[] states = { VirtualApplianceState.NEEDS_SYNC, VirtualApplianceState.UNKNOWN, + VirtualApplianceState.NOT_DEPLOYED }; + + checkStatesReturn(new MockVirtualAppliance(), new VirtualApplianceDeployMonitor(), states, MonitorStatus.FAILED); + } + + public void testReturnContinue() { + VirtualApplianceState[] states = { VirtualApplianceState.LOCKED }; + + checkStatesReturn(new MockVirtualAppliance(), new VirtualApplianceDeployMonitor(), states, MonitorStatus.CONTINUE); + + checkStatesReturn(new MockVirtualApplianceFailing(), new VirtualApplianceDeployMonitor(), states, + MonitorStatus.CONTINUE); + } + + private void checkStatesReturn(final MockVirtualAppliance vapp, + final Function function, final VirtualApplianceState[] states, + final MonitorStatus expectedStatus) { + for (VirtualApplianceState state : states) { + vapp.setState(state); + assertEquals(function.apply(vapp), expectedStatus); + } + } + + private static class MockVirtualAppliance extends VirtualAppliance { + private VirtualApplianceState state; + + @SuppressWarnings("unchecked") + public MockVirtualAppliance() { + super(EasyMock.createMock(RestContext.class), new VirtualApplianceDto()); + } + + @Override + public VirtualApplianceState getState() { + return state; + } + + public void setState(final VirtualApplianceState state) { + this.state = state; + } + } + + private static class MockVirtualApplianceFailing extends MockVirtualAppliance { + @Override + public VirtualApplianceState getState() { + throw new RuntimeException("This mock class always fails to get the state"); + } + + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/monitor/functions/VirtualApplianceUndeployMonitorTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/monitor/functions/VirtualApplianceUndeployMonitorTest.java new file mode 100644 index 0000000000..c2b9b3ce8d --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/monitor/functions/VirtualApplianceUndeployMonitorTest.java @@ -0,0 +1,105 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.monitor.functions; + +import static org.testng.Assert.assertEquals; + +import org.easymock.EasyMock; +import org.jclouds.abiquo.domain.cloud.VirtualAppliance; +import org.jclouds.abiquo.monitor.MonitorStatus; +import org.jclouds.rest.RestContext; +import org.testng.annotations.Test; + +import com.abiquo.server.core.cloud.VirtualApplianceDto; +import com.abiquo.server.core.cloud.VirtualApplianceState; +import com.google.common.base.Function; + +/** + * Unit tests for the {@link VirtualApplianceUndeployMonitor} function. + * + * @author Serafin Sedano + */ +@Test(groups = "unit", testName = "VirtualApplianceUndeployMonitorTest") +public class VirtualApplianceUndeployMonitorTest { + + @Test(expectedExceptions = NullPointerException.class) + public void testInvalidNullArgument() { + Function function = new VirtualApplianceUndeployMonitor(); + function.apply(null); + } + + public void testReturnDone() { + VirtualApplianceState[] states = { VirtualApplianceState.NOT_DEPLOYED }; + + checkStatesReturn(new MockVirtualAppliance(), new VirtualApplianceUndeployMonitor(), states, MonitorStatus.DONE); + } + + public void testReturnFail() { + VirtualApplianceState[] states = { VirtualApplianceState.DEPLOYED, VirtualApplianceState.NEEDS_SYNC, + VirtualApplianceState.UNKNOWN }; + + checkStatesReturn(new MockVirtualAppliance(), new VirtualApplianceUndeployMonitor(), states, MonitorStatus.FAILED); + } + + public void testReturnContinue() { + VirtualApplianceState[] states = { VirtualApplianceState.LOCKED }; + + checkStatesReturn(new MockVirtualAppliance(), new VirtualApplianceUndeployMonitor(), states, + MonitorStatus.CONTINUE); + + checkStatesReturn(new MockVirtualApplianceFailing(), new VirtualApplianceUndeployMonitor(), states, + MonitorStatus.CONTINUE); + } + + private void checkStatesReturn(final MockVirtualAppliance vapp, + final Function function, final VirtualApplianceState[] states, + final MonitorStatus expectedStatus) { + for (VirtualApplianceState state : states) { + vapp.setState(state); + assertEquals(function.apply(vapp), expectedStatus); + } + } + + private static class MockVirtualAppliance extends VirtualAppliance { + private VirtualApplianceState state; + + @SuppressWarnings("unchecked") + public MockVirtualAppliance() { + super(EasyMock.createMock(RestContext.class), new VirtualApplianceDto()); + } + + @Override + public VirtualApplianceState getState() { + return state; + } + + public void setState(final VirtualApplianceState state) { + this.state = state; + } + } + + private static class MockVirtualApplianceFailing extends MockVirtualAppliance { + @Override + public VirtualApplianceState getState() { + throw new RuntimeException("This mock class always fails to get the state"); + } + + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/monitor/functions/VirtualMachineDeployMonitorTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/monitor/functions/VirtualMachineDeployMonitorTest.java new file mode 100644 index 0000000000..566e91bc13 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/monitor/functions/VirtualMachineDeployMonitorTest.java @@ -0,0 +1,102 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.monitor.functions; + +import static org.testng.Assert.assertEquals; + +import org.easymock.EasyMock; +import org.jclouds.abiquo.domain.cloud.VirtualMachine; +import org.jclouds.abiquo.monitor.MonitorStatus; +import org.jclouds.rest.RestContext; +import org.testng.annotations.Test; + +import com.abiquo.server.core.cloud.VirtualMachineState; +import com.abiquo.server.core.cloud.VirtualMachineWithNodeExtendedDto; +import com.google.common.base.Function; + +/** + * Unit tests for the {@link VirtualMachineDeployMonitor} function. + * + * @author Ignasi Barrera + */ +@Test(groups = "unit", testName = "VirtualMachineDeployMonitorTest") +public class VirtualMachineDeployMonitorTest { + @Test(expectedExceptions = NullPointerException.class) + public void testInvalidNullArgument() { + Function function = new VirtualMachineDeployMonitor(); + function.apply(null); + } + + public void testReturnDone() { + VirtualMachineState[] states = { VirtualMachineState.ON }; + + checkStatesReturn(new MockVirtualMachine(), new VirtualMachineDeployMonitor(), states, MonitorStatus.DONE); + } + + public void testReturnFail() { + VirtualMachineState[] states = { VirtualMachineState.NOT_ALLOCATED, VirtualMachineState.UNKNOWN }; + + checkStatesReturn(new MockVirtualMachine(), new VirtualMachineDeployMonitor(), states, MonitorStatus.FAILED); + } + + public void testReturnContinue() { + VirtualMachineState[] states = { VirtualMachineState.ALLOCATED, VirtualMachineState.CONFIGURED, + VirtualMachineState.LOCKED, VirtualMachineState.OFF, VirtualMachineState.PAUSED }; + + checkStatesReturn(new MockVirtualMachine(), new VirtualMachineDeployMonitor(), states, MonitorStatus.CONTINUE); + + checkStatesReturn(new MockVirtualMachineFailing(), new VirtualMachineDeployMonitor(), states, + MonitorStatus.CONTINUE); + } + + private void checkStatesReturn(final MockVirtualMachine vm, final Function function, + final VirtualMachineState[] states, final MonitorStatus expectedStatus) { + for (VirtualMachineState state : states) { + vm.setState(state); + assertEquals(function.apply(vm), expectedStatus); + } + } + + private static class MockVirtualMachine extends VirtualMachine { + private VirtualMachineState state; + + @SuppressWarnings("unchecked") + public MockVirtualMachine() { + super(EasyMock.createMock(RestContext.class), new VirtualMachineWithNodeExtendedDto()); + } + + @Override + public VirtualMachineState getState() { + return state; + } + + public void setState(final VirtualMachineState state) { + this.state = state; + } + } + + private static class MockVirtualMachineFailing extends MockVirtualMachine { + @Override + public VirtualMachineState getState() { + throw new RuntimeException("This mock class always fails to get the state"); + } + + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/monitor/functions/VirtualMachineStateMonitorTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/monitor/functions/VirtualMachineStateMonitorTest.java new file mode 100644 index 0000000000..fdc7e294b6 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/monitor/functions/VirtualMachineStateMonitorTest.java @@ -0,0 +1,104 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.monitor.functions; + +import static org.testng.Assert.assertEquals; + +import org.easymock.EasyMock; +import org.jclouds.abiquo.domain.cloud.VirtualMachine; +import org.jclouds.abiquo.monitor.MonitorStatus; +import org.jclouds.rest.RestContext; +import org.testng.annotations.Test; + +import com.abiquo.server.core.cloud.VirtualMachineState; +import com.abiquo.server.core.cloud.VirtualMachineWithNodeExtendedDto; +import com.google.common.base.Function; + +/** + * Unit tests for the {@link VirtualMachineStateMonitor} function. + * + * @author Ignasi Barrera + */ +@Test(groups = "unit", testName = "VirtualMachineStateMonitorTest") +public class VirtualMachineStateMonitorTest { + @Test(expectedExceptions = NullPointerException.class) + public void testInvalidNullState() { + new VirtualMachineStateMonitor(null); + } + + @Test(expectedExceptions = NullPointerException.class) + public void testInvalidNullArgument() { + Function function = new VirtualMachineStateMonitor(VirtualMachineState.ON); + function.apply(null); + } + + public void testReturnDone() { + VirtualMachineState[] states = { VirtualMachineState.ON }; + + checkStatesReturn(new MockVirtualMachine(), new VirtualMachineStateMonitor(VirtualMachineState.ON), states, + MonitorStatus.DONE); + } + + public void testReturnContinue() { + VirtualMachineState[] states = { VirtualMachineState.ALLOCATED, VirtualMachineState.CONFIGURED, + VirtualMachineState.LOCKED, VirtualMachineState.OFF, VirtualMachineState.PAUSED, + VirtualMachineState.NOT_ALLOCATED, VirtualMachineState.UNKNOWN }; + + checkStatesReturn(new MockVirtualMachine(), new VirtualMachineStateMonitor(VirtualMachineState.ON), states, + MonitorStatus.CONTINUE); + + checkStatesReturn(new MockVirtualMachineFailing(), new VirtualMachineStateMonitor(VirtualMachineState.ON), + states, MonitorStatus.CONTINUE); + } + + private void checkStatesReturn(final MockVirtualMachine vm, final Function function, + final VirtualMachineState[] states, final MonitorStatus expectedStatus) { + for (VirtualMachineState state : states) { + vm.setState(state); + assertEquals(function.apply(vm), expectedStatus); + } + } + + private static class MockVirtualMachine extends VirtualMachine { + private VirtualMachineState state; + + @SuppressWarnings("unchecked") + public MockVirtualMachine() { + super(EasyMock.createMock(RestContext.class), new VirtualMachineWithNodeExtendedDto()); + } + + @Override + public VirtualMachineState getState() { + return state; + } + + public void setState(final VirtualMachineState state) { + this.state = state; + } + } + + private static class MockVirtualMachineFailing extends MockVirtualMachine { + @Override + public VirtualMachineState getState() { + throw new RuntimeException("This mock class always fails to get the state"); + } + + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/monitor/functions/VirtualMachineUndeployMonitorTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/monitor/functions/VirtualMachineUndeployMonitorTest.java new file mode 100644 index 0000000000..27ce26b8be --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/monitor/functions/VirtualMachineUndeployMonitorTest.java @@ -0,0 +1,103 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.monitor.functions; + +import static org.testng.Assert.assertEquals; + +import org.easymock.EasyMock; +import org.jclouds.abiquo.domain.cloud.VirtualMachine; +import org.jclouds.abiquo.monitor.MonitorStatus; +import org.jclouds.rest.RestContext; +import org.testng.annotations.Test; + +import com.abiquo.server.core.cloud.VirtualMachineState; +import com.abiquo.server.core.cloud.VirtualMachineWithNodeExtendedDto; +import com.google.common.base.Function; + +/** + * Unit tests for the {@link VirtualMachineUndeployMonitor} function. + * + * @author Ignasi Barrera + */ +@Test(groups = "unit", testName = "VirtualMachineUndeployMonitorTest") +public class VirtualMachineUndeployMonitorTest { + + @Test(expectedExceptions = NullPointerException.class) + public void testInvalidNullArgument() { + Function function = new VirtualMachineUndeployMonitor(); + function.apply(null); + } + + public void testReturnDone() { + VirtualMachineState[] states = { VirtualMachineState.NOT_ALLOCATED }; + + checkStatesReturn(new MockVirtualMachine(), new VirtualMachineUndeployMonitor(), states, MonitorStatus.DONE); + } + + public void testReturnFail() { + VirtualMachineState[] states = { VirtualMachineState.ON, VirtualMachineState.CONFIGURED, VirtualMachineState.OFF, + VirtualMachineState.PAUSED, VirtualMachineState.UNKNOWN }; + + checkStatesReturn(new MockVirtualMachine(), new VirtualMachineUndeployMonitor(), states, MonitorStatus.FAILED); + } + + public void testReturnContinue() { + VirtualMachineState[] states = { VirtualMachineState.ALLOCATED, VirtualMachineState.LOCKED }; + + checkStatesReturn(new MockVirtualMachine(), new VirtualMachineUndeployMonitor(), states, MonitorStatus.CONTINUE); + + checkStatesReturn(new MockVirtualMachineFailing(), new VirtualMachineUndeployMonitor(), states, + MonitorStatus.CONTINUE); + } + + private void checkStatesReturn(final MockVirtualMachine vm, final Function function, + final VirtualMachineState[] states, final MonitorStatus expectedStatus) { + for (VirtualMachineState state : states) { + vm.setState(state); + assertEquals(function.apply(vm), expectedStatus); + } + } + + private static class MockVirtualMachine extends VirtualMachine { + private VirtualMachineState state; + + @SuppressWarnings("unchecked") + public MockVirtualMachine() { + super(EasyMock.createMock(RestContext.class), new VirtualMachineWithNodeExtendedDto()); + } + + @Override + public VirtualMachineState getState() { + return state; + } + + public void setState(final VirtualMachineState state) { + this.state = state; + } + } + + private static class MockVirtualMachineFailing extends MockVirtualMachine { + @Override + public VirtualMachineState getState() { + throw new RuntimeException("This mock class always fails to get the state"); + } + + } +} diff --git a/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/paas/service/scheduler/Scheduler.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/monitor/internal/BaseAsyncTaskMonitorTest.java similarity index 52% rename from demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/paas/service/scheduler/Scheduler.java rename to labs/abiquo/src/test/java/org/jclouds/abiquo/monitor/internal/BaseAsyncTaskMonitorTest.java index dabdff877b..af6857bd63 100644 --- a/demos/tweetstore/cf-tweetstore-spring/src/main/java/org/jclouds/demo/paas/service/scheduler/Scheduler.java +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/monitor/internal/BaseAsyncTaskMonitorTest.java @@ -7,7 +7,7 @@ * "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 + * 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 @@ -16,26 +16,26 @@ * specific language governing permissions and limitations * under the License. */ -package org.jclouds.demo.paas.service.scheduler; -import org.jclouds.demo.paas.RunnableHttpRequest; -import org.jclouds.demo.paas.RunnableHttpRequest.Factory; -import org.jclouds.http.HttpCommandExecutorService; +package org.jclouds.abiquo.monitor.internal; + +import static org.testng.Assert.assertNotNull; + +import org.jclouds.abiquo.internal.BaseInjectionTest; +import org.jclouds.abiquo.monitor.AsyncTaskMonitor; +import org.testng.annotations.Test; /** - * @author Andrew Phillips + * Unit tests for the {@link BaseAsyncTaskMonitor} class. + * + * @author Ignasi Barrera */ -public class Scheduler { - protected static final String SCHEDULER_ORIGINATOR_NAME = "scheduler"; +@Test(groups = "unit", testName = "BaseAsyncTaskMonitorTest") +public class BaseAsyncTaskMonitorTest extends BaseInjectionTest { - protected final Factory httpRequestFactory; + public void testAllPropertiesInjected() { + BaseAsyncTaskMonitor monitor = (BaseAsyncTaskMonitor) injector.getInstance(AsyncTaskMonitor.class); - public Scheduler(HttpCommandExecutorService httpClient) { - httpRequestFactory = - RunnableHttpRequest.factory(httpClient, SCHEDULER_ORIGINATOR_NAME); - } - - public Factory getHttpRequestFactory() { - return httpRequestFactory; - } + assertNotNull(monitor.taskMonitor); + } } diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/monitor/internal/BaseVirtualApplianceMonitorTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/monitor/internal/BaseVirtualApplianceMonitorTest.java new file mode 100644 index 0000000000..6e5e62a1b6 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/monitor/internal/BaseVirtualApplianceMonitorTest.java @@ -0,0 +1,43 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.monitor.internal; + +import static org.testng.Assert.assertNotNull; + +import org.jclouds.abiquo.internal.BaseInjectionTest; +import org.jclouds.abiquo.monitor.VirtualApplianceMonitor; +import org.testng.annotations.Test; + +/** + * Unit tests for the {@link BaseVirtualApplianceMonitor} class. + * + * @author Ignasi Barrera + */ +@Test(groups = "unit", testName = "BaseVirtualApplianceMonitorTest") +public class BaseVirtualApplianceMonitorTest extends BaseInjectionTest { + + public void testAllPropertiesInjected() { + BaseVirtualApplianceMonitor monitor = (BaseVirtualApplianceMonitor) injector + .getInstance(VirtualApplianceMonitor.class); + + assertNotNull(monitor.deployMonitor); + assertNotNull(monitor.undeployMonitor); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/monitor/internal/BaseVirtualMachineMonitorTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/monitor/internal/BaseVirtualMachineMonitorTest.java new file mode 100644 index 0000000000..6c17a59ada --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/monitor/internal/BaseVirtualMachineMonitorTest.java @@ -0,0 +1,42 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.monitor.internal; + +import static org.testng.Assert.assertNotNull; + +import org.jclouds.abiquo.internal.BaseInjectionTest; +import org.jclouds.abiquo.monitor.VirtualMachineMonitor; +import org.testng.annotations.Test; + +/** + * Unit tests for the {@link BaseVirtualMachineMonitor} class. + * + * @author Ignasi Barrera + */ +@Test(groups = "unit", testName = "BaseVirtualMachineMonitorTest") +public class BaseVirtualMachineMonitorTest extends BaseInjectionTest { + + public void testAllPropertiesInjected() { + BaseVirtualMachineMonitor monitor = (BaseVirtualMachineMonitor) injector.getInstance(VirtualMachineMonitor.class); + + assertNotNull(monitor.deployMonitor); + assertNotNull(monitor.undeployMonitor); + } +} diff --git a/demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/paas/reference/PaasConstants.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/reference/AbiquoTestConstants.java similarity index 71% rename from demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/paas/reference/PaasConstants.java rename to labs/abiquo/src/test/java/org/jclouds/abiquo/reference/AbiquoTestConstants.java index 8af7021bd2..b909d9b4d9 100644 --- a/demos/tweetstore/rhcloud-tweetstore/src/main/java/org/jclouds/demo/paas/reference/PaasConstants.java +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/reference/AbiquoTestConstants.java @@ -7,7 +7,7 @@ * "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 + * 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 @@ -16,13 +16,15 @@ * specific language governing permissions and limitations * under the License. */ -package org.jclouds.demo.paas.reference; + +package org.jclouds.abiquo.reference; /** - * Configuration properties and constants used in PaaS applications. + * Configuration constants and properties used in Abiquo tests. * - * @author Andrew Phillips + * @author Ignasi Barrera */ -public interface PaasConstants { - static final String PROPERTY_PLATFORM_BASE_URL = "jclouds.paas.baseurl"; +public interface AbiquoTestConstants { + /** The prefix for test object names. */ + public static final String PREFIX = "JC-"; } diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/rest/internal/AbiquoHttpAsyncClientTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/rest/internal/AbiquoHttpAsyncClientTest.java new file mode 100644 index 0000000000..18bc306826 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/rest/internal/AbiquoHttpAsyncClientTest.java @@ -0,0 +1,67 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.rest.internal; + +import java.io.IOException; +import java.lang.reflect.Method; + +import org.jclouds.abiquo.features.BaseAbiquoAsyncApiTest; +import org.jclouds.functions.IdentityFunction; +import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; +import org.jclouds.rest.internal.GeneratedHttpRequest; +import org.jclouds.rest.internal.RestAnnotationProcessor; +import org.testng.annotations.Test; + +import com.abiquo.model.rest.RESTLink; +import com.abiquo.server.core.infrastructure.DatacentersDto; +import com.google.inject.TypeLiteral; + +/** + * Tests annotation parsing of {@code AbiquoHttpAsyncApi}. + * + * @author Ignasi Barrera + */ +@Test(groups = "unit", testName = "AbiquoHttpAsyncClientTest") +public class AbiquoHttpAsyncClientTest extends BaseAbiquoAsyncApiTest { + public void testGet() throws SecurityException, NoSuchMethodException, IOException { + RESTLink link = new RESTLink("edit", "http://foo/bar"); + link.setType(DatacentersDto.BASE_MEDIA_TYPE); + + Method method = AbiquoHttpAsyncClient.class.getMethod("get", RESTLink.class); + GeneratedHttpRequest request = processor.createRequest(method, link); + + assertRequestLineEquals(request, "GET http://foo/bar HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: " + DatacentersDto.BASE_MEDIA_TYPE + "\n"); + assertPayloadEquals(request, null, null, false); + + assertResponseParserClassEquals(method, request, IdentityFunction.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); + + checkFilters(request); + } + + @Override + protected TypeLiteral> createTypeLiteral() { + return new TypeLiteral>() { + }; + } + +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/strategy/BaseAbiquoStrategyLiveApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/strategy/BaseAbiquoStrategyLiveApiTest.java new file mode 100644 index 0000000000..a84bf558e9 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/strategy/BaseAbiquoStrategyLiveApiTest.java @@ -0,0 +1,33 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.strategy; + +import org.jclouds.abiquo.internal.BaseAbiquoApiLiveApiTest; +import org.testng.annotations.BeforeClass; + +/** + * Base class for strategy live tests. + * + * @author Ignasi Barrera + */ +public abstract class BaseAbiquoStrategyLiveApiTest extends BaseAbiquoApiLiveApiTest { + @BeforeClass(groups = "api") + protected abstract void setupStrategy(); +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/strategy/admin/internal/ListRolesImplLiveApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/strategy/admin/internal/ListRolesImplLiveApiTest.java new file mode 100644 index 0000000000..5e6aabbb1e --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/strategy/admin/internal/ListRolesImplLiveApiTest.java @@ -0,0 +1,65 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.strategy.admin.internal; + +import static com.google.common.collect.Iterables.size; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertTrue; + +import org.jclouds.abiquo.domain.enterprise.Role; +import org.jclouds.abiquo.predicates.enterprise.RolePredicates; +import org.jclouds.abiquo.strategy.BaseAbiquoStrategyLiveApiTest; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +/** + * Live tests for the {@link ListRolesImpl} strategy. + * + * @author Ignasi Barrera + */ +@Test(groups = "api", testName = "ListRolesImplLiveApiTest") +public class ListRolesImplLiveApiTest extends BaseAbiquoStrategyLiveApiTest { + private ListRolesImpl strategy; + + @Override + @BeforeClass(groups = "api") + protected void setupStrategy() { + this.strategy = env.context.getUtils().getInjector().getInstance(ListRolesImpl.class); + } + + public void testExecute() { + Iterable roles = strategy.execute(); + assertNotNull(roles); + assertTrue(size(roles) > 0); + } + + public void testExecutePredicateWithoutResults() { + Iterable roles = strategy.execute(RolePredicates.name("UNEXISTING")); + assertNotNull(roles); + assertEquals(size(roles), 0); + } + + public void testExecutePredicateWithResults() { + Iterable roles = strategy.execute(RolePredicates.name(env.role.getName())); + assertNotNull(roles); + assertEquals(size(roles), 1); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/strategy/cloud/internal/ListAttachedNicsImplLiveApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/strategy/cloud/internal/ListAttachedNicsImplLiveApiTest.java new file mode 100644 index 0000000000..70d1cc9637 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/strategy/cloud/internal/ListAttachedNicsImplLiveApiTest.java @@ -0,0 +1,101 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.strategy.cloud.internal; + +import static com.google.common.collect.Iterables.size; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertTrue; + +import org.jclouds.abiquo.domain.network.ExternalIp; +import org.jclouds.abiquo.domain.network.Ip; +import org.jclouds.abiquo.domain.network.PrivateIp; +import org.jclouds.abiquo.domain.network.PublicIp; +import org.jclouds.abiquo.domain.network.UnmanagedNetwork; +import org.jclouds.abiquo.predicates.network.IpPredicates; +import org.jclouds.abiquo.strategy.BaseAbiquoStrategyLiveApiTest; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import com.google.common.collect.Lists; + +/** + * Live tests for the {@link ListAttachedNicsImpl} strategy. + * + * @author Ignasi Barrera + */ +@Test(groups = "api", testName = "ListAttachedNicsImplLiveApiTest") +public class ListAttachedNicsImplLiveApiTest extends BaseAbiquoStrategyLiveApiTest { + private ListAttachedNicsImpl strategy; + + private PrivateIp privateIp; + + private ExternalIp externalIp; + + private PublicIp publicIp; + + @Override + @BeforeClass(groups = "api") + protected void setupStrategy() { + this.strategy = env.context.getUtils().getInjector().getInstance(ListAttachedNicsImpl.class); + + privateIp = env.privateNetwork.listUnusedIps().get(0); + assertNotNull(privateIp); + + externalIp = env.externalNetwork.listUnusedIps().get(0); + assertNotNull(externalIp); + + publicIp = env.virtualDatacenter.listAvailablePublicIps().get(0); + env.virtualDatacenter.purchasePublicIp(publicIp); + publicIp = env.virtualDatacenter.findPurchasedPublicIp(IpPredicates. address(publicIp.getIp())); + assertNotNull(publicIp); + + env.virtualMachine.setNics(Lists.> newArrayList(privateIp, externalIp, publicIp), + Lists. newArrayList(env.unmanagedNetwork)); + } + + @AfterClass(groups = "api") + protected void tearDownStrategy() { + env.virtualMachine.setNics(Lists.> newArrayList(privateIp)); + String address = publicIp.getIp(); + env.virtualDatacenter.releaseePublicIp(publicIp); + assertNull(env.virtualDatacenter.findPurchasedPublicIp(IpPredicates. address(address))); + } + + public void testExecute() { + Iterable> vapps = strategy.execute(env.virtualMachine); + assertNotNull(vapps); + assertTrue(size(vapps) == 4); + } + + public void testExecutePredicateWithoutResults() { + Iterable> vapps = strategy.execute(env.virtualMachine, IpPredicates.address("UNEXISTING")); + assertNotNull(vapps); + assertEquals(size(vapps), 0); + } + + public void testExecutePredicateWithResults() { + Iterable> vapps = strategy.execute(env.virtualMachine, IpPredicates.address(publicIp.getIp())); + assertNotNull(vapps); + assertEquals(size(vapps), 1); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/strategy/cloud/internal/ListVirtualAppliancesImplLiveApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/strategy/cloud/internal/ListVirtualAppliancesImplLiveApiTest.java new file mode 100644 index 0000000000..c577de9b41 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/strategy/cloud/internal/ListVirtualAppliancesImplLiveApiTest.java @@ -0,0 +1,66 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.strategy.cloud.internal; + +import static com.google.common.collect.Iterables.size; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertTrue; + +import org.jclouds.abiquo.domain.cloud.VirtualAppliance; +import org.jclouds.abiquo.predicates.cloud.VirtualAppliancePredicates; +import org.jclouds.abiquo.strategy.BaseAbiquoStrategyLiveApiTest; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +/** + * Live tests for the {@link ListVirtualAppliancesImpl} strategy. + * + * @author Ignasi Barrera + */ +@Test(groups = "api", testName = "ListVirtualAppliancesImplLiveApiTest") +public class ListVirtualAppliancesImplLiveApiTest extends BaseAbiquoStrategyLiveApiTest { + private ListVirtualAppliancesImpl strategy; + + @Override + @BeforeClass(groups = "api") + protected void setupStrategy() { + this.strategy = env.context.getUtils().getInjector().getInstance(ListVirtualAppliancesImpl.class); + } + + public void testExecute() { + Iterable vapps = strategy.execute(); + assertNotNull(vapps); + assertTrue(size(vapps) > 0); + } + + public void testExecutePredicateWithoutResults() { + Iterable vapps = strategy.execute(VirtualAppliancePredicates.name("UNEXISTING")); + assertNotNull(vapps); + assertEquals(size(vapps), 0); + } + + public void testExecutePredicateWithResults() { + Iterable vapps = strategy.execute(VirtualAppliancePredicates.name(env.virtualAppliance + .getName())); + assertNotNull(vapps); + assertEquals(size(vapps), 1); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/strategy/cloud/internal/ListVirtualDatacentersImplLiveApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/strategy/cloud/internal/ListVirtualDatacentersImplLiveApiTest.java new file mode 100644 index 0000000000..1a155baf17 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/strategy/cloud/internal/ListVirtualDatacentersImplLiveApiTest.java @@ -0,0 +1,81 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.strategy.cloud.internal; + +import static com.google.common.collect.Iterables.size; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertTrue; + +import org.jclouds.abiquo.domain.cloud.VirtualDatacenter; +import org.jclouds.abiquo.domain.cloud.options.VirtualDatacenterOptions; +import org.jclouds.abiquo.predicates.cloud.VirtualDatacenterPredicates; +import org.jclouds.abiquo.strategy.BaseAbiquoStrategyLiveApiTest; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +/** + * Live tests for the {@link ListVirtualDatacentersImpl} strategy. + * + * @author Ignasi Barrera + */ +@Test(groups = "api", testName = "ListVirtualDatacentersImplLiveApiTest") +public class ListVirtualDatacentersImplLiveApiTest extends BaseAbiquoStrategyLiveApiTest { + private ListVirtualDatacentersImpl strategy; + + @Override + @BeforeClass(groups = "api") + protected void setupStrategy() { + this.strategy = env.context.getUtils().getInjector().getInstance(ListVirtualDatacentersImpl.class); + } + + public void testExecute() { + Iterable vdcs = strategy.execute(); + assertNotNull(vdcs); + assertTrue(size(vdcs) > 0); + } + + public void testExecutePredicateWithoutResults() { + Iterable vdcs = strategy.execute(VirtualDatacenterPredicates.name("UNEXISTING")); + assertNotNull(vdcs); + assertEquals(size(vdcs), 0); + } + + public void testExecutePredicateWithResults() { + Iterable vdcs = strategy.execute(VirtualDatacenterPredicates.name(env.virtualDatacenter + .getName())); + assertNotNull(vdcs); + assertEquals(size(vdcs), 1); + } + + public void testExecutePredicateOptionsWithResults() { + Iterable vdcs = strategy.execute(VirtualDatacenterOptions.builder() + .datacenterId(env.datacenter.getId()).enterpriseId(env.defaultEnterprise.getId()).build()); + assertNotNull(vdcs); + assertEquals(size(vdcs), 1); + } + + public void testExecutePredicateOptionsWithoutResults() { + Iterable vdcs = strategy.execute(VirtualDatacenterOptions.builder() + .enterpriseId(env.enterprise.getId()).build()); + assertNotNull(vdcs); + assertEquals(size(vdcs), 0); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/strategy/cloud/internal/ListVirtualMachinesImplLiveApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/strategy/cloud/internal/ListVirtualMachinesImplLiveApiTest.java new file mode 100644 index 0000000000..4c87e244e9 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/strategy/cloud/internal/ListVirtualMachinesImplLiveApiTest.java @@ -0,0 +1,95 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.strategy.cloud.internal; + +import static com.google.common.collect.Iterables.size; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.List; + +import org.jclouds.abiquo.domain.cloud.VirtualMachine; +import org.jclouds.abiquo.predicates.cloud.VirtualMachinePredicates; +import org.jclouds.abiquo.strategy.BaseAbiquoStrategyLiveApiTest; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +/** + * Live tests for the {@link ListVirtualMachinesImpl} strategy. + * + * @author Ignasi Barrera + */ +@Test(groups = "api", testName = "ListVirtualMachinesImplLiveApiTest") +public class ListVirtualMachinesImplLiveApiTest extends BaseAbiquoStrategyLiveApiTest { + private ListVirtualMachinesImpl strategy; + + @Override + @BeforeClass(groups = "api") + protected void setupStrategy() { + this.strategy = env.context.getUtils().getInjector().getInstance(ListVirtualMachinesImpl.class); + } + + public void testExecute() { + Iterable vms = strategy.execute(); + assertNotNull(vms); + assertTrue(size(vms) > 0); + } + + public void testExecutePredicateWithoutResults() { + Iterable vms = strategy.execute(VirtualMachinePredicates.internalName("UNEXISTING")); + assertNotNull(vms); + assertEquals(size(vms), 0); + } + + public void testExecutePredicateWithResults() { + Iterable vms = strategy.execute(VirtualMachinePredicates.internalName(env.virtualMachine + .getInternalName())); + assertNotNull(vms); + assertEquals(size(vms), 1); + } + + public void testExecuteWhenExceedsPagination() { + List vms = new ArrayList(); + + // Pagination by default is set to 25 items per page, so create a few more + // to verify that + // all are returned when listing + int numVms = 30; + + for (int i = 0; i < numVms; i++) { + VirtualMachine vm = VirtualMachine.Builder.fromVirtualMachine(env.virtualMachine).build(); + vm.save(); + vms.add(vm); + } + + try { + Iterable all = strategy.execute(); + + assertNotNull(all); + assertTrue(size(all) >= numVms); + } finally { + for (VirtualMachine vm : vms) { + vm.delete(); + } + } + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/strategy/config/internal/ListCategoriesImplLiveApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/strategy/config/internal/ListCategoriesImplLiveApiTest.java new file mode 100644 index 0000000000..de62bb849f --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/strategy/config/internal/ListCategoriesImplLiveApiTest.java @@ -0,0 +1,78 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.strategy.config.internal; + +import static com.google.common.collect.Iterables.size; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertTrue; + +import org.jclouds.abiquo.domain.config.Category; +import org.jclouds.abiquo.predicates.config.CategoryPredicates; +import org.jclouds.abiquo.strategy.BaseAbiquoStrategyLiveApiTest; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import com.google.common.base.Predicates; + +/** + * Live tests for the {@link ListPropertiesImpl} strategy. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +@Test(groups = "api", testName = "ListCategoriesImplLiveApiTest") +public class ListCategoriesImplLiveApiTest extends BaseAbiquoStrategyLiveApiTest { + private ListCategoriesImpl strategy; + + @Override + @BeforeClass(groups = "api") + protected void setupStrategy() { + this.strategy = env.context.getUtils().getInjector().getInstance(ListCategoriesImpl.class); + } + + public void testExecute() { + Iterable categories = strategy.execute(); + assertNotNull(categories); + assertTrue(size(categories) > 0); + } + + public void testExecutePredicateWithoutResults() { + Iterable categories = strategy.execute(CategoryPredicates.name("Unexisting category")); + assertNotNull(categories); + assertEquals(size(categories), 0); + } + + public void testExecutePredicateWithResults() { + Iterable categories = strategy.execute(CategoryPredicates.name("Applications servers")); + assertNotNull(categories); + assertEquals(size(categories), 1); + } + + public void testExecuteNotPredicateWithResults() { + Iterable categories = strategy.execute(Predicates.not(CategoryPredicates.name("Applications servers"))); + + Iterable allProperties = strategy.execute(); + + assertNotNull(categories); + assertNotNull(allProperties); + assertEquals(size(categories), size(allProperties) - 1); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/strategy/config/internal/ListLicensesImplLiveApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/strategy/config/internal/ListLicensesImplLiveApiTest.java new file mode 100644 index 0000000000..d9776c52f8 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/strategy/config/internal/ListLicensesImplLiveApiTest.java @@ -0,0 +1,82 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.strategy.config.internal; + +import static com.google.common.collect.Iterables.size; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertTrue; + +import org.jclouds.abiquo.domain.config.License; +import org.jclouds.abiquo.domain.config.options.LicenseOptions; +import org.jclouds.abiquo.predicates.config.LicensePredicates; +import org.jclouds.abiquo.strategy.BaseAbiquoStrategyLiveApiTest; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +/** + * Live tests for the {@link ListLicenseImpl} strategy. + * + * @author Ignasi Barrera + */ +@Test(groups = "api", testName = "ListLicensesImplLiveApiTest") +public class ListLicensesImplLiveApiTest extends BaseAbiquoStrategyLiveApiTest { + private ListLicensesImpl strategy; + + @Override + @BeforeClass(groups = "api") + protected void setupStrategy() { + this.strategy = env.context.getUtils().getInjector().getInstance(ListLicensesImpl.class); + } + + public void testExecute() { + Iterable licenses = strategy.execute(); + assertNotNull(licenses); + assertTrue(size(licenses) > 0); + } + + public void testExecuteInactive() { + LicenseOptions options = LicenseOptions.builder().inactive(true).build(); + + Iterable licenses = strategy.execute(options); + assertNotNull(licenses); + assertTrue(size(licenses) == 1); + } + + public void testExecuteActive() { + LicenseOptions options = LicenseOptions.builder().active(true).build(); + + Iterable licenses = strategy.execute(options); + assertNotNull(licenses); + assertTrue(size(licenses) >= 1); + } + + public void testExecutePredicateWithoutResults() { + Iterable licenses = strategy.execute(LicensePredicates.customer("FAIL")); + assertNotNull(licenses); + assertEquals(size(licenses), 0); + } + + public void testExecutePredicateWithResults() { + Iterable licenses = strategy.execute(LicensePredicates.code(env.license.getCode())); + assertNotNull(licenses); + assertEquals(size(licenses), 1); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/strategy/config/internal/ListPrivilegesImplLiveApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/strategy/config/internal/ListPrivilegesImplLiveApiTest.java new file mode 100644 index 0000000000..eea2ebc953 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/strategy/config/internal/ListPrivilegesImplLiveApiTest.java @@ -0,0 +1,77 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.strategy.config.internal; + +import static com.google.common.collect.Iterables.size; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertTrue; + +import org.jclouds.abiquo.domain.config.Privilege; +import org.jclouds.abiquo.predicates.config.PrivilegePredicates; +import org.jclouds.abiquo.strategy.BaseAbiquoStrategyLiveApiTest; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import com.google.common.base.Predicates; + +/** + * Live tests for the {@link ListPrivilegesImpl} strategy. + * + * @author Ignasi Barrera + */ +@Test(groups = "api", testName = "ListPrivilegesImplLiveApiTest") +public class ListPrivilegesImplLiveApiTest extends BaseAbiquoStrategyLiveApiTest { + private ListPrivilegesImpl strategy; + + @Override + @BeforeClass(groups = "api") + protected void setupStrategy() { + this.strategy = env.context.getUtils().getInjector().getInstance(ListPrivilegesImpl.class); + } + + public void testExecute() { + Iterable privileges = strategy.execute(); + assertNotNull(privileges); + assertTrue(size(privileges) > 0); + } + + public void testExecutePredicateWithoutResults() { + Iterable privileges = strategy.execute(PrivilegePredicates.name("Destroy the universe")); + assertNotNull(privileges); + assertEquals(size(privileges), 0); + } + + public void testExecutePredicateWithResults() { + Iterable privileges = strategy.execute(PrivilegePredicates.name("USERS_MANAGE_USERS")); + assertNotNull(privileges); + assertEquals(size(privileges), 1); + } + + public void testExecuteNotPredicateWithResults() { + Iterable privileges = strategy.execute(Predicates.not(PrivilegePredicates.name("USERS_MANAGE_USERS"))); + + Iterable allPrivileges = strategy.execute(); + + assertNotNull(privileges); + assertNotNull(allPrivileges); + assertEquals(size(privileges), size(allPrivileges) - 1); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/strategy/config/internal/ListPropertiesImplLiveApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/strategy/config/internal/ListPropertiesImplLiveApiTest.java new file mode 100644 index 0000000000..28e747e5e3 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/strategy/config/internal/ListPropertiesImplLiveApiTest.java @@ -0,0 +1,89 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.strategy.config.internal; + +import static com.google.common.collect.Iterables.size; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertTrue; + +import org.jclouds.abiquo.domain.config.SystemProperty; +import org.jclouds.abiquo.domain.config.options.PropertyOptions; +import org.jclouds.abiquo.predicates.config.SystemPropertyPredicates; +import org.jclouds.abiquo.strategy.BaseAbiquoStrategyLiveApiTest; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +import com.google.common.base.Predicates; + +/** + * Live tests for the {@link ListPropertiesImpl} strategy. + * + * @author Ignasi Barrera + * @author Francesc Montserrat + */ +@Test(groups = "api", testName = "ListPropertiesImplLiveApiTest") +public class ListPropertiesImplLiveApiTest extends BaseAbiquoStrategyLiveApiTest { + private ListPropertiesImpl strategy; + + @Override + @BeforeClass(groups = "api") + protected void setupStrategy() { + this.strategy = env.context.getUtils().getInjector().getInstance(ListPropertiesImpl.class); + } + + public void testExecute() { + Iterable properties = strategy.execute(); + assertNotNull(properties); + assertTrue(size(properties) > 0); + } + + public void testExecuteWithOptions() { + PropertyOptions options = PropertyOptions.builder().component("client").build(); + + Iterable properties = strategy.execute(options); + assertNotNull(properties); + assertTrue(size(properties) > 0); + } + + public void testExecutePredicateWithoutResults() { + Iterable properties = strategy.execute(SystemPropertyPredicates.name("Cloud color")); + assertNotNull(properties); + assertEquals(size(properties), 0); + } + + public void testExecutePredicateWithResults() { + Iterable properties = strategy.execute(SystemPropertyPredicates + .name("client.applibrary.ovfpackagesDownloadingProgressUpdateInterval")); + assertNotNull(properties); + assertEquals(size(properties), 1); + } + + public void testExecuteNotPredicateWithResults() { + Iterable properties = strategy.execute(Predicates.not(SystemPropertyPredicates + .name("client.applibrary.ovfpackagesDownloadingProgressUpdateInterval"))); + + Iterable allProperties = strategy.execute(); + + assertNotNull(properties); + assertNotNull(allProperties); + assertEquals(size(properties), size(allProperties) - 1); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/strategy/enterprise/internal/ListEnterprisesImplLiveApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/strategy/enterprise/internal/ListEnterprisesImplLiveApiTest.java new file mode 100644 index 0000000000..13f1167e2d --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/strategy/enterprise/internal/ListEnterprisesImplLiveApiTest.java @@ -0,0 +1,65 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.strategy.enterprise.internal; + +import static com.google.common.collect.Iterables.size; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertTrue; + +import org.jclouds.abiquo.domain.enterprise.Enterprise; +import org.jclouds.abiquo.predicates.enterprise.EnterprisePredicates; +import org.jclouds.abiquo.strategy.BaseAbiquoStrategyLiveApiTest; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +/** + * Live tests for the {@link ListEnterprisesImpl} strategy. + * + * @author Ignasi Barrera + */ +@Test(groups = "api", testName = "ListEnterprisesImplLiveApiTest") +public class ListEnterprisesImplLiveApiTest extends BaseAbiquoStrategyLiveApiTest { + private ListEnterprisesImpl strategy; + + @Override + @BeforeClass(groups = "api") + protected void setupStrategy() { + this.strategy = env.context.getUtils().getInjector().getInstance(ListEnterprisesImpl.class); + } + + public void testExecute() { + Iterable enterprises = strategy.execute(); + assertNotNull(enterprises); + assertTrue(size(enterprises) > 0); + } + + public void testExecutePredicateWithoutResults() { + Iterable enterprises = strategy.execute(EnterprisePredicates.name("UNEXISTING")); + assertNotNull(enterprises); + assertEquals(size(enterprises), 0); + } + + public void testExecutePredicateWithResults() { + Iterable enterprises = strategy.execute(EnterprisePredicates.name(env.enterprise.getName())); + assertNotNull(enterprises); + assertEquals(size(enterprises), 1); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/strategy/enterprise/internal/ListVirtualMachineTemplatesImplLiveApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/strategy/enterprise/internal/ListVirtualMachineTemplatesImplLiveApiTest.java new file mode 100644 index 0000000000..20b739608a --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/strategy/enterprise/internal/ListVirtualMachineTemplatesImplLiveApiTest.java @@ -0,0 +1,69 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.strategy.enterprise.internal; + +import static com.google.common.collect.Iterables.size; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertTrue; + +import org.jclouds.abiquo.domain.cloud.VirtualMachineTemplate; +import org.jclouds.abiquo.predicates.cloud.VirtualMachineTemplatePredicates; +import org.jclouds.abiquo.strategy.BaseAbiquoStrategyLiveApiTest; +import org.jclouds.abiquo.strategy.cloud.internal.ListVirtualAppliancesImpl; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +/** + * Live tests for the {@link ListVirtualAppliancesImpl} strategy. + * + * @author Ignasi Barrera + */ +@Test(groups = "api", testName = "ListVirtualMachineTemplatesImplLiveApiTest") +public class ListVirtualMachineTemplatesImplLiveApiTest extends BaseAbiquoStrategyLiveApiTest { + private ListVirtualMachineTemplatesImpl strategy; + + @Override + @BeforeClass(groups = "api") + protected void setupStrategy() { + this.strategy = env.context.getUtils().getInjector().getInstance(ListVirtualMachineTemplatesImpl.class); + } + + public void testExecute() { + Iterable templates = strategy.execute(env.defaultEnterprise); + assertNotNull(templates); + assertTrue(size(templates) > 0); + } + + public void testExecutePredicateWithoutResults() { + Iterable templates = strategy.execute(env.defaultEnterprise, + VirtualMachineTemplatePredicates.name("UNEXISTING")); + assertNotNull(templates); + assertEquals(size(templates), 0); + } + + public void testExecutePredicateWithResults() { + Iterable templates = strategy.execute(env.defaultEnterprise, + VirtualMachineTemplatePredicates.name(env.template.getName())); + assertNotNull(templates); + // Repository can have multiple templates with the same name + assertTrue(size(templates) > 0); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/strategy/infrastructure/internal/ListDatacentersImplLiveApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/strategy/infrastructure/internal/ListDatacentersImplLiveApiTest.java new file mode 100644 index 0000000000..391c46c857 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/strategy/infrastructure/internal/ListDatacentersImplLiveApiTest.java @@ -0,0 +1,65 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.strategy.infrastructure.internal; + +import static com.google.common.collect.Iterables.size; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertTrue; + +import org.jclouds.abiquo.domain.infrastructure.Datacenter; +import org.jclouds.abiquo.predicates.infrastructure.DatacenterPredicates; +import org.jclouds.abiquo.strategy.BaseAbiquoStrategyLiveApiTest; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +/** + * Live tests for the {@link ListDatacentersImpl} strategy. + * + * @author Ignasi Barrera + */ +@Test(groups = "api", testName = "ListDatacentersImplLiveApiTest") +public class ListDatacentersImplLiveApiTest extends BaseAbiquoStrategyLiveApiTest { + private ListDatacentersImpl strategy; + + @Override + @BeforeClass(groups = "api") + protected void setupStrategy() { + this.strategy = env.context.getUtils().getInjector().getInstance(ListDatacentersImpl.class); + } + + public void testExecute() { + Iterable datacenters = strategy.execute(); + assertNotNull(datacenters); + assertTrue(size(datacenters) > 0); + } + + public void testExecutePredicateWithoutResults() { + Iterable datacenters = strategy.execute(DatacenterPredicates.name("UNEXISTING")); + assertNotNull(datacenters); + assertEquals(size(datacenters), 0); + } + + public void testExecutePredicateWithResults() { + Iterable datacenters = strategy.execute(DatacenterPredicates.name(env.datacenter.getName())); + assertNotNull(datacenters); + assertEquals(size(datacenters), 1); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/strategy/infrastructure/internal/ListMachinesImplLiveApiTest.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/strategy/infrastructure/internal/ListMachinesImplLiveApiTest.java new file mode 100644 index 0000000000..b739f42623 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/strategy/infrastructure/internal/ListMachinesImplLiveApiTest.java @@ -0,0 +1,65 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.strategy.infrastructure.internal; + +import static com.google.common.collect.Iterables.size; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertTrue; + +import org.jclouds.abiquo.domain.infrastructure.Machine; +import org.jclouds.abiquo.predicates.infrastructure.MachinePredicates; +import org.jclouds.abiquo.strategy.BaseAbiquoStrategyLiveApiTest; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + +/** + * Live tests for the {@link ListMachinesImpl} strategy. + * + * @author Ignasi Barrera + */ +@Test(groups = "api", testName = "ListMachinesImplLiveApiTest") +public class ListMachinesImplLiveApiTest extends BaseAbiquoStrategyLiveApiTest { + private ListMachinesImpl strategy; + + @Override + @BeforeClass(groups = "api") + protected void setupStrategy() { + this.strategy = env.context.getUtils().getInjector().getInstance(ListMachinesImpl.class); + } + + public void testExecute() { + Iterable machines = strategy.execute(); + assertNotNull(machines); + assertTrue(size(machines) > 0); + } + + public void testExecutePredicateWithoutResults() { + Iterable machines = strategy.execute(MachinePredicates.name("UNEXISTING")); + assertNotNull(machines); + assertEquals(size(machines), 0); + } + + public void testExecutePredicateWithResults() { + Iterable machines = strategy.execute(MachinePredicates.name(env.machine.getName())); + assertNotNull(machines); + assertEquals(size(machines), 1); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/util/Assert.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/util/Assert.java new file mode 100644 index 0000000000..dcbf9d8904 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/util/Assert.java @@ -0,0 +1,81 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.util; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; + +import java.io.IOException; + +import javax.ws.rs.core.Response.Status; + +import org.jclouds.abiquo.domain.exception.AbiquoException; +import org.jclouds.io.Payload; +import org.jclouds.xml.XMLParser; +import org.jclouds.xml.internal.JAXBParser; + +import com.abiquo.model.transport.SingleResourceTransportDto; +import com.abiquo.model.transport.error.ErrorDto; + +/** + * Assertion utilities. + * + * @author Ignasi Barrera + */ +public class Assert { + /** + * Assert that the exception contains the given error. + * + * @param exception + * The exception. + * @param expectedHttpStatus + * The expected HTTP status code. + * @param expectedErrorCode + * The expected error code. + */ + public static void assertHasError(final AbiquoException exception, final Status expectedHttpStatus, + final String expectedErrorCode) { + assertEquals(exception.getHttpStatus(), expectedHttpStatus); + ErrorDto error = exception.findError(expectedErrorCode); + assertNotNull(error); + } + + /** + * Assert that the given payload matches the given string. + * + * @param payload + * The payload to check. + * @param expected + * The expected string. + * @param entityClass + * The entity class for the payload. + * @throws IOException + * If there is an error during serialization. + */ + public static void assertPayloadEquals(final Payload payload, final String expected, + final Class entityClass) throws IOException { + // Serialize and deserialize to avoid formatting issues + XMLParser xml = new JAXBParser("false"); + SingleResourceTransportDto entity = xml.fromXML(expected, entityClass); + String toMatch = xml.toXML(entity, entityClass); + + assertEquals(payload.getRawContent(), toMatch); + } +} diff --git a/labs/abiquo/src/test/java/org/jclouds/abiquo/util/Config.java b/labs/abiquo/src/test/java/org/jclouds/abiquo/util/Config.java new file mode 100644 index 0000000000..f2c2eae504 --- /dev/null +++ b/labs/abiquo/src/test/java/org/jclouds/abiquo/util/Config.java @@ -0,0 +1,70 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.abiquo.util; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.io.IOException; +import java.util.Properties; + +/** + * Test configuration. + * + * @author Ignasi Barrera + */ +public class Config { + /** The main configuration file. */ + private static final String CONFIG_FILE = "api-live.properties"; + + /** The configuration properties */ + private Properties config; + + /** The singleton configuration instance. */ + private static Config instance; + + public Config(final String config) { + ClassLoader cl = Thread.currentThread().getContextClassLoader(); + this.config = new Properties(); + + try { + this.config.load(cl.getResourceAsStream(config)); + } catch (IOException ex) { + throw new RuntimeException("Could not load test configuration file", ex); + } + } + + public Config(final Properties config) { + this.config = config; + } + + public static String get(final String property) { + return get(property, null); + } + + public static String get(final String property, final String defaultValue) { + if (instance == null) { + String configFile = System.getProperty("abiquo.live.config", CONFIG_FILE); + instance = new Config(configFile); + } + + return checkNotNull(instance.config.getProperty(property, defaultValue)); + } + +} diff --git a/labs/abiquo/src/test/resources/api-live.properties b/labs/abiquo/src/test/resources/api-live.properties new file mode 100644 index 0000000000..a452389f85 --- /dev/null +++ b/labs/abiquo/src/test/resources/api-live.properties @@ -0,0 +1,20 @@ +# Hypervisor configuration +abiquo.hypervisor.type = ${abiquo.hypervisor.type} +abiquo.hypervisor.address = ${abiquo.hypervisor.address} +abiquo.hypervisor.user = ${abiquo.hypervisor.user} +abiquo.hypervisor.pass = ${abiquo.hypervisor.pass} +abiquo.hypervisor.vswitch = ${abiquo.hypervisor.vswitch} +abiquo.hypervisor.datastore = ${abiquo.hypervisor.datastore} + +# Storage configuration +abiquo.storage.type = ${abiquo.storage.type} +abiquo.storage.address = ${abiquo.storage.address} +abiquo.storage.pass = ${abiquo.storage.pass} +abiquo.storage.user = ${abiquo.storage.user} +abiquo.storage.pool = ${abiquo.storage.pool} + +# UCS Rack configuration +abiquo.ucs.address = ${abiquo.ucs.address} +abiquo.ucs.port = ${abiquo.ucs.port} +abiquo.ucs.pass = ${abiquo.ucs.pass} +abiquo.ucs.user = ${abiquo.ucs.user} diff --git a/labs/abiquo/src/test/resources/filters/filters.properties b/labs/abiquo/src/test/resources/filters/filters.properties new file mode 100644 index 0000000000..8f434a8b80 --- /dev/null +++ b/labs/abiquo/src/test/resources/filters/filters.properties @@ -0,0 +1,26 @@ +# Hypervisor configuration +# This is the Tarantino IT hypervisor. +# Should be replaced with a dedicated ESX asap! + +#abiquo.hypervisor.pass=tarantino +#abiquo.hypervisor.address=10.60.1.132 +#abiquo.hypervisor.datastore=nfs-ds +abiquo.hypervisor.type=VMX_04 +abiquo.hypervisor.address=10.60.20.62 +abiquo.hypervisor.pass=temporal +abiquo.hypervisor.user=root +abiquo.hypervisor.vswitch=vSwitch0 +abiquo.hypervisor.datastore=datastore1 + +# Storage configuration +abiquo.storage.type=LVM +abiquo.storage.address=10.60.12.177 +#abiquo.storage.user= +#abiquo.storage.pass= +abiquo.storage.pool=abiquo + +# UCS Rack configuration +abiquo.ucs.address=10.60.1.45 +abiquo.ucs.port=80 +abiquo.ucs.pass=config +abiquo.ucs.user=config \ No newline at end of file diff --git a/labs/abiquo/src/test/resources/license/expired b/labs/abiquo/src/test/resources/license/expired new file mode 100644 index 0000000000..1db9f513ae --- /dev/null +++ b/labs/abiquo/src/test/resources/license/expired @@ -0,0 +1 @@ +B9cG06GaLHhUlpD9AWxKVkZPd4qPB0OAbm2Blr4374Y6rtPhcukg4MMLNK0uWn5fnsoBSqVX8o0hwQ1I6D3zUbFBSibMaK5xIZQfZmReHf04HPPBg0ZyaPRTBoKy6dCLnWpQIKe8vLemAudZ0w4spdzYMH2jw2TImN+2vd4QDU1qmUItYMsV5Sz+e8YVEGbUVkjRjQCmIUJskVxC+sW47dokgl5Qo8hN+4I6vKgEnXFdOSRFW2cyGgpHVH4Js4hwLG+PS2LXPS4UwvISJXRF6tO7Rgg9iaObcBD/byH5jGmggtSECUtXqI70nesIbMXRHQ1aGHARqbHH3+0Znjcu5g== \ No newline at end of file diff --git a/labs/abiquo/src/test/resources/logback-test.xml b/labs/abiquo/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..70a88e8ba3 --- /dev/null +++ b/labs/abiquo/src/test/resources/logback-test.xml @@ -0,0 +1,94 @@ + + + + target/test-data/jclouds-headers.log + true + + TRACE + + + %date %level [%logger] \(%thread\) %msg%n + + + + target/test-data/jclouds-headers.log.%d + 5 + + + + target/test-data/jclouds-payloads.log + true + + TRACE + + + %date %level [%logger] \(%thread\) %msg%n + + + + target/test-data/jclouds-payloads.log.%d + 5 + + + + target/test-data/jclouds-compute.log + true + + TRACE + + + %date %level [%logger] \(%thread\) %msg%n + + + + target/test-data/jclouds-compute.log.%d + 5 + + + + target/test-data/jclouds.log + true + + TRACE + + + %date %level [%logger] \(%thread\) %msg%n + + + + target/test-data/jclouds.log.%d + 5 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/labs/aws-elb/pom.xml b/labs/aws-elb/pom.xml index e2141be0e7..08f4c9eea4 100644 --- a/labs/aws-elb/pom.xml +++ b/labs/aws-elb/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.labs diff --git a/labs/aws-iam/pom.xml b/labs/aws-iam/pom.xml index fc9f282bc5..aaea825bce 100644 --- a/labs/aws-iam/pom.xml +++ b/labs/aws-iam/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.labs diff --git a/labs/aws-rds/pom.xml b/labs/aws-rds/pom.xml index 50fb5f5973..c4ccd05166 100644 --- a/labs/aws-rds/pom.xml +++ b/labs/aws-rds/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.labs diff --git a/labs/azure-management/pom.xml b/labs/azure-management/pom.xml index abfeb16af4..dd725d8ad2 100644 --- a/labs/azure-management/pom.xml +++ b/labs/azure-management/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.labs diff --git a/labs/azure-management/src/main/java/org/jclouds/azure/management/config/AzureManagementRestClientModule.java b/labs/azure-management/src/main/java/org/jclouds/azure/management/config/AzureManagementRestClientModule.java index 132669ada3..c3eb397a78 100644 --- a/labs/azure-management/src/main/java/org/jclouds/azure/management/config/AzureManagementRestClientModule.java +++ b/labs/azure-management/src/main/java/org/jclouds/azure/management/config/AzureManagementRestClientModule.java @@ -62,6 +62,7 @@ import org.jclouds.rest.annotations.Credential; import org.jclouds.rest.annotations.Identity; import org.jclouds.rest.config.RestClientModule; +import com.google.common.base.Charsets; import com.google.common.base.Supplier; import com.google.common.collect.ImmutableMap; import com.google.inject.Provides; @@ -139,7 +140,7 @@ public class AzureManagementRestClientModule extends RestClientModule certs = (Collection) cf.generateCertificates(new ByteArrayInputStream( - pemCerts.getBytes("UTF-8"))); + pemCerts.getBytes(Charsets.UTF_8))); keyStore.load(null); keyStore.setKeyEntry("dummy", privateKey, keyStorePassword.toCharArray(), certs.toArray(new java.security.cert.Certificate[0])); diff --git a/labs/carrenza-vcloud-director/pom.xml b/labs/carrenza-vcloud-director/pom.xml index 490dd0f0cc..83551b21d5 100644 --- a/labs/carrenza-vcloud-director/pom.xml +++ b/labs/carrenza-vcloud-director/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.labs diff --git a/labs/cdmi/pom.xml b/labs/cdmi/pom.xml index 72a2961ef2..13c1b70c9f 100644 --- a/labs/cdmi/pom.xml +++ b/labs/cdmi/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.labs diff --git a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/CDMIApi.java b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/CDMIApi.java index 5fcd3e6b39..a361c1a3f2 100644 --- a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/CDMIApi.java +++ b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/CDMIApi.java @@ -20,6 +20,9 @@ package org.jclouds.snia.cdmi.v1; import java.util.concurrent.TimeUnit; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; + import org.jclouds.concurrent.Timeout; import org.jclouds.rest.annotations.Delegate; import org.jclouds.snia.cdmi.v1.features.ContainerApi; @@ -48,18 +51,20 @@ public interface CDMIApi { * Provides synchronous access to Container Object Resource Operations. */ @Delegate - ContainerApi getContainerApi(); + ContainerApi getApi(); /** * Provides synchronous access to Data Object Resource Operations. */ @Delegate - DataApi getDataApi(); - + @Path("/{containerName}") + DataApi getDataApiForContainer(@PathParam("containerName") String containerName); + /** * Provides synchronous access to Data Object Resource Operations. */ @Delegate - DataNonCDMIContentTypeApi getDataNonCDMIContentTypeApi(); + @Path("/{containerName}") + DataNonCDMIContentTypeApi getDataNonCDMIContentTypeApiForContainer(@PathParam("containerName") String containerName); } diff --git a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/CDMIApiMetadata.java b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/CDMIApiMetadata.java index 0af9378e31..dd8ee87fd9 100644 --- a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/CDMIApiMetadata.java +++ b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/CDMIApiMetadata.java @@ -66,14 +66,9 @@ public class CDMIApiMetadata extends BaseRestApiMetadata { protected Builder() { super(CDMIApi.class, CDMIAsyncApi.class); - id("cdmi") - .name("SNIA CDMI API") - .identityName("tenantId:user") - .credentialName("password") - .documentation(URI.create("http://www.snia.org/cdmi")) - .version("1.0.1") - .defaultEndpoint("http://localhost:8080") - .defaultProperties(CDMIApiMetadata.defaultProperties()) + id("cdmi").name("SNIA CDMI API").identityName("tenantId:user").credentialName("password") + .documentation(URI.create("http://www.snia.org/cdmi")).version("1.0.1") + .defaultEndpoint("http://localhost:8080").defaultProperties(CDMIApiMetadata.defaultProperties()) .defaultModules(ImmutableSet.> of(CDMIRestClientModule.class)); } diff --git a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/CDMIAsyncApi.java b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/CDMIAsyncApi.java index a23670fe2a..8be45e56bd 100644 --- a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/CDMIAsyncApi.java +++ b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/CDMIAsyncApi.java @@ -18,9 +18,13 @@ */ package org.jclouds.snia.cdmi.v1; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; + import org.jclouds.rest.annotations.Delegate; import org.jclouds.snia.cdmi.v1.features.ContainerAsyncApi; import org.jclouds.snia.cdmi.v1.features.DataAsyncApi; +import org.jclouds.snia.cdmi.v1.features.DataNonCDMIContentTypeAsyncApi; import org.jclouds.snia.cdmi.v1.features.DomainAsyncApi; /** @@ -43,18 +47,21 @@ public interface CDMIAsyncApi { * Provides asynchronous access to Container Object Resource Operations. */ @Delegate - ContainerAsyncApi getContainerApi(); + ContainerAsyncApi getApi(); /** * Provides asynchronous access to Data Object Resource Operations. */ @Delegate - DataAsyncApi getDataApi(); + @Path("/{containerName}") + DataAsyncApi getDataApiForContainer(@PathParam("containerName") String containerName); /** * Provides asynchronous access to Data Object Resource Operations. */ @Delegate - DataAsyncApi getDataNonCDMIContentTypeApi(); - + @Path("/{containerName}") + DataNonCDMIContentTypeAsyncApi getDataNonCDMIContentTypeApiForContainer( + @PathParam("containerName") String containerName); + } diff --git a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/ObjectTypes.java b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/ObjectTypes.java index 17e627b0f1..d79f33e278 100644 --- a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/ObjectTypes.java +++ b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/ObjectTypes.java @@ -24,6 +24,6 @@ package org.jclouds.snia.cdmi.v1; */ public interface ObjectTypes { - public static final String CONTAINER = "application/cdmi-container"; - public static final String DATAOBJECT = "application/cdmi-object"; + public static final String CONTAINER = "application/cdmi-container"; + public static final String DATAOBJECT = "application/cdmi-object"; } diff --git a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/binders/BindQueryParmsToSuffix.java b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/binders/BindQueryParmsToSuffix.java index d2fa4cf880..3ea4fa8539 100644 --- a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/binders/BindQueryParmsToSuffix.java +++ b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/binders/BindQueryParmsToSuffix.java @@ -20,29 +20,28 @@ package org.jclouds.snia.cdmi.v1.binders; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; + import javax.inject.Singleton; + import org.jclouds.http.HttpRequest; import org.jclouds.rest.Binder; import org.jclouds.snia.cdmi.v1.queryparams.CDMIObjectQueryParams; /** - * This binding solves the problem jax-rs encoding ? ; : which some servers can - * not handle + * This binding solves the problem jax-rs encoding ? ; : which some servers can not handle * * @author Kenneth Nagin */ @Singleton public class BindQueryParmsToSuffix implements Binder { - @SuppressWarnings("unchecked") - @Override - public R bindToRequest(R request, Object input) { - checkArgument( - checkNotNull(input, "input") instanceof CDMIObjectQueryParams, - "this binder is only valid for CDMIObjectQueryParams!"); - checkNotNull(request, "request"); - String queryParams = input.toString(); - return (R) request.toBuilder() - .endpoint(request.getEndpoint() + "?" + queryParams).build(); - } + @SuppressWarnings("unchecked") + @Override + public R bindToRequest(R request, Object input) { + checkArgument(checkNotNull(input, "input") instanceof CDMIObjectQueryParams, + "this binder is only valid for CDMIObjectQueryParams!"); + checkNotNull(request, "request"); + String queryParams = input.toString(); + return (R) request.toBuilder().endpoint(request.getEndpoint() + "?" + queryParams).build(); + } } diff --git a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/config/CDMIRestClientModule.java b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/config/CDMIRestClientModule.java index 2004e8cd0d..161951f66b 100644 --- a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/config/CDMIRestClientModule.java +++ b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/config/CDMIRestClientModule.java @@ -26,16 +26,16 @@ import org.jclouds.http.annotation.Redirection; import org.jclouds.http.annotation.ServerError; import org.jclouds.rest.ConfiguresRestClient; import org.jclouds.rest.config.RestClientModule; -import org.jclouds.snia.cdmi.v1.CDMIAsyncApi; import org.jclouds.snia.cdmi.v1.CDMIApi; -import org.jclouds.snia.cdmi.v1.features.ContainerAsyncApi; +import org.jclouds.snia.cdmi.v1.CDMIAsyncApi; import org.jclouds.snia.cdmi.v1.features.ContainerApi; -import org.jclouds.snia.cdmi.v1.features.DataAsyncApi; +import org.jclouds.snia.cdmi.v1.features.ContainerAsyncApi; import org.jclouds.snia.cdmi.v1.features.DataApi; +import org.jclouds.snia.cdmi.v1.features.DataAsyncApi; import org.jclouds.snia.cdmi.v1.features.DataNonCDMIContentTypeApi; import org.jclouds.snia.cdmi.v1.features.DataNonCDMIContentTypeAsyncApi; -import org.jclouds.snia.cdmi.v1.features.DomainAsyncApi; import org.jclouds.snia.cdmi.v1.features.DomainApi; +import org.jclouds.snia.cdmi.v1.features.DomainAsyncApi; import org.jclouds.snia.cdmi.v1.handlers.CDMIErrorHandler; import com.google.common.collect.ImmutableMap; @@ -48,10 +48,10 @@ import com.google.common.collect.ImmutableMap; @ConfiguresRestClient public class CDMIRestClientModule extends RestClientModule { - public static final Map, Class> DELEGATE_MAP = ImmutableMap., Class> builder().put( - DomainApi.class, DomainAsyncApi.class).put(ContainerApi.class, ContainerAsyncApi.class).put( - DataApi.class, DataAsyncApi.class).put( - DataNonCDMIContentTypeApi.class, DataNonCDMIContentTypeAsyncApi.class).build(); + public static final Map, Class> DELEGATE_MAP = ImmutableMap., Class> builder() + .put(DomainApi.class, DomainAsyncApi.class).put(ContainerApi.class, ContainerAsyncApi.class) + .put(DataApi.class, DataAsyncApi.class) + .put(DataNonCDMIContentTypeApi.class, DataNonCDMIContentTypeAsyncApi.class).build(); public CDMIRestClientModule() { super(DELEGATE_MAP); diff --git a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/domain/CDMIObject.java b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/domain/CDMIObject.java index a8437c01e3..dea0b740eb 100644 --- a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/domain/CDMIObject.java +++ b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/domain/CDMIObject.java @@ -42,269 +42,250 @@ import com.google.common.collect.Maps; */ public class CDMIObject { - public static Builder builder() { - return new ConcreteBuilder(); - } + public static Builder builder() { + return new ConcreteBuilder(); + } - public Builder toBuilder() { - return builder().fromCDMIObject(this); - } + public Builder toBuilder() { + return builder().fromCDMIObject(this); + } - private static class ConcreteBuilder extends Builder { - } + private static class ConcreteBuilder extends Builder { + } - public static abstract class Builder> { - private String objectID; - private String objectType; - private String objectName; - private String parentURI; + public static abstract class Builder> { + private String objectID; + private String objectType; + private String objectName; + private String parentURI; - private Map metadata = Maps.newHashMap(); + private Map metadata = Maps.newHashMap(); - /** - * @see DataObject#getMetadata() - */ - public B metadata(Map metadata) { - this.metadata = ImmutableMap.copyOf(checkNotNull(metadata, - "metadata")); - return self(); - } + /** + * @see DataObject#getMetadata() + */ + public B metadata(Map metadata) { + this.metadata = ImmutableMap.copyOf(checkNotNull(metadata, "metadata")); + return self(); + } - @SuppressWarnings("unchecked") - protected B self() { - return (B) this; - } + @SuppressWarnings("unchecked") + protected B self() { + return (B) this; + } - /** - * @see CDMIObject#getObjectID() - */ - public B objectID(String objectID) { - this.objectID = objectID; - return self(); - } + /** + * @see CDMIObject#getObjectID() + */ + public B objectID(String objectID) { + this.objectID = objectID; + return self(); + } - /** - * @see CDMIObject#getObjectType() - */ - public B objectType(String objectType) { - this.objectType = objectType; - return self(); - } + /** + * @see CDMIObject#getObjectType() + */ + public B objectType(String objectType) { + this.objectType = objectType; + return self(); + } - /** - * @see CDMIObject#getObjectName() - */ - public B objectName(String objectName) { - this.objectName = objectName; - return self(); - } + /** + * @see CDMIObject#getObjectName() + */ + public B objectName(String objectName) { + this.objectName = objectName; + return self(); + } - /** - * @see CDMIObject#getParentURI() - */ - public B parentURI(String parentURI) { - this.parentURI = parentURI; - return self(); - } + /** + * @see CDMIObject#getParentURI() + */ + public B parentURI(String parentURI) { + this.parentURI = parentURI; + return self(); + } - public CDMIObject build() { - return new CDMIObject(this); - } + public CDMIObject build() { + return new CDMIObject(this); + } - protected B fromCDMIObject(CDMIObject in) { - return objectID(in.getObjectID()).objectType(in.getObjectType()) - .objectName(in.getObjectName()) - .parentURI(in.getParentURI()).metadata(in.getMetadata()); - } - } + protected B fromCDMIObject(CDMIObject in) { + return objectID(in.getObjectID()).objectType(in.getObjectType()).objectName(in.getObjectName()) + .parentURI(in.getParentURI()).metadata(in.getMetadata()); + } + } - private final String objectID; - private final String objectType; - private final String objectName; - private String parentURI; - private final Map metadata; - private Map userMetaDataIn; - private Map systemMetaDataIn; - private List> aclMetaDataIn; + private final String objectID; + private final String objectType; + private final String objectName; + private String parentURI; + private final Map metadata; + private Map userMetaDataIn; + private Map systemMetaDataIn; + private List> aclMetaDataIn; - protected CDMIObject(Builder builder) { - this.objectID = checkNotNull(builder.objectID, "objectID"); - this.objectType = checkNotNull(builder.objectType, "objectType"); - this.objectName = builder.objectName; - this.parentURI = checkNotNull(builder.parentURI, "parentURI"); - this.metadata = ImmutableMap.copyOf(checkNotNull(builder.metadata, - "metadata")); - } + protected CDMIObject(Builder builder) { + this.objectID = checkNotNull(builder.objectID, "objectID"); + this.objectType = checkNotNull(builder.objectType, "objectType"); + this.objectName = builder.objectName; + this.parentURI = checkNotNull(builder.parentURI, "parentURI"); + this.metadata = ImmutableMap.copyOf(checkNotNull(builder.metadata, "metadata")); + } - /** - * Object ID of the object
- * Every object stored within a CDMI-compliant system shall have a globally - * unique object identifier (ID) assigned at creation time. The CDMI object - * ID is a string with requirements for how it is generated and how it - * obtains its uniqueness. Each offering that implements CDMI is able to - * produce these identifiers without conflicting with other offerings. - * - * note: CDMI Servers do not always support ObjectID tags, however - * downstream jclouds code does not handle null so we return a empty String - * instead. - */ - public String getObjectID() { - return (objectID == null) ? "" : objectID; - } + /** + * Object ID of the object
+ * Every object stored within a CDMI-compliant system shall have a globally unique object + * identifier (ID) assigned at creation time. The CDMI object ID is a string with requirements + * for how it is generated and how it obtains its uniqueness. Each offering that implements CDMI + * is able to produce these identifiers without conflicting with other offerings. + * + * note: CDMI Servers do not always support ObjectID tags, however downstream jclouds code does + * not handle null so we return a empty String instead. + */ + public String getObjectID() { + return (objectID == null) ? "" : objectID; + } - /** - * - * type of the object - */ - public String getObjectType() { - return objectType; - } + /** + * + * type of the object + */ + public String getObjectType() { + return objectType; + } - /** - * For objects in a container, the objectName field shall be returned. For - * objects not in a container (objects that are only accessible by ID), the - * objectName field shall not be returned. - * - * Name of the object - */ - @Nullable - public String getObjectName() { - return (objectName == null) ? "" : objectName; - } + /** + * For objects in a container, the objectName field shall be returned. For objects not in a + * container (objects that are only accessible by ID), the objectName field shall not be + * returned. + * + * Name of the object + */ + @Nullable + public String getObjectName() { + return (objectName == null) ? "" : objectName; + } - /** - * - * parent URI - */ - public String getParentURI() { - return parentURI; - } + /** + * + * parent URI + */ + public String getParentURI() { + return parentURI; + } - /** - * Metadata for the CDMI object. This field includes any user and system - * metadata specified in the request body metadata field, along with storage - * system metadata generated by the cloud storage system. - */ - public Map getMetadata() { - return metadata; - } + /** + * Metadata for the CDMI object. This field includes any user and system metadata specified in + * the request body metadata field, along with storage system metadata generated by the cloud + * storage system. + */ + public Map getMetadata() { + return metadata; + } - /** - * Parse Metadata for the container object from the original JsonBall. - * System metadata data is prefixed with cdmi. System ACL metadata data is - * prefixed with cdmi_acl - * - */ - private void parseMetadata() { - userMetaDataIn = new HashMap(); - systemMetaDataIn = new HashMap(); - aclMetaDataIn = new ArrayList>(); - Iterator keys = metadata.keySet().iterator(); - while (keys.hasNext()) { - String key = keys.next(); - JsonBall value = metadata.get(key); - if (key.startsWith("cdmi")) { - if (key.matches("cdmi_acl")) { - String[] cdmi_acl_array = value.toString().split("[{}]"); - for (int i = 0; i < cdmi_acl_array.length; i++) { - if (!(cdmi_acl_array[i].startsWith("[") - || cdmi_acl_array[i].startsWith("]") || cdmi_acl_array[i] - .startsWith(","))) { - HashMap aclMap = new HashMap(); - String[] cdmi_acl_member = cdmi_acl_array[i] - .split(","); - for (String s : cdmi_acl_member) { - String cdmi_acl_key = s.substring(0, - s.indexOf(":")); - String cdmi_acl_value = s.substring(s - .indexOf(":") + 1); - cdmi_acl_value.replace('"', ' ').trim(); - aclMap.put(cdmi_acl_key, cdmi_acl_value); - } - aclMetaDataIn.add(aclMap); - } - } - } else { - systemMetaDataIn.put(key, value.toString() - .replace('"', ' ').trim()); - } - } else { - userMetaDataIn.put(key, value.toString().replace('"', ' ') - .trim()); - } - } - } + /** + * Parse Metadata for the container object from the original JsonBall. System metadata data is + * prefixed with cdmi. System ACL metadata data is prefixed with cdmi_acl + * + */ + private void parseMetadata() { + userMetaDataIn = new HashMap(); + systemMetaDataIn = new HashMap(); + aclMetaDataIn = new ArrayList>(); + Iterator keys = metadata.keySet().iterator(); + while (keys.hasNext()) { + String key = keys.next(); + JsonBall value = metadata.get(key); + if (key.startsWith("cdmi")) { + if (key.matches("cdmi_acl")) { + String[] cdmi_acl_array = value.toString().split("[{}]"); + for (int i = 0; i < cdmi_acl_array.length; i++) { + if (!(cdmi_acl_array[i].startsWith("[") || cdmi_acl_array[i].startsWith("]") || cdmi_acl_array[i] + .startsWith(","))) { + HashMap aclMap = new HashMap(); + String[] cdmi_acl_member = cdmi_acl_array[i].split(","); + for (String s : cdmi_acl_member) { + String cdmi_acl_key = s.substring(0, s.indexOf(":")); + String cdmi_acl_value = s.substring(s.indexOf(":") + 1); + cdmi_acl_value.replace('"', ' ').trim(); + aclMap.put(cdmi_acl_key, cdmi_acl_value); + } + aclMetaDataIn.add(aclMap); + } + } + } else { + systemMetaDataIn.put(key, value.toString().replace('"', ' ').trim()); + } + } else { + userMetaDataIn.put(key, value.toString().replace('"', ' ').trim()); + } + } + } - /** - * Get User Metadata for the container object. This field includes any user - * metadata - */ - public Map getUserMetadata() { - if (userMetaDataIn == null) { - parseMetadata(); - } - return userMetaDataIn; - } + /** + * Get User Metadata for the container object. This field includes any user metadata + */ + public Map getUserMetadata() { + if (userMetaDataIn == null) { + parseMetadata(); + } + return userMetaDataIn; + } - /** - * Get System Metadata for the container object excluding ACL related - * metadata - */ - public Map getSystemMetadata() { - if (systemMetaDataIn == null) { - parseMetadata(); - } - return systemMetaDataIn; - } + /** + * Get System Metadata for the container object excluding ACL related metadata + */ + public Map getSystemMetadata() { + if (systemMetaDataIn == null) { + parseMetadata(); + } + return systemMetaDataIn; + } - /** - * Get System Metadata for the container object excluding ACL related - * metadata - */ - public List> getACLMetadata() { - if (aclMetaDataIn == null) { - parseMetadata(); - } - return aclMetaDataIn; - } + /** + * Get System Metadata for the container object excluding ACL related metadata + */ + public List> getACLMetadata() { + if (aclMetaDataIn == null) { + parseMetadata(); + } + return aclMetaDataIn; + } - @Override - public boolean equals(Object o) { - if (this == o) - return true; - if (o == null || getClass() != o.getClass()) - return false; - CDMIObject that = CDMIObject.class.cast(o); - return equal(this.objectID, that.objectID) - && equal(this.objectName, that.objectName) - && equal(this.objectType, that.objectType) - && equal(this.parentURI, that.parentURI) - && equal(this.metadata, that.metadata); - } + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + CDMIObject that = CDMIObject.class.cast(o); + return equal(this.objectID, that.objectID) && equal(this.objectName, that.objectName) + && equal(this.objectType, that.objectType) && equal(this.parentURI, that.parentURI) + && equal(this.metadata, that.metadata); + } - public boolean clone(Object o) { - if (this == o) - return false; - if (o == null || getClass() != o.getClass()) - return false; - CDMIObject that = CDMIObject.class.cast(o); - return equal(this.objectType, that.objectType); - } + public boolean clone(Object o) { + if (this == o) + return false; + if (o == null || getClass() != o.getClass()) + return false; + CDMIObject that = CDMIObject.class.cast(o); + return equal(this.objectType, that.objectType); + } - @Override - public int hashCode() { - return Objects.hashCode(objectID, objectName, objectType, parentURI, - metadata); - } + @Override + public int hashCode() { + return Objects.hashCode(objectID, objectName, objectType, parentURI, metadata); + } - @Override - public String toString() { - return string().toString(); - } + @Override + public String toString() { + return string().toString(); + } - protected ToStringHelper string() { - return Objects.toStringHelper("").add("objectID", objectID) - .add("objectName", objectName).add("objectType", objectType) - .add("parentURI", parentURI).add("metadata", metadata); - } + protected ToStringHelper string() { + return Objects.toStringHelper("").add("objectID", objectID).add("objectName", objectName) + .add("objectType", objectType).add("parentURI", parentURI).add("metadata", metadata); + } } diff --git a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/domain/Container.java b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/domain/Container.java index 21dee5e811..852a34aa0b 100644 --- a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/domain/Container.java +++ b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/domain/Container.java @@ -33,87 +33,80 @@ import com.google.common.collect.ImmutableSet; */ public class Container extends CDMIObject { - public static Builder builder() { - return new ConcreteBuilder(); - } + public static Builder builder() { + return new ConcreteBuilder(); + } - @Override - public Builder toBuilder() { - return builder().fromContainer(this); - } + @Override + public Builder toBuilder() { + return builder().fromContainer(this); + } - public static class Builder> extends - CDMIObject.Builder { + public static class Builder> extends CDMIObject.Builder { - private Set children = ImmutableSet.of(); + private Set children = ImmutableSet.of(); - /** - * @see Container#getChildren() - */ - public B children(String... children) { - return children(ImmutableSet.copyOf(checkNotNull(children, - "children"))); - } + /** + * @see Container#getChildren() + */ + public B children(String... children) { + return children(ImmutableSet.copyOf(checkNotNull(children, "children"))); + } - /** - * @see Container#getChildren() - */ - public B children(Set children) { - this.children = ImmutableSet.copyOf(checkNotNull(children, - "children")); - return self(); - } + /** + * @see Container#getChildren() + */ + public B children(Set children) { + this.children = ImmutableSet.copyOf(checkNotNull(children, "children")); + return self(); + } + @Override + public Container build() { + return new Container(this); + } - @Override - public Container build() { - return new Container(this); - } + public B fromContainer(Container in) { + return fromCDMIObject(in).children(in.getChildren()); + // .metadata(in.getMetadata()); + } + } - public B fromContainer(Container in) { - return fromCDMIObject(in).children(in.getChildren()); - // .metadata(in.getMetadata()); - } - } + private static class ConcreteBuilder extends Builder { + } - private static class ConcreteBuilder extends Builder { - } + private final Set children; - private final Set children; + protected Container(Builder builder) { + super(builder); + this.children = ImmutableSet.copyOf(checkNotNull(builder.children, "children")); + } - protected Container(Builder builder) { - super(builder); - this.children = ImmutableSet.copyOf(checkNotNull(builder.children, - "children")); - } + /** + * Names of the children objects in the container object. Child container objects end with "/". + */ + public Set getChildren() { + return children; + } - /** - * Names of the children objects in the container object. Child container - * objects end with "/". - */ - public Set getChildren() { - return children; - } + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + Container that = Container.class.cast(o); + return super.equals(that) && equal(this.children, that.children); + } + @Override + public int hashCode() { + return Objects.hashCode(super.hashCode(), children); + } - @Override - public boolean equals(Object o) { - if (this == o) - return true; - if (o == null || getClass() != o.getClass()) - return false; - Container that = Container.class.cast(o); - return super.equals(that) && equal(this.children, that.children); - } - - @Override - public int hashCode() { - return Objects.hashCode(super.hashCode(), children); - } - - @Override - public ToStringHelper string() { - return super.string().add("children", children); - } + @Override + public ToStringHelper string() { + return super.string().add("children", children); + } } diff --git a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/domain/DataObject.java b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/domain/DataObject.java index f78ac12970..855e500aaa 100644 --- a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/domain/DataObject.java +++ b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/domain/DataObject.java @@ -39,161 +39,155 @@ import com.google.common.io.InputSupplier; */ public class DataObject extends CDMIObject { - public static Builder builder() { - return new ConcreteBuilder(); - } + public static Builder builder() { + return new ConcreteBuilder(); + } - @Override - public Builder toBuilder() { - return builder().fromDataObject(this); - } + @Override + public Builder toBuilder() { + return builder().fromDataObject(this); + } - public static class Builder> extends - CDMIObject.Builder { - private String mimetype = new String(); - private String value = new String(); + public static class Builder> extends CDMIObject.Builder { + private String mimetype = new String(); + private String value = new String(); - /** - * @see DataObject#getMimetype() - */ - public B mimetype(String mimetype) { - this.mimetype = mimetype; - return self(); - } + /** + * @see DataObject#getMimetype() + */ + public B mimetype(String mimetype) { + this.mimetype = mimetype; + return self(); + } - /** - * @see DataObject#getValueAsString() - */ - public B value(String value) { - this.value = value; - return self(); - } + /** + * @see DataObject#getValueAsString() + */ + public B value(String value) { + this.value = value; + return self(); + } - @Override - public DataObject build() { - return new DataObject(this); - } + @Override + public DataObject build() { + return new DataObject(this); + } - public B fromDataObject(DataObject in) { - return fromCDMIObject(in).mimetype(in.getMimetype()); - } - } + public B fromDataObject(DataObject in) { + return fromCDMIObject(in).mimetype(in.getMimetype()); + } + } - private static class ConcreteBuilder extends Builder { - } + private static class ConcreteBuilder extends Builder { + } - private final String mimetype; - private final String value; + private final String mimetype; + private final String value; - protected DataObject(Builder builder) { - super(builder); - this.mimetype = checkNotNull(builder.mimetype, "mimetype"); - this.value = checkNotNull(builder.value, "value"); - } + protected DataObject(Builder builder) { + super(builder); + this.mimetype = checkNotNull(builder.mimetype, "mimetype"); + this.value = checkNotNull(builder.value, "value"); + } - /** - * get dataObject's mimetype. - */ - public String getMimetype() { - return mimetype; - } + /** + * get dataObject's mimetype. + */ + public String getMimetype() { + return mimetype; + } - /** - * get dataObject's value as a String - */ - public String getValueAsString() { - return value; - } + /** + * get dataObject's value as a String + */ + public String getValueAsString() { + return value; + } - /** - * get dataObject's value as a InputStream value character set is - * Charsets.UTF_8 - * - * @return value - */ - public InputSupplier getValueAsInputSupplier() { - return ByteStreams.newInputStreamSupplier(value.getBytes(Charsets.UTF_8)); - } + /** + * get dataObject's value as a InputStream value character set is Charsets.UTF_8 + * + * @return value + */ + public InputSupplier getValueAsInputSupplier() { + return ByteStreams.newInputStreamSupplier(value.getBytes(Charsets.UTF_8)); + } - /** - * get dataObject's value as a InputStream - * - * @param charset - * value character set - * @return value - */ - public InputSupplier getValueAsInputSupplier(Charset charset) { - return ByteStreams.newInputStreamSupplier(value.getBytes(charset)); - } + /** + * get dataObject's value as a InputStream + * + * @param charset + * value character set + * @return value + */ + public InputSupplier getValueAsInputSupplier(Charset charset) { + return ByteStreams.newInputStreamSupplier(value.getBytes(charset)); + } - /** - * get dataObject's value as a ByteArray value character set is - * Charsets.UTF_8 - * - * @return value - */ - public byte[] getValueAsByteArray() { - return value.getBytes(Charsets.UTF_8); - } + /** + * get dataObject's value as a ByteArray value character set is Charsets.UTF_8 + * + * @return value + */ + public byte[] getValueAsByteArray() { + return value.getBytes(Charsets.UTF_8); + } - /** - * get dataObject's value as a InputStream - * - * @param charset - * value character set - * @return value - */ - public byte[] getValueAsByteArray(Charset charset) { - return value.getBytes(charset); - } + /** + * get dataObject's value as a InputStream + * + * @param charset + * value character set + * @return value + */ + public byte[] getValueAsByteArray(Charset charset) { + return value.getBytes(charset); + } - /** - * get dataObject's value as a File value character set is Charsets.UTF_8 - * - * @param destDir - * destination directory - * @return value - */ - public File getValueAsFile(File destDir) throws IOException { - File fileOut = new File(destDir, this.getObjectName()); - Files.copy(getValueAsInputSupplier(), fileOut); - return fileOut; - } - + /** + * get dataObject's value as a File value character set is Charsets.UTF_8 + * + * @param destDir + * destination directory + * @return value + */ + public File getValueAsFile(File destDir) throws IOException { + File fileOut = new File(destDir, this.getObjectName()); + Files.copy(getValueAsInputSupplier(), fileOut); + return fileOut; + } - /** - * get dataObject's value as a File - * - * @param charset - * value character set - * @return value - */ - public File getValueAsFile(File destDir, Charset charset) - throws IOException { - File fileOut = new File(destDir, this.getObjectName()); - Files.copy(getValueAsInputSupplier(charset), fileOut); - return fileOut; - } + /** + * get dataObject's value as a File + * + * @param charset + * value character set + * @return value + */ + public File getValueAsFile(File destDir, Charset charset) throws IOException { + File fileOut = new File(destDir, this.getObjectName()); + Files.copy(getValueAsInputSupplier(charset), fileOut); + return fileOut; + } - @Override - public boolean equals(Object o) { - if (this == o) - return true; - if (o == null || getClass() != o.getClass()) - return false; - DataObject that = DataObject.class.cast(o); - return super.equals(that) && equal(this.mimetype, that.mimetype) - && equal(this.value, that.value); - } + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; + DataObject that = DataObject.class.cast(o); + return super.equals(that) && equal(this.mimetype, that.mimetype) && equal(this.value, that.value); + } - @Override - public int hashCode() { - return Objects.hashCode(super.hashCode(), mimetype, value); - } + @Override + public int hashCode() { + return Objects.hashCode(super.hashCode(), mimetype, value); + } - @Override - public ToStringHelper string() { - return super.string().add("mimetype", mimetype); - } + @Override + public ToStringHelper string() { + return super.string().add("mimetype", mimetype); + } } diff --git a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/features/ContainerApi.java b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/features/ContainerApi.java index 728d99c33e..fe3b1ae555 100644 --- a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/features/ContainerApi.java +++ b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/features/ContainerApi.java @@ -35,80 +35,83 @@ import org.jclouds.snia.cdmi.v1.queryparams.ContainerQueryParams; @Timeout(duration = 180, timeUnit = TimeUnit.SECONDS) public interface ContainerApi { - /** - * get CDMI Container - * - * @param containerName - * containerName must end with a forward slash, /. - * @return Container - *
-	 *  Examples: 
-	 *  {@code
-	 *  container = getContainer("myContainer/");
-	 *  container = getContainer("parentContainer/childContainer/");
-	 *  }
-	 *  
-	 */
-	Container getContainer(String containerName);
+   /**
+    * get CDMI Container
+    * 
+    * @param containerName
+    *           containerName must end with a forward slash, /.
+    * @return Container
+    * 
+    *         
+    *  Examples: 
+    *  {@code
+    *  container = get("myContainer/");
+    *  container = get("parentContainer/childContainer/");
+    * }
+    * 
+    *         
+    */
+   Container get(String containerName);
 
-	/**
-	 * get CDMI Container
-	 * 
-	 * @param containerName
-	 * @param queryParams
-	 *            enables getting only certain fields, metadata, children range
-	 * @return Container
-	 * 
-	 * Examples: 
-	 * {@code
-	 * container = getContainer("myContainer/",ContainerQueryParams.Builder.mimetype("text/plain").field("objectName"))
-	 * container = getContainer("myContainer/",ContainerQueryParams.Builder.metadata().field("objectName"))
-	 * }
-	 * 
- * @see ContainerQueryParams - */ - Container getContainer(String containerName, - ContainerQueryParams queryParams); + /** + * get CDMI Container + * + * @param containerName + * @param queryParams + * enables getting only certain fields, metadata, children range + * @return Container + * + *
+    * Examples: 
+    * {@code
+    * container = get("myContainer/",ContainerQueryParams.Builder.mimetype("text/plain").field("objectName"))
+    * container = get("myContainer/",ContainerQueryParams.Builder.metadata().field("objectName"))
+    * }
+    * 
+ * @see ContainerQueryParams + */ + Container get(String containerName, ContainerQueryParams queryParams); - /** - * Create CDMI Container - * - * @param containerName - * containerName must end with a forward slash, /. - * @return Container - *
-	 *  Examples: 
-	 *  {@code
-	 *  container = createContainer("myContainer/");
-	 *  container = createContainer("parentContainer/childContainer/");
-	 *  }
-	 *  
- */ - Container createContainer(String containerName); + /** + * Create CDMI Container + * + * @param containerName + * containerName must end with a forward slash, /. + * @return Container + * + *
+    *  Examples: 
+    *  {@code
+    *  container = create("myContainer/");
+    *  container = create("parentContainer/childContainer/");
+    *  }
+    * 
+ */ + Container create(String containerName); - /** - * Create CDMI Container - * - * @param containerName - * @param options - * enables adding metadata - * @return Container - *
-	 *  Examples: 
-	 *  {@code
-	 *  container = createContainer("myContainer/",CreateContainerOptions.Builder..metadata(metaDataIn));
-	 *  }
-	 *  
- * @see CreateContainerOptions - */ - Container createContainer(String containerName, - CreateContainerOptions... options); + /** + * Create CDMI Container + * + * @param containerName + * @param options + * enables adding metadata + * @return Container + * + *
+    *  Examples: 
+    *  {@code
+    *  container = create("myContainer/",CreateContainerOptions.Builder..metadata(metaDataIn));
+    *  }
+    * 
+ * @see CreateContainerOptions + */ + Container create(String containerName, CreateContainerOptions... options); - /** - * Delete CDMI Container - * - * @param containerName - */ - void deleteContainer(String containerName); + /** + * Delete CDMI Container + * + * @param containerName + */ + void delete(String containerName); } diff --git a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/features/ContainerAsyncApi.java b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/features/ContainerAsyncApi.java index 84cec5f6be..8e9c0763c6 100644 --- a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/features/ContainerAsyncApi.java +++ b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/features/ContainerAsyncApi.java @@ -26,6 +26,7 @@ import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; + import org.jclouds.rest.annotations.BinderParam; import org.jclouds.rest.annotations.ExceptionParser; import org.jclouds.rest.annotations.Headers; @@ -39,6 +40,7 @@ import org.jclouds.snia.cdmi.v1.filters.BasicAuthenticationAndTenantId; import org.jclouds.snia.cdmi.v1.filters.StripExtraAcceptHeader; import org.jclouds.snia.cdmi.v1.options.CreateContainerOptions; import org.jclouds.snia.cdmi.v1.queryparams.ContainerQueryParams; + import com.google.common.util.concurrent.ListenableFuture; /** @@ -49,115 +51,111 @@ import com.google.common.util.concurrent.ListenableFuture; * @see api doc */ @SkipEncoding({ '/', '=' }) -@RequestFilters({ BasicAuthenticationAndTenantId.class, - StripExtraAcceptHeader.class }) +@RequestFilters({ BasicAuthenticationAndTenantId.class, StripExtraAcceptHeader.class }) @Headers(keys = "X-CDMI-Specification-Version", values = "{jclouds.api-version}") public interface ContainerAsyncApi { - /** - * get CDMI Container - * - * @param containerName - * containerName must end with a forward slash, /. - * @return Container - * - *
-	 *  Examples: 
-	 *  {@code
-	 *  container = getContainer("myContainer/");
-	 *  container = getContainer("parentContainer/childContainer/");
-	 * }
-	 * 
-	 * 
-	 */
-	@GET
-	@Consumes({ ObjectTypes.CONTAINER, MediaType.APPLICATION_JSON })
-	@ExceptionParser(ReturnNullOnNotFoundOr404.class)
-	@Path("/{containerName}")
-	ListenableFuture getContainer(
-			@PathParam("containerName") String containerName);
+   /**
+    * get CDMI Container
+    * 
+    * @param containerName
+    *           containerName must end with a forward slash, /.
+    * @return Container
+    * 
+    *         
+    *  Examples: 
+    *  {@code
+    *  container = get("myContainer/");
+    *  container = get("parentContainer/childContainer/");
+    * }
+    * 
+    *         
+    */
+   @GET
+   @Consumes({ ObjectTypes.CONTAINER, MediaType.APPLICATION_JSON })
+   @ExceptionParser(ReturnNullOnNotFoundOr404.class)
+   @Path("/{containerName}")
+   ListenableFuture get(@PathParam("containerName") String containerName);
 
-	/**
-	 * get CDMI Container
-	 * 
-	 * @param containerName
-	 * @param queryParams
-	 *            enables getting only certain fields, metadata, children range
-	 * @return Container
-	 * 
-	 * 
-	 * Examples: 
-	 * {@code
-	 * container = getContainer("myContainer/",ContainerQueryParams.Builder.field("parentURI").field("objectName"))
-	 * container = getContainer("myContainer/",ContainerQueryParams.Builder.metadata().field("objectName"))
-	 * }
-	 * 
- * @see ContainerQueryParams - */ - @GET - @Consumes({ ObjectTypes.CONTAINER, MediaType.APPLICATION_JSON }) - @ExceptionParser(ReturnNullOnNotFoundOr404.class) - @Path("/{containerName}") - ListenableFuture getContainer( - @PathParam("containerName") String containerName, - @BinderParam(BindQueryParmsToSuffix.class) ContainerQueryParams queryParams); + /** + * get CDMI Container + * + * @param containerName + * @param queryParams + * enables getting only certain fields, metadata, children range + * @return Container + * + *
+    * Examples: 
+    * {@code
+    * container = get("myContainer/",ContainerQueryParams.Builder.field("parentURI").field("objectName"))
+    * container = get("myContainer/",ContainerQueryParams.Builder.metadata().field("objectName"))
+    * }
+    * 
+ * @see ContainerQueryParams + */ + @GET + @Consumes({ ObjectTypes.CONTAINER, MediaType.APPLICATION_JSON }) + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + @Path("/{containerName}") + ListenableFuture get(@PathParam("containerName") String containerName, + @BinderParam(BindQueryParmsToSuffix.class) ContainerQueryParams queryParams); - /** - * Create CDMI Container - * - * @param containerName - * containerName must end with a forward slash, /. - * @return Container - *
-	 *  Examples: 
-	 *  {@code
-	 *  container = createContainer("myContainer/");
-	 *  container = createContainer("parentContainer/childContainer/");
-	 *  }
-	 *  
- */ - @PUT - @Consumes({ ObjectTypes.CONTAINER, MediaType.APPLICATION_JSON }) - @Produces({ ObjectTypes.CONTAINER }) - @ExceptionParser(ReturnNullOnNotFoundOr404.class) - @Path("/{containerName}") - ListenableFuture createContainer( - @PathParam("containerName") String containerName); + /** + * Create CDMI Container + * + * @param containerName + * containerName must end with a forward slash, /. + * @return Container + * + *
+    *  Examples: 
+    *  {@code
+    *  container = create("myContainer/");
+    *  container = create("parentContainer/childContainer/");
+    *  }
+    * 
+ */ + @PUT + @Consumes({ ObjectTypes.CONTAINER, MediaType.APPLICATION_JSON }) + @Produces({ ObjectTypes.CONTAINER }) + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + @Path("/{containerName}") + ListenableFuture create(@PathParam("containerName") String containerName); - /** - * Create CDMI Container - * - * @param containerName - * @param options - * enables adding metadata - * @return Container - *
-	 *  Examples: 
-	 *  {@code
-	 *  container = createContainer("myContainer/",CreateContainerOptions.Builder..metadata(metaDataIn));
-	 *  }
-	 *  
- * @see CreateContainerOptions - */ - @PUT - @Consumes({ ObjectTypes.CONTAINER, MediaType.APPLICATION_JSON }) - @Produces({ ObjectTypes.CONTAINER }) - @ExceptionParser(ReturnNullOnNotFoundOr404.class) - @Path("/{containerName}") - ListenableFuture createContainer( - @PathParam("containerName") String containerName, - CreateContainerOptions... options); + /** + * Create CDMI Container + * + * @param containerName + * @param options + * enables adding metadata + * @return Container + * + *
+    *  Examples: 
+    *  {@code
+    *  container = create("myContainer/",CreateContainerOptions.Builder..metadata(metaDataIn));
+    *  }
+    * 
+ * @see CreateContainerOptions + */ + @PUT + @Consumes({ ObjectTypes.CONTAINER, MediaType.APPLICATION_JSON }) + @Produces({ ObjectTypes.CONTAINER }) + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + @Path("/{containerName}") + ListenableFuture create(@PathParam("containerName") String containerName, + CreateContainerOptions... options); - /** - * Delete Container - * - * @param containerName - */ - @DELETE - @Consumes(MediaType.APPLICATION_JSON) - @ExceptionParser(ReturnNullOnNotFoundOr404.class) - @Path("/{containerName}") - ListenableFuture deleteContainer( - @PathParam("containerName") String containerName); + /** + * Delete Container + * + * @param containerName + */ + @DELETE + @Consumes(MediaType.APPLICATION_JSON) + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + @Path("/{containerName}") + ListenableFuture delete(@PathParam("containerName") String containerName); } diff --git a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/features/DataApi.java b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/features/DataApi.java index c85a945240..935047ee07 100644 --- a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/features/DataApi.java +++ b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/features/DataApi.java @@ -19,6 +19,7 @@ package org.jclouds.snia.cdmi.v1.features; import java.util.concurrent.TimeUnit; + import org.jclouds.concurrent.Timeout; import org.jclouds.snia.cdmi.v1.domain.DataObject; import org.jclouds.snia.cdmi.v1.options.CreateDataObjectOptions; @@ -33,83 +34,86 @@ import org.jclouds.snia.cdmi.v1.queryparams.DataObjectQueryParams; */ @Timeout(duration = 180, timeUnit = TimeUnit.SECONDS) public interface DataApi { - /** - * get CDMI Data object - * - * @param containerName - * containerName must end with a forward slash, /. - * @param dataObjectName - * dataObjectName must not end with a forward slash, /. - * @return DataObject - *
-	 *  Examples: 
-	 *  {@code
-	 *  dataObject = getDataObject("myContainer/","myDataObject");
-	 *  dataObject = getDataObject("parentContainer/childContainer/","myDataObject");
-	 *  }
-	 *  
-	 */
-	DataObject getDataObject(String containerName, String dataObjectName);
-	/**
-	 * get CDMI Data object
-	 * 
-	 * @param containerName
-	 *            containerName must end with a forward slash, /.
-	 * @param dataObjectName
-	 *            dataObjectName must not end with a forward slash, /. 
-	 * @param queryParams 
-	 *            enables getting only certain fields, metadata, value range
-	 * @return DataObject
-	 *  
-	 *  Examples: 
-	 *  {@code
-	 *  dataObject = getContainer("myContainer/","myDataObject",ContainerQueryParams.Builder.field("parentURI").field("objectName"));
-	 *  dataObject = getContainer("myContainer/","myDataObject",ContainerQueryParams.Builder.value(0,10));
-	 *  }
-	 *  
-	 */
-	DataObject getDataObject(String containerName, String dataObjectName,
-			DataObjectQueryParams queryParams);
+   /**
+    * get CDMI Data object
+    * 
+    * 
+    * @param dataObjectName
+    *           dataObjectName must not end with a forward slash, /.
+    * @return DataObject
+    * 
+    *         
+    *  Examples: 
+    *  {@code
+    *  dataObject = get("myDataObject");
+    *  dataObject = get("parentContainer/childContainer","myDataObject");
+    * }
+    * 
+    *         
+    */
+   DataObject get(String dataObjectName);
 
-	/**
-	 * create CDMI Data object
-	 * 
-	 * @param containerName
-	 *            containerName must end with a forward slash, /.
-	 * @param dataObjectName
-	 *            dataObjectName must not end with a forward slash, /. 
-	 * @param options 
-	 *            enables defining the body i.e. metadata, mimetype, value
-	 * @return DataObject
-	 *  
-	 *  Examples: 
-	 *  {@code
-	 *  dataObject = createDataObject("myContainer/",
-	 *                                "myDataObject",
-	 *                                CreateDataObjectOptions.Builder
-	 *                                                    .value(value)
-	 *                                                    .mimetype("text/plain")
-	 *                                                    .metadata(pDataObjectMetaDataIn);
-	 *  }
-	 *  
-	 */	
-	DataObject createDataObject(String containerName, String dataObjectName,
-			CreateDataObjectOptions... options);
+   /**
+    * get CDMI Data object
+    * 
+    * 
+    * @param dataObjectName
+    *           dataObjectName must not end with a forward slash, /.
+    * @param queryParams
+    *           enables getting only certain fields, metadata, value range
+    * @return DataObject
+    * 
+    *         
+    *  Examples: 
+    *  {@code
+    *  dataObject = get("myDataObject",ContainerQueryParams.Builder.field("parentURI").field("objectName"));
+    *  dataObject = get("myDataObject",ContainerQueryParams.Builder.value(0,10));
+    * }
+    * 
+    *         
+    */
+   DataObject get(String dataObjectName, DataObjectQueryParams queryParams);
 
-	/**
-	 * delete CDMI Data object
-	 * 
-	 * @param containerName
-	 *            containerName must end with a forward slash, /.
-	 * @param  dataObjectName
-	 *            dataObjectName must not end with a forward slash, /.           
-	 *  
-	 *  Examples: 
-	 *  {@code
-	 *  deleteDataObject("myContainer/","myDataObject");
-	 *  }
-	 *  
-	 */
-	void deleteDataObject(String containerName, String dataObjectName);
+   /**
+    * create CDMI Data object
+    * 
+    * 
+    * @param dataObjectName
+    *           dataObjectName must not end with a forward slash, /.
+    * @param options
+    *           enables defining the body i.e. metadata, mimetype, value
+    * @return DataObject
+    * 
+    *         
+    *  Examples: 
+    *  {@code
+    *  dataObject = create(
+    *                                "myDataObject",
+    *                                CreateDataObjectOptions.Builder
+    *                                                    .value(value)
+    *                                                    .mimetype("text/plain")
+    *                                                    .metadata(pDataObjectMetaDataIn);
+    * }
+    * 
+    *         
+    */
+   DataObject create(String dataObjectName, CreateDataObjectOptions... options);
+
+   /**
+    * delete CDMI Data object
+    * 
+    * 
+    * @param dataObjectName
+    *           dataObjectName must not end with a forward slash, /.
+    * 
+    *           
+    *  Examples: 
+    *  {@code
+    *  delete("myDataObject");
+    * }
+    * 
+    *           
+    */
+   void delete(String dataObjectName);
 
 }
diff --git a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/features/DataAsyncApi.java b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/features/DataAsyncApi.java
index 7ae1216935..6fe8841bca 100644
--- a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/features/DataAsyncApi.java
+++ b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/features/DataAsyncApi.java
@@ -51,60 +51,48 @@ import com.google.common.util.concurrent.ListenableFuture;
  * @see api doc
  */
 @SkipEncoding({ '/', '=' })
-@RequestFilters({ BasicAuthenticationAndTenantId.class,
-		StripExtraAcceptHeader.class })
+@RequestFilters({ BasicAuthenticationAndTenantId.class, StripExtraAcceptHeader.class })
 @Headers(keys = "X-CDMI-Specification-Version", values = "{jclouds.api-version}")
 public interface DataAsyncApi {
-	/**
-	 * @see DataApi#getDataObject(String containerName, String dataObjectName)
-	 */
-	@GET
-	@Consumes({ ObjectTypes.DATAOBJECT, MediaType.APPLICATION_JSON })
-	@ExceptionParser(ReturnNullOnNotFoundOr404.class)
-	@Path("/{containerName}{dataObjectName}")
-	ListenableFuture getDataObject(
-			@PathParam("containerName") String containerName,
-			@PathParam("dataObjectName") String dataObjectName);
+   /**
+    * @see DataApi#get(String dataObjectName)
+    */
+   @GET
+   @Consumes({ ObjectTypes.DATAOBJECT, MediaType.APPLICATION_JSON })
+   @ExceptionParser(ReturnNullOnNotFoundOr404.class)
+   @Path("/{dataObjectName}")
+   ListenableFuture get(@PathParam("dataObjectName") String dataObjectName);
 
-	/**
-	 * @see DataApi#getDataObject(String containerName, String dataObjectName,
-	 *      DataObjectQueryParams queryParams)
-	 */
-	@GET
-	@Consumes({ ObjectTypes.DATAOBJECT, MediaType.APPLICATION_JSON })
-	@ExceptionParser(ReturnNullOnNotFoundOr404.class)
-	@Path("/{containerName}{dataObjectName}")
-	ListenableFuture getDataObject(
-			@PathParam("containerName") String containerName,
-			@PathParam("dataObjectName") String dataObjectName,
-			@BinderParam(BindQueryParmsToSuffix.class) DataObjectQueryParams queryParams);
+   /**
+    * @see DataApi#get(String dataObjectName, DataObjectQueryParams queryParams)
+    */
+   @GET
+   @Consumes({ ObjectTypes.DATAOBJECT, MediaType.APPLICATION_JSON })
+   @ExceptionParser(ReturnNullOnNotFoundOr404.class)
+   @Path("/{dataObjectName}")
+   ListenableFuture get(@PathParam("dataObjectName") String dataObjectName,
+            @BinderParam(BindQueryParmsToSuffix.class) DataObjectQueryParams queryParams);
 
-	/**
-	 * @see DataApi#createDataObject(String containerName, String
-	 *      dataObjectName, CreateDataObjectOptions... options)
-	 */
-	@PUT
-	@Consumes({ ObjectTypes.DATAOBJECT, MediaType.APPLICATION_JSON })
-	@Produces({ ObjectTypes.DATAOBJECT })
-	@ExceptionParser(ReturnNullOnNotFoundOr404.class)
-	@Path("/{containerName}{dataObjectName}")
-	ListenableFuture createDataObject(
-			@PathParam("containerName") String containerName,
-			@PathParam("dataObjectName") String dataObjectName,
-			CreateDataObjectOptions... options);
+   /**
+    * @see DataApi#create(String dataObjectName, CreateDataObjectOptions... options)
+    */
+   @PUT
+   @Consumes({ ObjectTypes.DATAOBJECT, MediaType.APPLICATION_JSON })
+   @Produces({ ObjectTypes.DATAOBJECT })
+   @ExceptionParser(ReturnNullOnNotFoundOr404.class)
+   @Path("/{dataObjectName}")
+   ListenableFuture create(@PathParam("dataObjectName") String dataObjectName,
+            CreateDataObjectOptions... options);
 
-	/**
-	 * @see DataApi#deleteDataObject(String containerName, String
-	 *      dataObjectName)
-	 */
-	@DELETE
-	@Consumes(MediaType.TEXT_PLAIN)
-	// note: MediaType.APPLICATION_JSON work also, however without consumes
-	// jclouds throws null exception
-	@ExceptionParser(ReturnNullOnNotFoundOr404.class)
-	@Path("/{containerName}{dataObjectName}")
-	ListenableFuture deleteDataObject(
-			@PathParam("containerName") String containerName,
-			@PathParam("dataObjectName") String dataObjectName);
+   /**
+    * @see DataApi#delete(String dataObjectName)
+    */
+   @DELETE
+   @Consumes(MediaType.TEXT_PLAIN)
+   // note: MediaType.APPLICATION_JSON work also, however without consumes
+   // jclouds throws null exception
+   @ExceptionParser(ReturnNullOnNotFoundOr404.class)
+   @Path("/{dataObjectName}")
+   ListenableFuture delete(@PathParam("dataObjectName") String dataObjectName);
 
 }
diff --git a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/features/DataNonCDMIContentTypeApi.java b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/features/DataNonCDMIContentTypeApi.java
index 91b797fe4f..593565e2c2 100644
--- a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/features/DataNonCDMIContentTypeApi.java
+++ b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/features/DataNonCDMIContentTypeApi.java
@@ -19,6 +19,7 @@
 package org.jclouds.snia.cdmi.v1.features;
 
 import java.util.concurrent.TimeUnit;
+
 import org.jclouds.concurrent.Timeout;
 import org.jclouds.io.Payload;
 import org.jclouds.snia.cdmi.v1.domain.DataObject;
@@ -33,172 +34,163 @@ import org.jclouds.snia.cdmi.v1.queryparams.DataObjectQueryParams;
  */
 @Timeout(duration = 600, timeUnit = TimeUnit.SECONDS)
 public interface DataNonCDMIContentTypeApi {
-	/**
-	 * get CDMI Data object
-	 * 
-	 * @param containerName
-	 *            containerName must end with a forward slash, /.
-	 * @param dataObjectName
-	 *            dataObjectName must not end with a forward slash, /.
-	 * @return DataObjectNonCDMIContentType
-	 * 
-	 *         
-	 *  Examples: 
-	 *  {@code
-	 *  dataObject = getDataObject("myContainer/","myDataObject");
-	 *  dataObject = getDataObject("parentContainer/childContainer/","myDataObject");
-	 * }
-	 * 
-	 * 
-	 * @see DataNonCDMIContentTypeAsyncApi#getDataObjectValue(String containerName, String dataObjectName)
-	 */
-	Payload getDataObjectValue(String containerName, String dataObjectName);
+   /**
+    * get CDMI Data object
+    * 
+    * @param containerName
+    *           containerName must end with a forward slash, /.
+    * @param dataObjectName
+    *           dataObjectName must not end with a forward slash, /.
+    * @return DataObjectNonCDMIContentType
+    * 
+    *         
+    *  Examples: 
+    *  {@code
+    *  dataObject = get("myDataObject");
+    *  dataObject = get("parentContainer/childContainer/","myDataObject");
+    * }
+    * 
+    * 
+    * @see DataNonCDMIContentTypeAsyncApi#getValue(String dataObjectName)
+    */
+   Payload getValue(String dataObjectName);
 
-	/**
-	 * get CDMI Data object
-	 * 
-	 * @param containerName
-	 *            containerName must end with a forward slash, /.
-	 * @param dataObjectName
-	 *            dataObjectName must not end with a forward slash, /.
-	 * @param range
-	 *            a valid ranges-specifier (see RFC2616 Section 14.35.1)
-	 * @return DataObjectNonCDMIContentType
-	 * 
-	 *         
-	 *  Examples: 
-	 *  {@code
-	 *  dataObject = getDataObject("myContainer/","myDataObject","bytes=0-10");
-	 * }
-	 * 
-	 *         
-	 */
-	Payload getDataObjectValue(String containerName, String dataObjectName,
-			String range);
+   /**
+    * get CDMI Data object
+    * 
+    * @param containerName
+    *           containerName must end with a forward slash, /.
+    * @param dataObjectName
+    *           dataObjectName must not end with a forward slash, /.
+    * @param range
+    *           a valid ranges-specifier (see RFC2616 Section 14.35.1)
+    * @return DataObjectNonCDMIContentType
+    * 
+    *         
+    *  Examples: 
+    *  {@code
+    *  dataObject = get("myDataObject","bytes=0-10");
+    * }
+    * 
+    *         
+    */
+   Payload getValue(String dataObjectName, String range);
 
-	/**
-	 * get CDMI Data object
-	 * 
-	 * @param containerName
-	 *            containerName must end with a forward slash, /.
-	 * @param dataObjectName
-	 *            dataObjectName must not end with a forward slash, /.
-	 * @param queryParams
-	 *            enables getting only certain fields, metadata, value range
-	 * @return DataObject
-	 * 
-	 *         
-	 *  Examples: 
-	 *  {@code
-	 *  dataObject = getContainer("myContainer/","myDataObject",ContainerQueryParams.Builder.field("parentURI").field("objectName"));
-	 *  dataObject = getContainer("myContainer/","myDataObject",ContainerQueryParams.Builder.value(0,10));
-	 * }
-	 * 
-	 *         
-	 */
-	DataObject getDataObject(String containerName, String dataObjectName,
-			DataObjectQueryParams queryParams);
+   /**
+    * get CDMI Data object
+    * 
+    * @param containerName
+    *           containerName must end with a forward slash, /.
+    * @param dataObjectName
+    *           dataObjectName must not end with a forward slash, /.
+    * @param queryParams
+    *           enables getting only certain fields, metadata, value range
+    * @return DataObject
+    * 
+    *         
+    *  Examples: 
+    *  {@code
+    *  dataObject = get("myDataObject",ContainerQueryParams.Builder.field("parentURI").field("objectName"));
+    *  dataObject = get("myDataObject",ContainerQueryParams.Builder.value(0,10));
+    * }
+    * 
+    *         
+    */
+   DataObject get(String dataObjectName, DataObjectQueryParams queryParams);
 
-	/**
-	 * create CDMI Data object Non CDMI Content Type
-	 * 
-	 * @param containerName
-	 *            containerName must end with a forward slash, /.
-	 * @param dataObjectName
-	 *            dataObjectName must not end with a forward slash, /.
-	 * @param payload
-	 *            enables defining the body's payload i.e. file, inputStream,
-	 *            String, ByteArray
-	 * 
-	 *            
-	 *  Examples: 
-	 *  {@code
-	 *  createDataObject("myContainer/","myDataObject",new StringPayload("value");
-	 *  createDataObject("myContainer/","myDataObject",new ByteArrayPayload(bytes);
-	 *  createDataObject("myContainer/","myDataObject",new FilePayload(myFileIn);
-	 *  createDataObject("myContainer/","myDataObject",new InputStreamPayload(is);
-	 *  
-	 *  File f = new File("yellow-flowers.jpg");
-	 *  payloadIn = new InputStreamPayload(new FileInputStream(f));
-	 *  payloadIn.setContentMetadata(BaseMutableContentMetadata.fromContentMetadata(
-	 *            payloadIn.getContentMetadata().toBuilder()
-	 *            .contentType(MediaType.JPEG.toString())
-	 *            .contentLength(new Long(inFile.length()))
-	 *            .build()));
-	 *  dataNonCDMIContentTypeApi.createDataObject(containerName, f.getName(),
-	 * 					payloadIn);
-	 * }
-	 * 
-	 *            
-	 */
-	void createDataObject(String containerName, String dataObjectName,
-			Payload payload);
+   /**
+    * create CDMI Data object Non CDMI Content Type
+    * 
+    * @param containerName
+    *           containerName must end with a forward slash, /.
+    * @param dataObjectName
+    *           dataObjectName must not end with a forward slash, /.
+    * @param payload
+    *           enables defining the body's payload i.e. file, inputStream, String, ByteArray
+    * 
+    *           
+    *  Examples: 
+    *  {@code
+    *  create("myDataObject",new StringPayload("value");
+    *  create("myDataObject",new ByteArrayPayload(bytes);
+    *  create("myDataObject",new FilePayload(myFileIn);
+    *  create("myDataObject",new InputStreamPayload(is);
+    *  
+    *  File f = new File("yellow-flowers.jpg");
+    *  payloadIn = new InputStreamPayload(new FileInputStream(f));
+    *  payloadIn.setContentMetadata(BaseMutableContentMetadata.fromContentMetadata(
+    *            payloadIn.getContentMetadata().toBuilder()
+    *            .contentType(MediaType.JPEG.toString())
+    *            .contentLength(new Long(inFile.length()))
+    *            .build()));
+    *  dataNonCDMIContentTypeApi.create(containerName, f.getName(),
+    * 					payloadIn);
+    * }
+    * 
+    *           
+    */
+   void create(String dataObjectName, Payload payload);
 
-	/**
-	 * create CDMI Data object partial Non CDMI Content Type Only part of the
-	 * object is contained in the payload and the X-CDMI-Partial header flag is
-	 * set to true
-	 * 
-	 * 
-	 * @param containerName
-	 *            containerName must end with a forward slash, /.
-	 * @param dataObjectName
-	 *            dataObjectName must not end with a forward slash, /.
-	 * @param payload
-	 *            enables defining the body's payload i.e. file, inputStream,
-	 *            String, ByteArray
-	 * 
-	 *            
-	 *  Examples: 
-	 *  {@code
-	 *  createDataObjectPartial("myContainer/","myDataObject",new StringPayload("value");
-	 *  createDataObjectPartial("myContainer/","myDataObject",new ByteArrayPayload(bytes);
-	 *  createDataObjectPartial("myContainer/","myDataObject",new FilePayload(myFileIn);
-	 *  createDataObjectPartial("myContainer/","myDataObject",new InputStreamPayload(is);
-	 * }
-	 * 
-	 *            
-	 */
-	void createDataObjectPartial(String containerName, String dataObjectName,
-			Payload payload);
+   /**
+    * create CDMI Data object partial Non CDMI Content Type Only part of the object is contained in
+    * the payload and the X-CDMI-Partial header flag is set to true
+    * 
+    * 
+    * 
+    * @param dataObjectName
+    *           dataObjectName must not end with a forward slash, /.
+    * @param payload
+    *           enables defining the body's payload i.e. file, inputStream, String, ByteArray
+    * 
+    *           
+    *  Examples: 
+    *  {@code
+    *  createPartial("myDataObject",new StringPayload("value");
+    *  createPartial("myDataObject",new ByteArrayPayload(bytes);
+    *  createPartial("myDataObject",new FilePayload(myFileIn);
+    *  createPartial("myDataObject",new InputStreamPayload(is);
+    * }
+    * 
+    *           
+    */
+   void createPartial(String dataObjectName, Payload payload);
 
-	/**
-	 * create CDMI Data object Non CDMI Content Type
-	 * 
-	 * @param containerName
-	 *            containerName must end with a forward slash, /.
-	 * @param dataObjectName
-	 *            dataObjectName must not end with a forward slash, /.
-	 * @param inputString
-	 *            simple string input
-	 * 
-	 *            
-	 *  Examples: 
-	 *  {@code
-	 *  createDataObject("myContainer/","myDataObject",new String("value");
-	 * }
-	 * 
-	 *            
-	 */
-	void createDataObject(String containerName, String dataObjectName,
-			String inputString);
+   /**
+    * create CDMI Data object Non CDMI Content Type
+    * 
+    * @param containerName
+    *           containerName must end with a forward slash, /.
+    * @param dataObjectName
+    *           dataObjectName must not end with a forward slash, /.
+    * @param inputString
+    *           simple string input
+    * 
+    *           
+    *  Examples: 
+    *  {@code
+    *  create("myDataObject",new String("value");
+    * }
+    * 
+    *           
+    */
+   void create(String dataObjectName, String inputString);
 
-	/**
-	 * delete CDMI Data object
-	 * 
-	 * @param containerName
-	 *            containerName must end with a forward slash, /.
-	 * @param dataObjectName
-	 *            dataObjectName must not end with a forward slash, /.
-	 * 
-	 *            
-	 *  Examples: 
-	 *  {@code
-	 *  deleteDataObject("myContainer/","myDataObject");
-	 * }
-	 * 
-	 *            
-	 */
-	void deleteDataObject(String containerName, String dataObjectName);
+   /**
+    * delete CDMI Data object
+    * 
+    * @param containerName
+    *           containerName must end with a forward slash, /.
+    * @param dataObjectName
+    *           dataObjectName must not end with a forward slash, /.
+    * 
+    *           
+    *  Examples: 
+    *  {@code
+    *  delete("myDataObject");
+    * }
+    * 
+    *           
+    */
+   void delete(String dataObjectName);
 
 }
diff --git a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/features/DataNonCDMIContentTypeAsyncApi.java b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/features/DataNonCDMIContentTypeAsyncApi.java
index f44630d713..b58f80b472 100644
--- a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/features/DataNonCDMIContentTypeAsyncApi.java
+++ b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/features/DataNonCDMIContentTypeAsyncApi.java
@@ -21,15 +21,17 @@ package org.jclouds.snia.cdmi.v1.features;
 import javax.ws.rs.Consumes;
 import javax.ws.rs.DELETE;
 import javax.ws.rs.GET;
+import javax.ws.rs.HeaderParam;
 import javax.ws.rs.PUT;
 import javax.ws.rs.Path;
 import javax.ws.rs.PathParam;
 import javax.ws.rs.Produces;
-import javax.ws.rs.HeaderParam;
 import javax.ws.rs.core.MediaType;
+
 import org.jclouds.rest.annotations.BinderParam;
 import org.jclouds.rest.annotations.ExceptionParser;
 import org.jclouds.rest.annotations.Headers;
+import org.jclouds.rest.annotations.Payload;
 import org.jclouds.rest.annotations.PayloadParam;
 import org.jclouds.rest.annotations.RequestFilters;
 import org.jclouds.rest.annotations.ResponseParser;
@@ -39,10 +41,10 @@ import org.jclouds.snia.cdmi.v1.binders.BindQueryParmsToSuffix;
 import org.jclouds.snia.cdmi.v1.domain.DataObject;
 import org.jclouds.snia.cdmi.v1.filters.BasicAuthenticationAndTenantId;
 import org.jclouds.snia.cdmi.v1.filters.StripExtraAcceptHeader;
-import org.jclouds.snia.cdmi.v1.queryparams.DataObjectQueryParams;
 import org.jclouds.snia.cdmi.v1.functions.ParseObjectFromHeadersAndHttpContent;
+import org.jclouds.snia.cdmi.v1.queryparams.DataObjectQueryParams;
+
 import com.google.common.util.concurrent.ListenableFuture;
-import org.jclouds.rest.annotations.Payload;
 
 /**
  * Non CDMI Content Type Data Object Resource Operations
@@ -53,103 +55,79 @@ import org.jclouds.rest.annotations.Payload;
  * @see api doc
  */
 @SkipEncoding({ '/', '=' })
-@RequestFilters({ BasicAuthenticationAndTenantId.class,
-		StripExtraAcceptHeader.class })
+@RequestFilters({ BasicAuthenticationAndTenantId.class, StripExtraAcceptHeader.class })
 public interface DataNonCDMIContentTypeAsyncApi {
-	/**
-	 * @see DataNonCDMIContentTypeApi#getDataObjectValue(String containerName,
-	 *      String dataObjectName)
-	 */
-	@GET
-	@Consumes(MediaType.MEDIA_TYPE_WILDCARD)
-	@ResponseParser(ParseObjectFromHeadersAndHttpContent.class)
-	@ExceptionParser(ReturnNullOnNotFoundOr404.class)
-	@Path("/{containerName}{dataObjectName}")
-	ListenableFuture getDataObjectValue(
-			@PathParam("containerName") String containerName,
-			@PathParam("dataObjectName") String dataObjectName);
+   /**
+    * @see DataNonCDMIContentTypeApi#getValue(String dataObjectName)
+    */
+   @GET
+   @Consumes(MediaType.MEDIA_TYPE_WILDCARD)
+   @ResponseParser(ParseObjectFromHeadersAndHttpContent.class)
+   @ExceptionParser(ReturnNullOnNotFoundOr404.class)
+   @Path("/{dataObjectName}")
+   ListenableFuture getValue(@PathParam("dataObjectName") String dataObjectName);
 
-	/**
-	 * @see DataNonCDMIContentTypeApi#getDataObjectValue(String containerName,
-	 *      String dataObjectName, String range )
-	 */
+   /**
+    * @see DataNonCDMIContentTypeApi#getValue(String dataObjectName, String range )
+    */
 
-	@GET
-	@Consumes(MediaType.MEDIA_TYPE_WILDCARD)
-	@ResponseParser(ParseObjectFromHeadersAndHttpContent.class)
-	@ExceptionParser(ReturnNullOnNotFoundOr404.class)
-	@Path("/{containerName}{dataObjectName}")
-	ListenableFuture getDataObjectValue(
-			@PathParam("containerName") String containerName,
-			@PathParam("dataObjectName") String dataObjectName,
-			@HeaderParam("Range") String range);
+   @GET
+   @Consumes(MediaType.MEDIA_TYPE_WILDCARD)
+   @ResponseParser(ParseObjectFromHeadersAndHttpContent.class)
+   @ExceptionParser(ReturnNullOnNotFoundOr404.class)
+   @Path("/{dataObjectName}")
+   ListenableFuture getValue(@PathParam("dataObjectName") String dataObjectName,
+            @HeaderParam("Range") String range);
 
-	/**
-	 * @see DataNonCDMIContentTypeApi#getDataObject(String containerName, String
-	 *      dataObjectName, DataObjectQueryParams queryParams )
-	 */
-	@GET
-	@Consumes(MediaType.APPLICATION_JSON)
-	@ExceptionParser(ReturnNullOnNotFoundOr404.class)
-	@Path("/{containerName}{dataObjectName}")
-	ListenableFuture getDataObject(
-			@PathParam("containerName") String containerName,
-			@PathParam("dataObjectName") String dataObjectName,
-			@BinderParam(BindQueryParmsToSuffix.class) DataObjectQueryParams queryParams);
+   /**
+    * @see DataNonCDMIContentTypeApi#get(String dataObjectName, DataObjectQueryParams queryParams )
+    */
+   @GET
+   @Consumes(MediaType.APPLICATION_JSON)
+   @ExceptionParser(ReturnNullOnNotFoundOr404.class)
+   @Path("/{dataObjectName}")
+   ListenableFuture get(@PathParam("dataObjectName") String dataObjectName,
+            @BinderParam(BindQueryParmsToSuffix.class) DataObjectQueryParams queryParams);
 
-	/**
-	 * @see DataNonCDMIContentTypeApi#createDataObject(String containerName,
-	 *      String dataObjectName, org.jclouds.io.Payload payload )
-	 */
-	@PUT
-	@Consumes(MediaType.MEDIA_TYPE_WILDCARD)
-	@ExceptionParser(ReturnNullOnNotFoundOr404.class)
-	@Path("/{containerName}{dataObjectName}")
-	ListenableFuture createDataObject(
-			@PathParam("containerName") String containerName,
-			@PathParam("dataObjectName") String dataObjectName,
-			org.jclouds.io.Payload payload);
+   /**
+    * @see DataNonCDMIContentTypeApi#create(String dataObjectName, org.jclouds.io.Payload payload )
+    */
+   @PUT
+   @Consumes(MediaType.MEDIA_TYPE_WILDCARD)
+   @ExceptionParser(ReturnNullOnNotFoundOr404.class)
+   @Path("/{dataObjectName}")
+   ListenableFuture create(@PathParam("dataObjectName") String dataObjectName, org.jclouds.io.Payload payload);
 
-	/**
-	 * @see DataNonCDMIContentTypeApi#createDataObjectPartial(String
-	 *      containerName, String dataObjectName, org.jclouds.io.Payload payload
-	 *      )
-	 */
-	@PUT
-	@Consumes(MediaType.MEDIA_TYPE_WILDCARD)
-	@ExceptionParser(ReturnNullOnNotFoundOr404.class)
-	@Path("/{containerName}{dataObjectName}")
-	@Headers(keys = "X-CDMI-Partial", values = "true")
-	ListenableFuture createDataObjectPartial(
-			@PathParam("containerName") String containerName,
-			@PathParam("dataObjectName") String dataObjectName,
-			org.jclouds.io.Payload payload);
+   /**
+    * @see DataNonCDMIContentTypeApi#createPartial(String dataObjectName, org.jclouds.io.Payload
+    *      payload )
+    */
+   @PUT
+   @Consumes(MediaType.MEDIA_TYPE_WILDCARD)
+   @ExceptionParser(ReturnNullOnNotFoundOr404.class)
+   @Path("/{dataObjectName}")
+   @Headers(keys = "X-CDMI-Partial", values = "true")
+   ListenableFuture createPartial(@PathParam("dataObjectName") String dataObjectName,
+            org.jclouds.io.Payload payload);
 
-	/**
-	 * @see DataNonCDMIContentTypeApi#createDataObject(String containerName,
-	 *      String dataObjectName, String input )
-	 */
-	@PUT
-	@Consumes(MediaType.MEDIA_TYPE_WILDCARD)
-	@Produces(MediaType.TEXT_PLAIN)
-	@ExceptionParser(ReturnNullOnNotFoundOr404.class)
-	@Path("/{containerName}{dataObjectName}")
-	@Payload("{input}")
-	ListenableFuture createDataObject(
-			@PathParam("containerName") String containerName,
-			@PathParam("dataObjectName") String dataObjectName,
-			@PayloadParam("input") String input);
+   /**
+    * @see DataNonCDMIContentTypeApi#create(String dataObjectName, String input )
+    */
+   @PUT
+   @Consumes(MediaType.MEDIA_TYPE_WILDCARD)
+   @Produces(MediaType.TEXT_PLAIN)
+   @ExceptionParser(ReturnNullOnNotFoundOr404.class)
+   @Path("/{dataObjectName}")
+   @Payload("{input}")
+   ListenableFuture create(@PathParam("dataObjectName") String dataObjectName, @PayloadParam("input") String input);
 
-	/**
-	 * @see DataNonCDMIContentTypeApi#deleteDataObject(String containerName,
-	 *      String dataObjectName)
-	 */
-	@DELETE
-	@Consumes(MediaType.MEDIA_TYPE_WILDCARD)
-	@ExceptionParser(ReturnNullOnNotFoundOr404.class)
-	@Path("/{containerName}{dataObjectName}")
-	ListenableFuture deleteDataObject(
-			@PathParam("containerName") String containerName,
-			@PathParam("dataObjectName") String dataObjectName);
+   /**
+    * @see DataNonCDMIContentTypeApi#delete(String dataObjectName)
+    */
+   @DELETE
+   @Consumes(MediaType.MEDIA_TYPE_WILDCARD)
+   @ExceptionParser(ReturnNullOnNotFoundOr404.class)
+   @Path("/{dataObjectName}")
+   ListenableFuture delete(@PathParam("dataObjectName") String dataObjectName);
 
 }
diff --git a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/features/DomainApi.java b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/features/DomainApi.java
index e224e0f7ea..f3e671a260 100644
--- a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/features/DomainApi.java
+++ b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/features/DomainApi.java
@@ -32,5 +32,4 @@ import org.jclouds.concurrent.Timeout;
 @Timeout(duration = 180, timeUnit = TimeUnit.SECONDS)
 public interface DomainApi {
 
-
 }
diff --git a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/features/DomainAsyncApi.java b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/features/DomainAsyncApi.java
index 257a93c06d..78c93fd4c8 100644
--- a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/features/DomainAsyncApi.java
+++ b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/features/DomainAsyncApi.java
@@ -31,10 +31,9 @@ import org.jclouds.snia.cdmi.v1.filters.StripExtraAcceptHeader;
  * @author Adrian Cole
  * @see api doc
  */
-@SkipEncoding( { '/', '=' })
-@RequestFilters( { BasicAuthenticationAndTenantId.class, StripExtraAcceptHeader.class })
-@Headers(keys="X-CDMI-Specification-Version", values = "{jclouds.api-version}")
+@SkipEncoding({ '/', '=' })
+@RequestFilters({ BasicAuthenticationAndTenantId.class, StripExtraAcceptHeader.class })
+@Headers(keys = "X-CDMI-Specification-Version", values = "{jclouds.api-version}")
 public interface DomainAsyncApi {
 
-
 }
diff --git a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/filters/StripExtraAcceptHeader.java b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/filters/StripExtraAcceptHeader.java
index 332ff0f4ff..7380d17768 100644
--- a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/filters/StripExtraAcceptHeader.java
+++ b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/filters/StripExtraAcceptHeader.java
@@ -34,7 +34,7 @@ import org.jclouds.http.HttpRequestFilter;
  */
 @Singleton
 public class StripExtraAcceptHeader implements HttpRequestFilter {
- 
+
    @Override
    public HttpRequest filter(HttpRequest request) throws HttpException {
       return request.toBuilder().replaceHeader("Accept", request.getFirstHeaderOrNull("Accept")).build();
diff --git a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/functions/ParseObjectFromHeadersAndHttpContent.java b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/functions/ParseObjectFromHeadersAndHttpContent.java
index 631b5849c8..21b52e3853 100644
--- a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/functions/ParseObjectFromHeadersAndHttpContent.java
+++ b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/functions/ParseObjectFromHeadersAndHttpContent.java
@@ -30,17 +30,16 @@ import com.google.common.base.Function;
  * 
  * @author Kenneth Nagin
  */
-public class ParseObjectFromHeadersAndHttpContent implements
-		Function,
-		InvocationContext {
+public class ParseObjectFromHeadersAndHttpContent implements Function,
+         InvocationContext {
 
-	public Payload apply(HttpResponse from) {
-		Payload object = from.getPayload();
-		return object;
-	}
+   public Payload apply(HttpResponse from) {
+      Payload object = from.getPayload();
+      return object;
+   }
 
-	@Override
-	public ParseObjectFromHeadersAndHttpContent setContext(HttpRequest request) {
-		return this;
-	}
+   @Override
+   public ParseObjectFromHeadersAndHttpContent setContext(HttpRequest request) {
+      return this;
+   }
 }
diff --git a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/options/CreateCDMIObjectOptions.java b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/options/CreateCDMIObjectOptions.java
index 47ca431c86..7fcdfc37b3 100644
--- a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/options/CreateCDMIObjectOptions.java
+++ b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/options/CreateCDMIObjectOptions.java
@@ -8,34 +8,32 @@ import org.jclouds.http.options.BaseHttpRequestOptions;
 import com.google.gson.JsonObject;
 
 /**
- * Contains options supported in the REST API for the CREATE container
- * operation. 

+ * Contains options supported in the REST API for the CREATE container operation.

* * @author Kenneth Nagin */ public class CreateCDMIObjectOptions extends BaseHttpRequestOptions { - protected JsonObject jsonObjectBody = new JsonObject(); - /** - * A name-value pair to associate with the container as metadata. - */ - public CreateCDMIObjectOptions metadata(Map metadata) { - JsonObject jsonObjectMetadata = new JsonObject(); - if (metadata != null) { - for (Entry entry : metadata.entrySet()) { - jsonObjectMetadata - .addProperty(entry.getKey(), entry.getValue()); - } - } - jsonObjectBody.add("metadata", jsonObjectMetadata); - this.payload = jsonObjectBody.toString(); - return this; - } + protected JsonObject jsonObjectBody = new JsonObject(); - public static class Builder { - public static CreateCDMIObjectOptions withMetadata( - Map metadata) { - CreateCDMIObjectOptions options = new CreateCDMIObjectOptions(); - return (CreateCDMIObjectOptions) options.metadata(metadata); - } - } + /** + * A name-value pair to associate with the container as metadata. + */ + public CreateCDMIObjectOptions metadata(Map metadata) { + JsonObject jsonObjectMetadata = new JsonObject(); + if (metadata != null) { + for (Entry entry : metadata.entrySet()) { + jsonObjectMetadata.addProperty(entry.getKey(), entry.getValue()); + } + } + jsonObjectBody.add("metadata", jsonObjectMetadata); + this.payload = jsonObjectBody.toString(); + return this; + } + + public static class Builder { + public static CreateCDMIObjectOptions withMetadata(Map metadata) { + CreateCDMIObjectOptions options = new CreateCDMIObjectOptions(); + return (CreateCDMIObjectOptions) options.metadata(metadata); + } + } } diff --git a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/options/CreateContainerOptions.java b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/options/CreateContainerOptions.java index 39d60c7d0f..de76fe4461 100644 --- a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/options/CreateContainerOptions.java +++ b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/options/CreateContainerOptions.java @@ -8,19 +8,19 @@ import java.util.Map; * @author Kenneth Nagin */ public class CreateContainerOptions extends CreateCDMIObjectOptions { - /** - * A name-value pair to associate with the container as metadata. - */ - public CreateContainerOptions metadata(Map metadata) { - super.metadata(metadata); - return this; - - } - public static class Builder { - public static CreateContainerOptions metadata( - Map metadata) { - CreateContainerOptions options = new CreateContainerOptions(); - return (CreateContainerOptions) options.metadata(metadata); - } - } + /** + * A name-value pair to associate with the container as metadata. + */ + public CreateContainerOptions metadata(Map metadata) { + super.metadata(metadata); + return this; + + } + + public static class Builder { + public static CreateContainerOptions metadata(Map metadata) { + CreateContainerOptions options = new CreateContainerOptions(); + return (CreateContainerOptions) options.metadata(metadata); + } + } } diff --git a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/options/CreateDataObjectNonCDMIOptions.java b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/options/CreateDataObjectNonCDMIOptions.java index 5ca397f403..2e0575072f 100644 --- a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/options/CreateDataObjectNonCDMIOptions.java +++ b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/options/CreateDataObjectNonCDMIOptions.java @@ -3,30 +3,24 @@ package org.jclouds.snia.cdmi.v1.options; import org.jclouds.http.options.BaseHttpRequestOptions; /** - * Contains options supported in the REST API for the CREATE container - * operation.

+ * Contains options supported in the REST API for the CREATE container operation.

* * @author Kenneth Nagin */ public class CreateDataObjectNonCDMIOptions extends BaseHttpRequestOptions { - /** - * A name-value pair to associate with the container as metadata. - */ - public CreateDataObjectNonCDMIOptions withStringPayload(String value) { - this.payload = value; - return this; - } - + /** + * A name-value pair to associate with the container as metadata. + */ + public CreateDataObjectNonCDMIOptions withStringPayload(String value) { + this.payload = value; + return this; + } - + public static class Builder { + public static CreateDataObjectNonCDMIOptions withStringPayload(String value) { + CreateDataObjectNonCDMIOptions options = new CreateDataObjectNonCDMIOptions(); + return (CreateDataObjectNonCDMIOptions) options.withStringPayload(value); + } - public static class Builder { - public static CreateDataObjectNonCDMIOptions withStringPayload( - String value) { - CreateDataObjectNonCDMIOptions options = new CreateDataObjectNonCDMIOptions(); - return (CreateDataObjectNonCDMIOptions) options.withStringPayload(value); - } - - - } + } } diff --git a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/options/CreateDataObjectOptions.java b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/options/CreateDataObjectOptions.java index b0738fba9c..3461db7a01 100644 --- a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/options/CreateDataObjectOptions.java +++ b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/options/CreateDataObjectOptions.java @@ -3,208 +3,192 @@ package org.jclouds.snia.cdmi.v1.options; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.File; +import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; -import java.io.IOException; -import java.util.Map; -import com.google.common.base.Charsets; import java.nio.charset.Charset; +import java.util.Map; + +import com.google.common.base.Charsets; import com.google.common.io.CharStreams; import com.google.common.io.Files; /** - * CreateDataObjectOptions options supported in the REST API for the CREATE CDMI - * Data Object operation.

+ * CreateDataObjectOptions options supported in the REST API for the CREATE CDMI Data Object + * operation.

* * @author Kenneth Nagin */ public class CreateDataObjectOptions extends CreateCDMIObjectOptions { - public CreateDataObjectOptions() { - jsonObjectBody.addProperty("value", new String()); - } + public CreateDataObjectOptions() { + jsonObjectBody.addProperty("value", new String()); + } - /** - * Create CDMI data object with metadata - * - * @param metadata - * @return CreateDataObjectOptions - */ - public CreateDataObjectOptions metadata(Map metadata) { - super.metadata(metadata); - return this; - } + /** + * Create CDMI data object with metadata + * + * @param metadata + * @return CreateDataObjectOptions + */ + public CreateDataObjectOptions metadata(Map metadata) { + super.metadata(metadata); + return this; + } - /** - * Create CDMI data object with mimetype - * - * @param mimetype - * @return CreateDataObjectOptions - */ - public CreateDataObjectOptions mimetype(String mimetype) { - jsonObjectBody.addProperty("mimetype", mimetype); - this.payload = jsonObjectBody.toString(); - return this; - } + /** + * Create CDMI data object with mimetype + * + * @param mimetype + * @return CreateDataObjectOptions + */ + public CreateDataObjectOptions mimetype(String mimetype) { + jsonObjectBody.addProperty("mimetype", mimetype); + this.payload = jsonObjectBody.toString(); + return this; + } - /** - * Create CDMI data object with value equal to empty string - * - * @return CreateDataObjectOptions - */ - public CreateDataObjectOptions value() { - this.payload = jsonObjectBody.toString(); - return this; - } + /** + * Create CDMI data object with value equal to empty string + * + * @return CreateDataObjectOptions + */ + public CreateDataObjectOptions value() { + this.payload = jsonObjectBody.toString(); + return this; + } - /** - * Create CDMI data object with String value - * - * @param value - * String value - * @return CreateDataObjectOptions - */ - public CreateDataObjectOptions value(String value) { - jsonObjectBody.addProperty("value", (value == null) ? new String() - : value); - this.payload = jsonObjectBody.toString(); - return this; - } + /** + * Create CDMI data object with String value + * + * @param value + * String value + * @return CreateDataObjectOptions + */ + public CreateDataObjectOptions value(String value) { + jsonObjectBody.addProperty("value", (value == null) ? new String() : value); + this.payload = jsonObjectBody.toString(); + return this; + } - /** - * Create CDMI data object with byte array value - * - * @param value - * byte array value byte array is converted to a String value - * @return CreateDataObjectOptions - */ - public CreateDataObjectOptions value(byte[] value) throws IOException { - jsonObjectBody.addProperty("value", - (value == null) ? new String() : new DataInputStream( - new ByteArrayInputStream(value)).readUTF()); - this.payload = jsonObjectBody.toString(); - return this; - } + /** + * Create CDMI data object with byte array value + * + * @param value + * byte array value byte array is converted to a String value + * @return CreateDataObjectOptions + */ + public CreateDataObjectOptions value(byte[] value) throws IOException { + jsonObjectBody.addProperty("value", (value == null) ? new String() : new DataInputStream( + new ByteArrayInputStream(value)).readUTF()); + this.payload = jsonObjectBody.toString(); + return this; + } - /** - * Create CDMI data object with file value - * - * @param value - * File File is converted to a String value with charset UTF_8 - * @return CreateDataObjectOptions - */ - public CreateDataObjectOptions value(File value) throws IOException { - jsonObjectBody.addProperty("value", (value == null) ? new String() - : Files.toString(value, Charsets.UTF_8)); - this.payload = jsonObjectBody.toString(); - return this; - } + /** + * Create CDMI data object with file value + * + * @param value + * File File is converted to a String value with charset UTF_8 + * @return CreateDataObjectOptions + */ + public CreateDataObjectOptions value(File value) throws IOException { + jsonObjectBody.addProperty("value", (value == null) ? new String() : Files.toString(value, Charsets.UTF_8)); + this.payload = jsonObjectBody.toString(); + return this; + } - /** - * Create CDMI data object with file value - * - * @param value - * File - * @param charset - * character set of file File is converted to a String value - * @return CreateDataObjectOptions - */ - public CreateDataObjectOptions value(File value, Charset charset) - throws IOException { - jsonObjectBody.addProperty("value", (value == null) ? new String() - : Files.toString(value, charset)); - this.payload = jsonObjectBody.toString(); - return this; - } + /** + * Create CDMI data object with file value + * + * @param value + * File + * @param charset + * character set of file File is converted to a String value + * @return CreateDataObjectOptions + */ + public CreateDataObjectOptions value(File value, Charset charset) throws IOException { + jsonObjectBody.addProperty("value", (value == null) ? new String() : Files.toString(value, charset)); + this.payload = jsonObjectBody.toString(); + return this; + } - /** - * Create CDMI data object with InputStream value - * - * @param value - * InputSteam InputSteam is converted to a String value with - * charset UTF_8 - * @return CreateDataObjectOptions - */ - public CreateDataObjectOptions value(InputStream value) throws IOException { - jsonObjectBody - .addProperty( - "value", - (value == null) ? new String() : CharStreams - .toString(new InputStreamReader(value, - Charsets.UTF_8))); - this.payload = jsonObjectBody.toString(); - return this; - } + /** + * Create CDMI data object with InputStream value + * + * @param value + * InputSteam InputSteam is converted to a String value with charset UTF_8 + * @return CreateDataObjectOptions + */ + public CreateDataObjectOptions value(InputStream value) throws IOException { + jsonObjectBody.addProperty("value", + (value == null) ? new String() : CharStreams.toString(new InputStreamReader(value, Charsets.UTF_8))); + this.payload = jsonObjectBody.toString(); + return this; + } - /** - * Create CDMI data object with InputStream value - * - * @param value - * InputSteam - * @param charset - * character set of input stream InputSteam is converted to a - * String value with charset UTF_8 - * @return CreateDataObjectOptions - */ - public CreateDataObjectOptions value(InputStream value, Charset charset) - throws IOException { - jsonObjectBody.addProperty("value", (value == null) ? new String() - : CharStreams.toString(new InputStreamReader(value, charset))); - this.payload = jsonObjectBody.toString(); - return this; - } + /** + * Create CDMI data object with InputStream value + * + * @param value + * InputSteam + * @param charset + * character set of input stream InputSteam is converted to a String value with charset + * UTF_8 + * @return CreateDataObjectOptions + */ + public CreateDataObjectOptions value(InputStream value, Charset charset) throws IOException { + jsonObjectBody.addProperty("value", + (value == null) ? new String() : CharStreams.toString(new InputStreamReader(value, charset))); + this.payload = jsonObjectBody.toString(); + return this; + } - public static class Builder { - public static CreateDataObjectOptions metadata( - Map metadata) { - CreateDataObjectOptions options = new CreateDataObjectOptions(); - return (CreateDataObjectOptions) options.metadata(metadata); - } + public static class Builder { + public static CreateDataObjectOptions metadata(Map metadata) { + CreateDataObjectOptions options = new CreateDataObjectOptions(); + return (CreateDataObjectOptions) options.metadata(metadata); + } - public static CreateDataObjectOptions mimetype(String mimetype) { - CreateDataObjectOptions options = new CreateDataObjectOptions(); - return (CreateDataObjectOptions) options.mimetype(mimetype); - } + public static CreateDataObjectOptions mimetype(String mimetype) { + CreateDataObjectOptions options = new CreateDataObjectOptions(); + return (CreateDataObjectOptions) options.mimetype(mimetype); + } - public static CreateDataObjectOptions value() { - CreateDataObjectOptions options = new CreateDataObjectOptions(); - return (CreateDataObjectOptions) options.value(); - } + public static CreateDataObjectOptions value() { + CreateDataObjectOptions options = new CreateDataObjectOptions(); + return (CreateDataObjectOptions) options.value(); + } - public static CreateDataObjectOptions value(String value) { - CreateDataObjectOptions options = new CreateDataObjectOptions(); - return (CreateDataObjectOptions) options.value(value); - } + public static CreateDataObjectOptions value(String value) { + CreateDataObjectOptions options = new CreateDataObjectOptions(); + return (CreateDataObjectOptions) options.value(value); + } - public static CreateDataObjectOptions value(byte[] value) - throws IOException { - CreateDataObjectOptions options = new CreateDataObjectOptions(); - return (CreateDataObjectOptions) options.value(value); - } + public static CreateDataObjectOptions value(byte[] value) throws IOException { + CreateDataObjectOptions options = new CreateDataObjectOptions(); + return (CreateDataObjectOptions) options.value(value); + } - public static CreateDataObjectOptions value(File value) - throws IOException { - CreateDataObjectOptions options = new CreateDataObjectOptions(); - return (CreateDataObjectOptions) options.value(value); - } + public static CreateDataObjectOptions value(File value) throws IOException { + CreateDataObjectOptions options = new CreateDataObjectOptions(); + return (CreateDataObjectOptions) options.value(value); + } - public static CreateDataObjectOptions value(File value, Charset charset) - throws IOException { - CreateDataObjectOptions options = new CreateDataObjectOptions(); - return (CreateDataObjectOptions) options.value(value, charset); - } + public static CreateDataObjectOptions value(File value, Charset charset) throws IOException { + CreateDataObjectOptions options = new CreateDataObjectOptions(); + return (CreateDataObjectOptions) options.value(value, charset); + } - public static CreateDataObjectOptions value(InputStream value) - throws IOException { - CreateDataObjectOptions options = new CreateDataObjectOptions(); - return (CreateDataObjectOptions) options.value(value); - } + public static CreateDataObjectOptions value(InputStream value) throws IOException { + CreateDataObjectOptions options = new CreateDataObjectOptions(); + return (CreateDataObjectOptions) options.value(value); + } - public static CreateDataObjectOptions value(InputStream value, - Charset charset) throws IOException { - CreateDataObjectOptions options = new CreateDataObjectOptions(); - return (CreateDataObjectOptions) options.value(value, charset); - } + public static CreateDataObjectOptions value(InputStream value, Charset charset) throws IOException { + CreateDataObjectOptions options = new CreateDataObjectOptions(); + return (CreateDataObjectOptions) options.value(value, charset); + } - } + } } diff --git a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/options/GetCDMIObjectOptions.java b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/options/GetCDMIObjectOptions.java index 0a36e15508..01d5f68b26 100644 --- a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/options/GetCDMIObjectOptions.java +++ b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/options/GetCDMIObjectOptions.java @@ -3,80 +3,77 @@ package org.jclouds.snia.cdmi.v1.options; import org.jclouds.http.options.BaseHttpRequestOptions; /** - * Optional get CDMI object options Note: We use - * BaseHttpRequestOptions.pathSuffix to include the CDMI query parameters rather - * than queryParam or MatrixParam because the CDMI specification is not - * following the standard usage. This is the summary of the CDMI specification: - * To read one or more requested fields from an existing CDMI container object, - * one of the following requests shall be performed: - * GET ///?;;... - * GET ///?children:;... - * GET ///?metadata:;... + * Optional get CDMI object options Note: We use BaseHttpRequestOptions.pathSuffix to include the + * CDMI query parameters rather than queryParam or MatrixParam because the CDMI specification is not + * following the standard usage. This is the summary of the CDMI specification: To read one or more + * requested fields from an existing CDMI container object, one of the following requests shall be + * performed: GET ///?;;... GET + * ///?children:;... GET ///?metadata:;... * - * For example: GET /MyContainer/?parentURI;children HTTP/1.1 - * GET /MyContainer/?childrenrange;children:0-2 HTTP/1.1 + * For example: GET /MyContainer/?parentURI;children HTTP/1.1 GET + * /MyContainer/?childrenrange;children:0-2 HTTP/1.1 * - * To read one or more requested fields from an existing data object, one of the - * following requests shall be performed: - * GET //?;;... - * GET //?value:;... - * GET //?metadata:;... + * To read one or more requested fields from an existing data object, one of the following requests + * shall be performed: GET //?;;... + * GET //?value:;... GET //?metadata:;... * * @author Kenneth Nagin */ public class GetCDMIObjectOptions extends BaseHttpRequestOptions { - public GetCDMIObjectOptions() { - this.pathSuffix = "?"; - } + public GetCDMIObjectOptions() { + this.pathSuffix = "?"; + } - /** - * Get CDMI data object's field - * - * @param fieldname - * @return this - */ - public GetCDMIObjectOptions field(String fieldname) { - this.pathSuffix = this.pathSuffix + fieldname + ";"; - return this; - } + /** + * Get CDMI data object's field + * + * @param fieldname + * @return this + */ + public GetCDMIObjectOptions field(String fieldname) { + this.pathSuffix = this.pathSuffix + fieldname + ";"; + return this; + } - /** - * Get CDMI data object's metadata - * - * @return this - */ - public GetCDMIObjectOptions metadata() { - this.pathSuffix = this.pathSuffix + "metadata;"; - return this; - } + /** + * Get CDMI data object's metadata + * + * @return this + */ + public GetCDMIObjectOptions metadata() { + this.pathSuffix = this.pathSuffix + "metadata;"; + return this; + } - /** - * Get CDMI data object's metadata - * - * @param prefix - * @return this - */ - public GetCDMIObjectOptions metadata(String prefix) { - this.pathSuffix = this.pathSuffix + "metadata:" + prefix + ";"; - return this; - } + /** + * Get CDMI data object's metadata + * + * @param prefix + * @return this + */ + public GetCDMIObjectOptions metadata(String prefix) { + this.pathSuffix = this.pathSuffix + "metadata:" + prefix + ";"; + return this; + } - public static class Builder { - public static GetCDMIObjectOptions field(String fieldname) { - GetCDMIObjectOptions options = new GetCDMIObjectOptions(); - return (GetCDMIObjectOptions) options.field(fieldname); - } + public static class Builder { + public static GetCDMIObjectOptions field(String fieldname) { + GetCDMIObjectOptions options = new GetCDMIObjectOptions(); + return (GetCDMIObjectOptions) options.field(fieldname); + } - public static GetCDMIObjectOptions metadata() { - GetCDMIObjectOptions options = new GetCDMIObjectOptions(); - return (GetCDMIObjectOptions) options.metadata(); - } + public static GetCDMIObjectOptions metadata() { + GetCDMIObjectOptions options = new GetCDMIObjectOptions(); + return (GetCDMIObjectOptions) options.metadata(); + } - public static GetCDMIObjectOptions metadata(String prefix) { - GetCDMIObjectOptions options = new GetCDMIObjectOptions(); - return (GetCDMIObjectOptions) options.metadata(prefix); - } + public static GetCDMIObjectOptions metadata(String prefix) { + GetCDMIObjectOptions options = new GetCDMIObjectOptions(); + return (GetCDMIObjectOptions) options.metadata(prefix); + } - } + } } diff --git a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/options/GetContainerOptions.java b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/options/GetContainerOptions.java index 105ffc193e..ab96e678e3 100644 --- a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/options/GetContainerOptions.java +++ b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/options/GetContainerOptions.java @@ -1,6 +1,5 @@ package org.jclouds.snia.cdmi.v1.options; - /** * Optional get CDMI container operations * @@ -8,89 +7,89 @@ package org.jclouds.snia.cdmi.v1.options; */ public class GetContainerOptions extends GetCDMIObjectOptions { - public GetContainerOptions() { - super(); - } + public GetContainerOptions() { + super(); + } - /** - * Get CDMI container's field - * - * @param fieldname - * @return this - */ - public GetContainerOptions field(String fieldname) { - super.field(fieldname); - return this; - } + /** + * Get CDMI container's field + * + * @param fieldname + * @return this + */ + public GetContainerOptions field(String fieldname) { + super.field(fieldname); + return this; + } - /** - * Get CDMI container's metadata - * - * @return this - */ - public GetContainerOptions metadata() { - super.metadata(); - return this; - } + /** + * Get CDMI container's metadata + * + * @return this + */ + public GetContainerOptions metadata() { + super.metadata(); + return this; + } - /** - * Get CDMI container's metadata - * - * @param prefix - * @return this - */ - public GetContainerOptions metadata(String prefix) { - super.metadata(prefix); - return this; - } + /** + * Get CDMI container's metadata + * + * @param prefix + * @return this + */ + public GetContainerOptions metadata(String prefix) { + super.metadata(prefix); + return this; + } - /** - * Get CDMI container's children - * - * @return this - */ - public GetContainerOptions children() { - this.pathSuffix = this.pathSuffix + "children;"; - return this; - } + /** + * Get CDMI container's children + * + * @return this + */ + public GetContainerOptions children() { + this.pathSuffix = this.pathSuffix + "children;"; + return this; + } - /** - * Get CDMI container's children in range - * - * @param from - * @param to - * @return this - */ - public GetContainerOptions children(int from, int to) { - this.pathSuffix = this.pathSuffix + "children:" + from + "-" + to + ";"; - return this; - } + /** + * Get CDMI container's children in range + * + * @param from + * @param to + * @return this + */ + public GetContainerOptions children(int from, int to) { + this.pathSuffix = this.pathSuffix + "children:" + from + "-" + to + ";"; + return this; + } - public static class Builder { - public static GetContainerOptions field(String fieldname) { - GetContainerOptions options = new GetContainerOptions(); - return (GetContainerOptions) options.field(fieldname); - } + public static class Builder { + public static GetContainerOptions field(String fieldname) { + GetContainerOptions options = new GetContainerOptions(); + return (GetContainerOptions) options.field(fieldname); + } - public static GetContainerOptions metadata() { - GetContainerOptions options = new GetContainerOptions(); - return (GetContainerOptions) options.metadata(); - } + public static GetContainerOptions metadata() { + GetContainerOptions options = new GetContainerOptions(); + return (GetContainerOptions) options.metadata(); + } - public static GetContainerOptions metadata(String prefix) { - GetContainerOptions options = new GetContainerOptions(); - return (GetContainerOptions) options.metadata(prefix); - } + public static GetContainerOptions metadata(String prefix) { + GetContainerOptions options = new GetContainerOptions(); + return (GetContainerOptions) options.metadata(prefix); + } - public static GetContainerOptions children() { - GetContainerOptions options = new GetContainerOptions(); - return (GetContainerOptions) options.children(); - } + public static GetContainerOptions children() { + GetContainerOptions options = new GetContainerOptions(); + return (GetContainerOptions) options.children(); + } - public static GetContainerOptions children(int from, int to) { - GetContainerOptions options = new GetContainerOptions(); - return (GetContainerOptions) options.children(from, to); - } + public static GetContainerOptions children(int from, int to) { + GetContainerOptions options = new GetContainerOptions(); + return (GetContainerOptions) options.children(from, to); + } - } + } } diff --git a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/queryparams/CDMIObjectQueryParams.java b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/queryparams/CDMIObjectQueryParams.java index c55bc594d0..cfd9f9b153 100644 --- a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/queryparams/CDMIObjectQueryParams.java +++ b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/queryparams/CDMIObjectQueryParams.java @@ -1,80 +1,68 @@ package org.jclouds.snia.cdmi.v1.queryparams; - - -import java.util.HashMap; - -import org.jclouds.http.options.BaseHttpRequestOptions; - -import com.google.common.collect.Multimap; - /** - * Generate CDMI object query parameters - * Note: The preferred implementation would use jax-rs queryParam. - * However, the CDMI query parameters specification does not conform to - * jax-rs queryParam of key=value separated by &. - * Rather it follows the form: - * ?;;.... - * ?metadata:;... - * ?children:-;... - * ?value:-;... + * Generate CDMI object query parameters Note: The preferred implementation would use jax-rs + * queryParam. However, the CDMI query parameters specification does not conform to jax-rs + * queryParam of key=value separated by &. Rather it follows the form: ?;;.... + * ?metadata:;... ?children:-;... ?value:-;... * * @author Kenneth Nagin */ -public class CDMIObjectQueryParams { - - protected String queryParams = ""; - - public CDMIObjectQueryParams() { - super(); - } +public class CDMIObjectQueryParams { - /** - * Get CDMI data object's field value - * @param fieldname - * @return this - */ - public CDMIObjectQueryParams field(String fieldname) { - queryParams = queryParams + fieldname + ";"; - return this; - } - - /** - * Get CDMI data object's metadata - * @return this - */ - public CDMIObjectQueryParams metadata() { - queryParams = queryParams + "metadata;"; - return this; - } + protected String queryParams = ""; - /** - * Get CDMI data object's metadata associated with prefix - * @param prefix - * @return this - */ - public CDMIObjectQueryParams metadata(String prefix) { - queryParams = queryParams + "metadata:"+prefix+";"; - return this; - } - + public CDMIObjectQueryParams() { + super(); + } - public static class Builder { - public static CDMIObjectQueryParams field( - String fieldname) { - CDMIObjectQueryParams options = new CDMIObjectQueryParams(); - return (CDMIObjectQueryParams) options.field(fieldname); - } - public static CDMIObjectQueryParams metadata( - String prefix) { - CDMIObjectQueryParams options = new CDMIObjectQueryParams(); - return (CDMIObjectQueryParams) options.metadata(prefix); - } + /** + * Get CDMI data object's field value + * + * @param fieldname + * @return this + */ + public CDMIObjectQueryParams field(String fieldname) { + queryParams = queryParams + fieldname + ";"; + return this; + } + + /** + * Get CDMI data object's metadata + * + * @return this + */ + public CDMIObjectQueryParams metadata() { + queryParams = queryParams + "metadata;"; + return this; + } + + /** + * Get CDMI data object's metadata associated with prefix + * + * @param prefix + * @return this + */ + public CDMIObjectQueryParams metadata(String prefix) { + queryParams = queryParams + "metadata:" + prefix + ";"; + return this; + } + + public static class Builder { + public static CDMIObjectQueryParams field(String fieldname) { + CDMIObjectQueryParams options = new CDMIObjectQueryParams(); + return (CDMIObjectQueryParams) options.field(fieldname); + } + + public static CDMIObjectQueryParams metadata(String prefix) { + CDMIObjectQueryParams options = new CDMIObjectQueryParams(); + return (CDMIObjectQueryParams) options.metadata(prefix); + } + + } + + public String toString() { + return queryParams; + } - } - - public String toString () { - return queryParams; - } - } diff --git a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/queryparams/ContainerQueryParams.java b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/queryparams/ContainerQueryParams.java index 0501940552..fe7a1f045e 100644 --- a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/queryparams/ContainerQueryParams.java +++ b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/queryparams/ContainerQueryParams.java @@ -1,96 +1,98 @@ package org.jclouds.snia.cdmi.v1.queryparams; /** - * Generate CDMI container query parameters - * Example: - * container = containerApi.getContainer(containerName,ContainerQueryParams.Builder.field("parentURI")); - * container = containerApi.getContainer(containerName,ContainerQueryParams.Builder.children(0,3)); + * Generate CDMI container query parameters Example: container = + * containerApi.get(containerName,ContainerQueryParams.Builder.field("parentURI")); container = + * containerApi.get(containerName,ContainerQueryParams.Builder.children(0,3)); * * @author Kenneth Nagin */ -public class ContainerQueryParams extends CDMIObjectQueryParams { +public class ContainerQueryParams extends CDMIObjectQueryParams { - public ContainerQueryParams() { - super(); - } + public ContainerQueryParams() { + super(); + } - /** - * Get CDMI container's field value - * @param fieldname - * @return this - */ - public ContainerQueryParams field(String fieldname) { - super.field(fieldname); - return this; - } - - /** - * Get CDMI container's metadata - * @return this - */ - public ContainerQueryParams metadata() { - super.metadata(); - return this; - } + /** + * Get CDMI container's field value + * + * @param fieldname + * @return this + */ + public ContainerQueryParams field(String fieldname) { + super.field(fieldname); + return this; + } - /** - * Get CDMI container's metadata associated with prefix - * @param prefix - * @return this - */ - public ContainerQueryParams metadata(String prefix) { - super.metadata(prefix); - return this; - } - - /** - * Get CDMI container's children - * @return this - */ - public ContainerQueryParams children() { - queryParams = queryParams + "children;"; - return this; - } - - - /** - * Get CDMI container's children within range - * @param from - * @param to - * @return this - */ - public ContainerQueryParams children(int from, int to) { - queryParams = queryParams + "children:"+from+"-"+to+";"; - return this; - } + /** + * Get CDMI container's metadata + * + * @return this + */ + public ContainerQueryParams metadata() { + super.metadata(); + return this; + } + /** + * Get CDMI container's metadata associated with prefix + * + * @param prefix + * @return this + */ + public ContainerQueryParams metadata(String prefix) { + super.metadata(prefix); + return this; + } - public static class Builder { - public static ContainerQueryParams field( - String fieldname) { - ContainerQueryParams options = new ContainerQueryParams(); - return (ContainerQueryParams) options.field(fieldname); - } - public static ContainerQueryParams metadata() { - ContainerQueryParams options = new ContainerQueryParams(); - return (ContainerQueryParams) options.metadata(); - } - - public static ContainerQueryParams metadata( - String prefix) { - ContainerQueryParams options = new ContainerQueryParams(); - return (ContainerQueryParams) options.metadata(prefix); - } - public static ContainerQueryParams children() { - ContainerQueryParams options = new ContainerQueryParams(); - return (ContainerQueryParams) options.children(); - } - public static ContainerQueryParams children( - int from, int to) { - ContainerQueryParams options = new ContainerQueryParams(); - return (ContainerQueryParams) options.children(from,to); - } + /** + * Get CDMI container's children + * + * @return this + */ + public ContainerQueryParams children() { + queryParams = queryParams + "children;"; + return this; + } + + /** + * Get CDMI container's children within range + * + * @param from + * @param to + * @return this + */ + public ContainerQueryParams children(int from, int to) { + queryParams = queryParams + "children:" + from + "-" + to + ";"; + return this; + } + + public static class Builder { + public static ContainerQueryParams field(String fieldname) { + ContainerQueryParams options = new ContainerQueryParams(); + return (ContainerQueryParams) options.field(fieldname); + } + + public static ContainerQueryParams metadata() { + ContainerQueryParams options = new ContainerQueryParams(); + return (ContainerQueryParams) options.metadata(); + } + + public static ContainerQueryParams metadata(String prefix) { + ContainerQueryParams options = new ContainerQueryParams(); + return (ContainerQueryParams) options.metadata(prefix); + } + + public static ContainerQueryParams children() { + ContainerQueryParams options = new ContainerQueryParams(); + return (ContainerQueryParams) options.children(); + } + + public static ContainerQueryParams children(int from, int to) { + ContainerQueryParams options = new ContainerQueryParams(); + return (ContainerQueryParams) options.children(from, to); + } + + } - } - } diff --git a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/queryparams/DataObjectQueryParams.java b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/queryparams/DataObjectQueryParams.java index e70107f2e1..f7e8fa1823 100644 --- a/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/queryparams/DataObjectQueryParams.java +++ b/labs/cdmi/src/main/java/org/jclouds/snia/cdmi/v1/queryparams/DataObjectQueryParams.java @@ -1,103 +1,98 @@ package org.jclouds.snia.cdmi.v1.queryparams; - - -import java.util.HashMap; - -import org.jclouds.http.options.BaseHttpRequestOptions; - -import com.google.common.collect.Multimap; - /** - * Generate CDMI data object query parameters - * Example: - * dataObject = dataApi.getDataObject(containerName,dataObjectNameIn,DataObjectQueryParams.Builder.field("parentURI")); - * dataObject = dataApi.getDataObject(containerName,dataObjectNameIn,DataObjectQueryParams.Builder.value()); + * Generate CDMI data object query parameters Example: dataObject = + * dataApi.get(containerName,dataObjectNameIn,DataObjectQueryParams.Builder.field("parentURI")); + * dataObject = dataApi.get(containerName,dataObjectNameIn,DataObjectQueryParams.Builder.value()); * * @author Kenneth Nagin */ -public class DataObjectQueryParams extends CDMIObjectQueryParams { +public class DataObjectQueryParams extends CDMIObjectQueryParams { - public DataObjectQueryParams() { - super(); - } + public DataObjectQueryParams() { + super(); + } - /** - * Get CDMI data object's field value - * @param fieldname - * @return this - */ - public DataObjectQueryParams field(String fieldname) { - super.field(fieldname); - return this; - } - - /** - * Get CDMI data object's metadata - * @return this - */ - public DataObjectQueryParams metadata() { - super.metadata(); - return this; - } + /** + * Get CDMI data object's field value + * + * @param fieldname + * @return this + */ + public DataObjectQueryParams field(String fieldname) { + super.field(fieldname); + return this; + } - /** - * Get CDMI data object's metadata associated with prefix - * @param prefix - * @return this - */ - public DataObjectQueryParams metadata(String prefix) { - super.metadata(prefix); - return this; - } - - /** - * Get CDMI data object's value with range - * @return this - */ - public DataObjectQueryParams value() { - queryParams = queryParams + "value;"; - return this; - } - - - /** - * Get CDMI data object's value within range - * @param from - * @param to - * @return this - */ - public DataObjectQueryParams value(int from, int to) { - queryParams = queryParams + "value:"+from+"-"+to+";"; - return this; - } + /** + * Get CDMI data object's metadata + * + * @return this + */ + public DataObjectQueryParams metadata() { + super.metadata(); + return this; + } + /** + * Get CDMI data object's metadata associated with prefix + * + * @param prefix + * @return this + */ + public DataObjectQueryParams metadata(String prefix) { + super.metadata(prefix); + return this; + } - public static class Builder { - public static DataObjectQueryParams field( - String fieldname) { - DataObjectQueryParams options = new DataObjectQueryParams(); - return (DataObjectQueryParams) options.field(fieldname); - } - public static DataObjectQueryParams metadata() { - DataObjectQueryParams options = new DataObjectQueryParams(); - return (DataObjectQueryParams) options.metadata(); - } - public static DataObjectQueryParams metadata( - String prefix) { - DataObjectQueryParams options = new DataObjectQueryParams(); - return (DataObjectQueryParams) options.metadata(prefix); - } - public static DataObjectQueryParams value() { - DataObjectQueryParams options = new DataObjectQueryParams(); - return (DataObjectQueryParams) options.value(); - } - public static DataObjectQueryParams value( - int from, int to) { - DataObjectQueryParams options = new DataObjectQueryParams(); - return (DataObjectQueryParams) options.value(from,to); - } + /** + * Get CDMI data object's value with range + * + * @return this + */ + public DataObjectQueryParams value() { + queryParams = queryParams + "value;"; + return this; + } + + /** + * Get CDMI data object's value within range + * + * @param from + * @param to + * @return this + */ + public DataObjectQueryParams value(int from, int to) { + queryParams = queryParams + "value:" + from + "-" + to + ";"; + return this; + } + + public static class Builder { + public static DataObjectQueryParams field(String fieldname) { + DataObjectQueryParams options = new DataObjectQueryParams(); + return (DataObjectQueryParams) options.field(fieldname); + } + + public static DataObjectQueryParams metadata() { + DataObjectQueryParams options = new DataObjectQueryParams(); + return (DataObjectQueryParams) options.metadata(); + } + + public static DataObjectQueryParams metadata(String prefix) { + DataObjectQueryParams options = new DataObjectQueryParams(); + return (DataObjectQueryParams) options.metadata(prefix); + } + + public static DataObjectQueryParams value() { + DataObjectQueryParams options = new DataObjectQueryParams(); + return (DataObjectQueryParams) options.value(); + } + + public static DataObjectQueryParams value(int from, int to) { + DataObjectQueryParams options = new DataObjectQueryParams(); + return (DataObjectQueryParams) options.value(from, to); + } + + } - } - } diff --git a/labs/cdmi/src/test/java/org/jclouds/snia/cdmi/v1/CDMIErrorHandlerTest.java b/labs/cdmi/src/test/java/org/jclouds/snia/cdmi/v1/CDMIErrorHandlerTest.java index 1e470d603a..6f8acbce5c 100644 --- a/labs/cdmi/src/test/java/org/jclouds/snia/cdmi/v1/CDMIErrorHandlerTest.java +++ b/labs/cdmi/src/test/java/org/jclouds/snia/cdmi/v1/CDMIErrorHandlerTest.java @@ -44,29 +44,30 @@ public class CDMIErrorHandlerTest { @Test public void test404SetsKeyNotFoundExceptionMosso() { - assertCodeMakes("HEAD", URI - .create("http://host/v1/MossoCloudFS_7064cdb1d49d4dcba3c899ac33e8409d/adriancole-blobstore1/key"), 404, - "Not Found", "", KeyNotFoundException.class); + assertCodeMakes("HEAD", + URI.create("http://host/v1/MossoCloudFS_7064cdb1d49d4dcba3c899ac33e8409d/adriancole-blobstore1/key"), + 404, "Not Found", "", KeyNotFoundException.class); } @Test public void test404SetsKeyNotFoundExceptionCDMI() { - assertCodeMakes("HEAD", URI - .create("http://67.202.39.175:8080/v1/AUTH_7064cdb1d49d4dcba3c899ac33e8409d/adriancole-blobstore1/key"), + assertCodeMakes( + "HEAD", + URI.create("http://67.202.39.175:8080/v1/AUTH_7064cdb1d49d4dcba3c899ac33e8409d/adriancole-blobstore1/key"), 404, "Not Found", "", KeyNotFoundException.class); } @Test public void test404SetsContainerNotFoundExceptionMosso() { - assertCodeMakes("HEAD", URI - .create("http://host/v1/MossoCloudFS_7064cdb1d49d4dcba3c899ac33e8409d/adriancole-blobstore1"), 404, + assertCodeMakes("HEAD", + URI.create("http://host/v1/MossoCloudFS_7064cdb1d49d4dcba3c899ac33e8409d/adriancole-blobstore1"), 404, "Not Found", "", ContainerNotFoundException.class); } @Test public void test404SetsContainerNotFoundExceptionCDMI() { - assertCodeMakes("HEAD", URI - .create("http://67.202.39.175:8080/v1/AUTH_7064cdb1d49d4dcba3c899ac33e8409d/adriancole-blobstore1"), + assertCodeMakes("HEAD", + URI.create("http://67.202.39.175:8080/v1/AUTH_7064cdb1d49d4dcba3c899ac33e8409d/adriancole-blobstore1"), 404, "Not Found", "", ContainerNotFoundException.class); } diff --git a/labs/cdmi/src/test/java/org/jclouds/snia/cdmi/v1/features/ContainerApiExpectTest.java b/labs/cdmi/src/test/java/org/jclouds/snia/cdmi/v1/features/ContainerApiExpectTest.java index 82a23c9405..72057425cf 100644 --- a/labs/cdmi/src/test/java/org/jclouds/snia/cdmi/v1/features/ContainerApiExpectTest.java +++ b/labs/cdmi/src/test/java/org/jclouds/snia/cdmi/v1/features/ContainerApiExpectTest.java @@ -36,30 +36,24 @@ import com.google.common.collect.ImmutableMultimap; */ @Test(groups = "unit", testName = "ContainerAsyncApiTest") public class ContainerApiExpectTest extends BaseCDMIApiExpectTest { - + public void testGetContainerWhenResponseIs2xx() throws Exception { - HttpRequest getContainer = HttpRequest.builder() - .method("GET") - .endpoint("http://localhost:8080/MyContainer/") - .headers(ImmutableMultimap. builder() - .put("X-CDMI-Specification-Version", "1.0.1") + HttpRequest get = HttpRequest + .builder() + .method("GET") + .endpoint("http://localhost:8080/MyContainer/") + .headers(ImmutableMultimap. builder().put("X-CDMI-Specification-Version", "1.0.1") .put("TID", "tenantId") .put("Authorization", "Basic " + CryptoStreams.base64("username:password".getBytes())) - .put("Accept", "application/cdmi-container") - .build()) - .build(); - - HttpResponse getContainerResponse = HttpResponse.builder() - .statusCode(200) - .payload(payloadFromResource("/container.json")) - .build(); + .put("Accept", "application/cdmi-container").build()).build(); - CDMIApi apiWhenContainersExist = requestSendsResponse(getContainer, getContainerResponse); + HttpResponse getResponse = HttpResponse.builder().statusCode(200).payload(payloadFromResource("/container.json")) + .build(); - assertEquals( - apiWhenContainersExist.getContainerApi().getContainer("MyContainer/"), - new ParseContainerTest().expected()); + CDMIApi apiWhenContainersExist = requestSendsResponse(get, getResponse); + + assertEquals(apiWhenContainersExist.getApi().get("MyContainer/"), new ParseContainerTest().expected()); } - + } diff --git a/labs/cdmi/src/test/java/org/jclouds/snia/cdmi/v1/features/ContainerApiLiveTest.java b/labs/cdmi/src/test/java/org/jclouds/snia/cdmi/v1/features/ContainerApiLiveTest.java index 53bfe159dd..7ad4537acc 100644 --- a/labs/cdmi/src/test/java/org/jclouds/snia/cdmi/v1/features/ContainerApiLiveTest.java +++ b/labs/cdmi/src/test/java/org/jclouds/snia/cdmi/v1/features/ContainerApiLiveTest.java @@ -43,247 +43,224 @@ import org.testng.annotations.Test; @Test(groups = "live", testName = "ContainerApiLiveTest") public class ContainerApiLiveTest extends BaseCDMIApiLiveTest { - @Test - public void testCreateContainer() throws Exception { - String pContainerName = "MyContainer" + System.currentTimeMillis() + "/"; - Map pContainerMetaDataIn = new HashMap(); - Iterator keys; - pContainerMetaDataIn.put("containerkey1", "value1"); - pContainerMetaDataIn.put("containerkey2", "value2"); - pContainerMetaDataIn.put("containerkey3", "value3"); + @Test + public void testCreateContainer() throws Exception { + String pContainerName = "MyContainer" + System.currentTimeMillis() + "/"; + Map pContainerMetaDataIn = new HashMap(); + Iterator keys; + pContainerMetaDataIn.put("containerkey1", "value1"); + pContainerMetaDataIn.put("containerkey2", "value2"); + pContainerMetaDataIn.put("containerkey3", "value3"); - CreateContainerOptions pCreateContainerOptions = CreateContainerOptions.Builder - .metadata(pContainerMetaDataIn); - ContainerApi api = cdmiContext.getApi().getContainerApi(); + CreateContainerOptions pCreateContainerOptions = CreateContainerOptions.Builder.metadata(pContainerMetaDataIn); + ContainerApi api = cdmiContext.getApi().getApi(); - Logger.getAnonymousLogger().info("createContainer: " + pContainerName); + Logger.getAnonymousLogger().info("create: " + pContainerName); - Container container = api.createContainer(pContainerName, - pCreateContainerOptions); - assertNotNull(container); - try { - System.out.println(container); - Logger.getAnonymousLogger().info("getContainer: " + pContainerName); - container = api.getContainer(pContainerName); - assertNotNull(container); - System.out.println(container); - assertEquals(container.getObjectType(), ObjectTypes.CONTAINER); - assertNotNull(container.getObjectID()); - assertNotNull(container.getObjectName()); - assertEquals(container.getObjectName(), pContainerName); - assertEquals(container.getParentURI(), "/"); - assertNotNull(container.getChildren()); - assertEquals(container.getChildren().isEmpty(), true); - System.out.println("Children: " + container.getChildren()); - assertNotNull(container.getMetadata()); - System.out.println("Raw metadata: " + container.getMetadata()); - keys = container.getMetadata().keySet().iterator(); - while (keys.hasNext()) { - String key = keys.next(); - JsonBall value = container.getMetadata().get(key); - System.out.println(key + ":" + value); - } - assertNotNull(container.getUserMetadata()); - Map pContainerMetaDataOut = container - .getUserMetadata(); - keys = pContainerMetaDataIn.keySet().iterator(); - while (keys.hasNext()) { - String key = keys.next(); - assertEquals(pContainerMetaDataOut.containsKey(key), true); - assertEquals(pContainerMetaDataOut.get(key), - pContainerMetaDataIn.get(key)); - } - System.out.println("UserMetaData: " + container.getUserMetadata()); - assertNotNull(container.getSystemMetadata()); - System.out.println("SystemMetaData: " - + container.getSystemMetadata()); - assertNotNull(container.getACLMetadata()); - assertEquals(container.getACLMetadata().size(),3); - List> aclMetadataOut = container - .getACLMetadata(); - System.out.println("ACLMetaData: "); - for (Map aclMap : aclMetadataOut) { - System.out.println(aclMap); - } - container = api.getContainer("/"); - System.out.println("root container: " + container); - assertEquals( - container.getChildren().contains(pContainerName), - true); - System.out.println("adding containers to container"); - String firstParentURI = api.getContainer(pContainerName).getObjectName(); - for(int i=0;i<10;i++) { -// container = api.createContainer(firstParentURI+"childcontainer"+i+"/"); - container = api.createContainer(pContainerName+"childcontainer"+i+"/"); - assertNotNull(container); - System.out.println(container); - assertEquals(container.getParentURI(),pContainerName); - assertEquals(container.getObjectName(),"childcontainer"+i+"/"); - container = api.createContainer(container.getParentURI()+container.getObjectName()+"grandchild/"); - assertEquals(container.getParentURI(),pContainerName+"childcontainer"+i+"/"); - assertEquals(container.getObjectName(),"grandchild/"); - System.out.println(container); - } - container = api.getContainer(pContainerName); - assertNotNull(container); - assertNotNull(container.getChildren()); - assertEquals(container.getChildren().size(), 10); - - } finally { - Logger.getAnonymousLogger().info( - "deleteContainer: " + pContainerName); - api.deleteContainer(pContainerName); - container = api.getContainer("/"); - System.out.println("root container: " + container); - assertEquals( - container.getChildren().contains(pContainerName), - false); - } + Container container = api.create(pContainerName, pCreateContainerOptions); + assertNotNull(container); + try { + System.out.println(container); + Logger.getAnonymousLogger().info("get: " + pContainerName); + container = api.get(pContainerName); + assertNotNull(container); + System.out.println(container); + assertEquals(container.getObjectType(), ObjectTypes.CONTAINER); + assertNotNull(container.getObjectID()); + assertNotNull(container.getObjectName()); + assertEquals(container.getObjectName(), pContainerName); + assertEquals(container.getParentURI(), "/"); + assertNotNull(container.getChildren()); + assertEquals(container.getChildren().isEmpty(), true); + System.out.println("Children: " + container.getChildren()); + assertNotNull(container.getMetadata()); + System.out.println("Raw metadata: " + container.getMetadata()); + keys = container.getMetadata().keySet().iterator(); + while (keys.hasNext()) { + String key = keys.next(); + JsonBall value = container.getMetadata().get(key); + System.out.println(key + ":" + value); + } + assertNotNull(container.getUserMetadata()); + Map pContainerMetaDataOut = container.getUserMetadata(); + keys = pContainerMetaDataIn.keySet().iterator(); + while (keys.hasNext()) { + String key = keys.next(); + assertEquals(pContainerMetaDataOut.containsKey(key), true); + assertEquals(pContainerMetaDataOut.get(key), pContainerMetaDataIn.get(key)); + } + System.out.println("UserMetaData: " + container.getUserMetadata()); + assertNotNull(container.getSystemMetadata()); + System.out.println("SystemMetaData: " + container.getSystemMetadata()); + assertNotNull(container.getACLMetadata()); + assertEquals(container.getACLMetadata().size(), 3); + List> aclMetadataOut = container.getACLMetadata(); + System.out.println("ACLMetaData: "); + for (Map aclMap : aclMetadataOut) { + System.out.println(aclMap); + } + container = api.get("/"); + System.out.println("root container: " + container); + assertEquals(container.getChildren().contains(pContainerName), true); + System.out.println("adding containers to container"); + String firstParentURI = api.get(pContainerName).getObjectName(); + for (int i = 0; i < 10; i++) { + // container = api.create(firstParentURI+"childcontainer"+i+"/"); + container = api.create(pContainerName + "childcontainer" + i + "/"); + assertNotNull(container); + System.out.println(container); + assertEquals(container.getParentURI(), pContainerName); + assertEquals(container.getObjectName(), "childcontainer" + i + "/"); + container = api.create(container.getParentURI() + container.getObjectName() + "grandchild/"); + assertEquals(container.getParentURI(), pContainerName + "childcontainer" + i + "/"); + assertEquals(container.getObjectName(), "grandchild/"); + System.out.println(container); + } + container = api.get(pContainerName); + assertNotNull(container); + assertNotNull(container.getChildren()); + assertEquals(container.getChildren().size(), 10); - } - - @Test - public void testGetContainer() throws Exception { - String pContainerName = "MyContainer" + System.currentTimeMillis() + "/"; - Map pContainerMetaDataIn = new HashMap(); - Iterator keys; - pContainerMetaDataIn.put("containerkey1", "value1"); - pContainerMetaDataIn.put("containerkey2", "value2"); - pContainerMetaDataIn.put("containerkey3", "value3"); - CreateContainerOptions pCreateContainerOptions = CreateContainerOptions.Builder - .metadata(pContainerMetaDataIn); - ContainerApi api = cdmiContext.getApi().getContainerApi(); + } finally { + Logger.getAnonymousLogger().info("delete: " + pContainerName); + api.delete(pContainerName); + container = api.get("/"); + System.out.println("root container: " + container); + assertEquals(container.getChildren().contains(pContainerName), false); + } - Logger.getAnonymousLogger().info("createContainer: " + pContainerName); + } - Container container = api.createContainer(pContainerName, - pCreateContainerOptions); - assertNotNull(container); - try { - System.out.println(container); - Logger.getAnonymousLogger().info("getContainer: " + pContainerName); - container = api.getContainer(pContainerName); - assertNotNull(container); - System.out.println(container); - assertEquals(container.getObjectType(), ObjectTypes.CONTAINER); - assertNotNull(container.getObjectID()); - assertNotNull(container.getObjectName()); - assertEquals(container.getObjectName(), pContainerName); - assertEquals(container.getParentURI(), "/"); - assertNotNull(container.getChildren()); - assertEquals(container.getChildren().isEmpty(), true); - System.out.println("Children: " + container.getChildren()); - assertNotNull(container.getMetadata()); - System.out.println("Raw metadata: " + container.getMetadata()); - keys = container.getMetadata().keySet().iterator(); - while (keys.hasNext()) { - String key = keys.next(); - JsonBall value = container.getMetadata().get(key); - System.out.println(key + ":" + value); - } - assertNotNull(container.getUserMetadata()); - Map pContainerMetaDataOut = container - .getUserMetadata(); - keys = pContainerMetaDataIn.keySet().iterator(); - while (keys.hasNext()) { - String key = keys.next(); - assertEquals(pContainerMetaDataOut.containsKey(key), true); - assertEquals(pContainerMetaDataOut.get(key), - pContainerMetaDataIn.get(key)); - } - System.out.println("UserMetaData: " + container.getUserMetadata()); - assertNotNull(container.getSystemMetadata()); - System.out.println("SystemMetaData: " - + container.getSystemMetadata()); - assertNotNull(container.getACLMetadata()); - List> aclMetadataOut = container - .getACLMetadata(); - System.out.println("ACLMetaData: "); - for (Map aclMap : aclMetadataOut) { - System.out.println(aclMap); - } - container = api.getContainer("/"); - System.out.println("root container: " + container); - assertEquals( - container.getChildren().contains(pContainerName), - true); - container = api.getContainer(pContainerName,ContainerQueryParams.Builder.field("parentURI")); - assertNotNull(container); - assertEquals(container.getParentURI(),"/"); - System.out.println(container); - - container = api.getContainer(pContainerName,ContainerQueryParams.Builder.field("parentURI").field("objectName")); - assertNotNull(container); - assertEquals(container.getParentURI(),"/"); - assertEquals(container.getObjectName(),pContainerName); + @Test + public void testGetContainer() throws Exception { + String pContainerName = "MyContainer" + System.currentTimeMillis() + "/"; + Map pContainerMetaDataIn = new HashMap(); + Iterator keys; + pContainerMetaDataIn.put("containerkey1", "value1"); + pContainerMetaDataIn.put("containerkey2", "value2"); + pContainerMetaDataIn.put("containerkey3", "value3"); + CreateContainerOptions pCreateContainerOptions = CreateContainerOptions.Builder.metadata(pContainerMetaDataIn); + ContainerApi api = cdmiContext.getApi().getApi(); - container = api.getContainer(pContainerName,ContainerQueryParams.Builder.metadata()); - assertNotNull(container); - pContainerMetaDataOut = container.getUserMetadata(); - keys = pContainerMetaDataIn.keySet().iterator(); - while (keys.hasNext()) { - String key = keys.next(); - assertEquals(pContainerMetaDataOut.containsKey(key), true); - assertEquals(pContainerMetaDataOut.get(key), - pContainerMetaDataIn.get(key)); - } - System.out.println(container); - - System.out.println("GetContainerOptions.Builder.metadata(cdmi_acl)"); - container = api.getContainer(pContainerName,ContainerQueryParams.Builder.metadata("cdmi_acl")); - assertNotNull(container); - System.out.println(container); - assertNotNull(container.getACLMetadata()); - assertEquals(container.getACLMetadata().size(),3); + Logger.getAnonymousLogger().info("create: " + pContainerName); - - System.out.println("adding containers to container"); - String firstParentURI = api.getContainer(pContainerName).getObjectName(); - for(int i=0;i<10;i++) { - container = api.createContainer(firstParentURI+"childcontainer"+i+"/"); - assertNotNull(container); - assertEquals(container.getParentURI(),pContainerName); - assertEquals(container.getObjectName(),"childcontainer"+i+"/"); - container = api.createContainer(container.getParentURI()+container.getObjectName()+"grandchild/",pCreateContainerOptions); - assertEquals(container.getParentURI(),pContainerName+"childcontainer"+i+"/"); - assertEquals(container.getObjectName(),"grandchild"+"/"); - container = api.getContainer(container.getParentURI(),ContainerQueryParams.Builder.children()); - assertEquals(container.getChildren().contains("grandchild"+"/"),true); - } - container = api.getContainer(pContainerName,ContainerQueryParams.Builder.children()); - assertNotNull(container); - assertNotNull(container.getChildren()); - assertEquals(container.getChildren().size(), 10); - container = api.getContainer(pContainerName,ContainerQueryParams.Builder.children(0,3)); - assertNotNull(container); - assertNotNull(container.getChildren()); - assertEquals(container.getChildren().size(), 4); - - container = api.getContainer(pContainerName,ContainerQueryParams.Builder.field("parentURI").field("objectName").children().metadata()); - assertNotNull(container); - assertNotNull(container.getChildren()); - assertEquals(container.getChildren().size(), 10); - assertEquals(container.getParentURI(),"/"); - assertEquals(container.getObjectName(),pContainerName); - assertEquals(container.getParentURI(),"/"); - assertEquals(container.getACLMetadata().size(),3); - for(String childName: container.getChildren()){ - api.deleteContainer(container.getObjectName()+ childName); - } - assertEquals(api.getContainer(pContainerName,ContainerQueryParams.Builder.children()).getChildren().isEmpty(),true); - - } finally { - Logger.getAnonymousLogger().info( - "deleteContainer: " + pContainerName); - api.deleteContainer(pContainerName); - container = api.getContainer("/"); - System.out.println("root container: " + container); - assertEquals( - container.getChildren().contains(pContainerName), - false); - } + Container container = api.create(pContainerName, pCreateContainerOptions); + assertNotNull(container); + try { + System.out.println(container); + Logger.getAnonymousLogger().info("get: " + pContainerName); + container = api.get(pContainerName); + assertNotNull(container); + System.out.println(container); + assertEquals(container.getObjectType(), ObjectTypes.CONTAINER); + assertNotNull(container.getObjectID()); + assertNotNull(container.getObjectName()); + assertEquals(container.getObjectName(), pContainerName); + assertEquals(container.getParentURI(), "/"); + assertNotNull(container.getChildren()); + assertEquals(container.getChildren().isEmpty(), true); + System.out.println("Children: " + container.getChildren()); + assertNotNull(container.getMetadata()); + System.out.println("Raw metadata: " + container.getMetadata()); + keys = container.getMetadata().keySet().iterator(); + while (keys.hasNext()) { + String key = keys.next(); + JsonBall value = container.getMetadata().get(key); + System.out.println(key + ":" + value); + } + assertNotNull(container.getUserMetadata()); + Map pContainerMetaDataOut = container.getUserMetadata(); + keys = pContainerMetaDataIn.keySet().iterator(); + while (keys.hasNext()) { + String key = keys.next(); + assertEquals(pContainerMetaDataOut.containsKey(key), true); + assertEquals(pContainerMetaDataOut.get(key), pContainerMetaDataIn.get(key)); + } + System.out.println("UserMetaData: " + container.getUserMetadata()); + assertNotNull(container.getSystemMetadata()); + System.out.println("SystemMetaData: " + container.getSystemMetadata()); + assertNotNull(container.getACLMetadata()); + List> aclMetadataOut = container.getACLMetadata(); + System.out.println("ACLMetaData: "); + for (Map aclMap : aclMetadataOut) { + System.out.println(aclMap); + } + container = api.get("/"); + System.out.println("root container: " + container); + assertEquals(container.getChildren().contains(pContainerName), true); + container = api.get(pContainerName, ContainerQueryParams.Builder.field("parentURI")); + assertNotNull(container); + assertEquals(container.getParentURI(), "/"); + System.out.println(container); - } + container = api.get(pContainerName, ContainerQueryParams.Builder.field("parentURI").field("objectName")); + assertNotNull(container); + assertEquals(container.getParentURI(), "/"); + assertEquals(container.getObjectName(), pContainerName); + container = api.get(pContainerName, ContainerQueryParams.Builder.metadata()); + assertNotNull(container); + pContainerMetaDataOut = container.getUserMetadata(); + keys = pContainerMetaDataIn.keySet().iterator(); + while (keys.hasNext()) { + String key = keys.next(); + assertEquals(pContainerMetaDataOut.containsKey(key), true); + assertEquals(pContainerMetaDataOut.get(key), pContainerMetaDataIn.get(key)); + } + System.out.println(container); + + System.out.println("GetContainerOptions.Builder.metadata(cdmi_acl)"); + container = api.get(pContainerName, ContainerQueryParams.Builder.metadata("cdmi_acl")); + assertNotNull(container); + System.out.println(container); + assertNotNull(container.getACLMetadata()); + assertEquals(container.getACLMetadata().size(), 3); + + System.out.println("adding containers to container"); + String firstParentURI = api.get(pContainerName).getObjectName(); + for (int i = 0; i < 10; i++) { + container = api.create(firstParentURI + "childcontainer" + i + "/"); + assertNotNull(container); + assertEquals(container.getParentURI(), pContainerName); + assertEquals(container.getObjectName(), "childcontainer" + i + "/"); + container = api.create(container.getParentURI() + container.getObjectName() + "grandchild/", + pCreateContainerOptions); + assertEquals(container.getParentURI(), pContainerName + "childcontainer" + i + "/"); + assertEquals(container.getObjectName(), "grandchild" + "/"); + container = api.get(container.getParentURI(), ContainerQueryParams.Builder.children()); + assertEquals(container.getChildren().contains("grandchild" + "/"), true); + } + container = api.get(pContainerName, ContainerQueryParams.Builder.children()); + assertNotNull(container); + assertNotNull(container.getChildren()); + assertEquals(container.getChildren().size(), 10); + container = api.get(pContainerName, ContainerQueryParams.Builder.children(0, 3)); + assertNotNull(container); + assertNotNull(container.getChildren()); + assertEquals(container.getChildren().size(), 4); + + container = api.get(pContainerName, ContainerQueryParams.Builder.field("parentURI").field("objectName") + .children().metadata()); + assertNotNull(container); + assertNotNull(container.getChildren()); + assertEquals(container.getChildren().size(), 10); + assertEquals(container.getParentURI(), "/"); + assertEquals(container.getObjectName(), pContainerName); + assertEquals(container.getParentURI(), "/"); + assertEquals(container.getACLMetadata().size(), 3); + for (String childName : container.getChildren()) { + api.delete(container.getObjectName() + childName); + } + assertEquals(api.get(pContainerName, ContainerQueryParams.Builder.children()).getChildren().isEmpty(), true); + + } finally { + Logger.getAnonymousLogger().info("delete: " + pContainerName); + api.delete(pContainerName); + container = api.get("/"); + System.out.println("root container: " + container); + assertEquals(container.getChildren().contains(pContainerName), false); + } + + } } diff --git a/labs/cdmi/src/test/java/org/jclouds/snia/cdmi/v1/features/DataApiLiveTest.java b/labs/cdmi/src/test/java/org/jclouds/snia/cdmi/v1/features/DataApiLiveTest.java index 91200d7262..b726446016 100644 --- a/labs/cdmi/src/test/java/org/jclouds/snia/cdmi/v1/features/DataApiLiveTest.java +++ b/labs/cdmi/src/test/java/org/jclouds/snia/cdmi/v1/features/DataApiLiveTest.java @@ -50,686 +50,553 @@ import com.google.common.io.Files; */ @Test(groups = "live", testName = "DataApiLiveTest") public class DataApiLiveTest extends BaseCDMIApiLiveTest { - @Test - public void testCreateDataObjects() throws Exception { + @Test + public void testCreateDataObjects() throws Exception { - String containerName = "MyContainer" + System.currentTimeMillis() + "/"; - String dataObjectNameIn = "dataobject08121.txt"; - File tmpFileIn = new File("temp.txt"); - String value; - InputStream is; - File tmpFileOut; - File inFile; - Files.touch(tmpFileIn); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - DataOutputStream out = new DataOutputStream(bos); - byte[] bytes; - - CreateDataObjectOptions pCreateDataObjectOptions; - DataObject dataObject; - Iterator keys; - Map dataObjectMetaDataOut; - Map pContainerMetaDataIn = new HashMap(); - Map pDataObjectMetaDataIn = new LinkedHashMap(); - pDataObjectMetaDataIn.put("dataObjectkey1", "value1"); - pDataObjectMetaDataIn.put("dataObjectkey2", "value2"); - pDataObjectMetaDataIn.put("dataObjectkey3", "value3"); + String containerName = "MyContainer" + System.currentTimeMillis() + "/"; + String dataObjectNameIn = "dataobject08121.txt"; + File tmpFileIn = new File("temp.txt"); + String value; + InputStream is; + File tmpFileOut; + File inFile; + Files.touch(tmpFileIn); + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + DataOutputStream out = new DataOutputStream(bos); + byte[] bytes; - CreateContainerOptions pCreateContainerOptions = CreateContainerOptions.Builder - .metadata(pContainerMetaDataIn); - ContainerApi containerApi = cdmiContext.getApi() - .getContainerApi(); - DataApi dataApi = cdmiContext.getApi().getDataApi(); - Logger.getAnonymousLogger().info("createContainer: " + containerName); - Container container = containerApi.createContainer(containerName, - pCreateContainerOptions); - try { - assertNotNull(container); - System.out.println(container); - container = containerApi.getContainer(containerName); - assertNotNull(container); - assertNotNull(container.getChildren()); - assertEquals(container.getChildren().isEmpty(), true); - - // exercise create data object with value mimetype and metadata - value = "Hello CDMI data object with value mimetype and metadata"; - pCreateDataObjectOptions = CreateDataObjectOptions.Builder - .value(value).mimetype("text/plain") - .metadata(pDataObjectMetaDataIn); - dataObject = dataApi.createDataObject(containerName, - dataObjectNameIn, pCreateDataObjectOptions); - assertNotNull(dataObject); - dataObject = dataApi.getDataObject(containerName, - dataObjectNameIn); - assertNotNull(dataObject); - System.out.println(dataObject); - System.out.println("value: " + dataObject.getValueAsString()); - assertEquals(dataObject.getMimetype(), "text/plain"); - assertEquals(dataObject.getValueAsString(), value); - dataObjectMetaDataOut = dataObject.getUserMetadata(); - assertNotNull(dataObjectMetaDataOut); - keys = pDataObjectMetaDataIn.keySet().iterator(); - while (keys.hasNext()) { - String key = keys.next(); - assertEquals(dataObjectMetaDataOut.containsKey(key), true); - assertEquals(dataObjectMetaDataOut.get(key), - pDataObjectMetaDataIn.get(key)); - } - assertEquals( - Integer.parseInt(dataObject.getSystemMetadata().get( - "cdmi_size")), value.length()); - assertEquals(dataObject.getObjectName(), dataObjectNameIn); - assertEquals(dataObject.getObjectType(), "application/cdmi-object"); - assertEquals(dataObject.getParentURI(), "/" + containerName ); - assertEquals(containerApi.getContainer(containerName) - .getChildren().contains(dataObjectNameIn), true); - - dataApi.deleteDataObject(containerName, dataObjectNameIn); - assertEquals(containerApi.getContainer(containerName) - .getChildren().contains(dataObjectNameIn), false); + CreateDataObjectOptions pCreateDataObjectOptions; + DataObject dataObject; + Iterator keys; + Map dataObjectMetaDataOut; + Map pContainerMetaDataIn = new HashMap(); + Map pDataObjectMetaDataIn = new LinkedHashMap(); + pDataObjectMetaDataIn.put("dataObjectkey1", "value1"); + pDataObjectMetaDataIn.put("dataObjectkey2", "value2"); + pDataObjectMetaDataIn.put("dataObjectkey3", "value3"); - // verify that options order does not matter - value = "Hello CDMI World3"; - pCreateDataObjectOptions = CreateDataObjectOptions.Builder - .metadata(pDataObjectMetaDataIn).mimetype("text/plain") - .value(value); - dataObject = dataApi.createDataObject(containerName, - dataObjectNameIn, pCreateDataObjectOptions); - assertNotNull(dataObject); - dataObject = dataApi.getDataObject(containerName, - dataObjectNameIn); - assertNotNull(dataObject); - System.out.println(dataObject); - System.out.println("value: " + dataObject.getValueAsString()); - assertEquals(dataObject.getMimetype(), "text/plain"); - assertEquals(dataObject.getValueAsString(), value); - dataObjectMetaDataOut = dataObject.getUserMetadata(); - assertNotNull(dataObjectMetaDataOut); - keys = pDataObjectMetaDataIn.keySet().iterator(); - while (keys.hasNext()) { - String key = keys.next(); - assertEquals(dataObjectMetaDataOut.containsKey(key), true); - assertEquals(dataObjectMetaDataOut.get(key), - pDataObjectMetaDataIn.get(key)); - } - assertEquals( - Integer.parseInt(dataObject.getSystemMetadata().get( - "cdmi_size")), value.length()); - assertEquals(dataObject.getObjectName(), dataObjectNameIn); - assertEquals(dataObject.getObjectType(), "application/cdmi-object"); - assertEquals(dataObject.getParentURI(), "/" + containerName); - assertEquals(containerApi.getContainer(containerName) - .getChildren().contains(dataObjectNameIn), true); - dataApi.deleteDataObject(containerName, dataObjectNameIn); - assertEquals(containerApi.getContainer(containerName) - .getChildren().contains(dataObjectNameIn), false); + CreateContainerOptions pCreateContainerOptions = CreateContainerOptions.Builder.metadata(pContainerMetaDataIn); + ContainerApi containerApi = cdmiContext.getApi().getApi(); + DataApi dataApi = cdmiContext.getApi().getDataApiForContainer(containerName); + Logger.getAnonymousLogger().info("create: " + containerName); + Container container = containerApi.create(containerName, pCreateContainerOptions); + try { + assertNotNull(container); + System.out.println(container); + container = containerApi.get(containerName); + assertNotNull(container); + assertNotNull(container.getChildren()); + assertEquals(container.getChildren().isEmpty(), true); - // exercise create data object with empty metadata - value = "Hello CDMI World4"; - pDataObjectMetaDataIn.clear(); - pCreateDataObjectOptions = CreateDataObjectOptions.Builder - .value(value).mimetype("text/plain") - .metadata(pDataObjectMetaDataIn); - dataObject = dataApi.createDataObject(containerName, - dataObjectNameIn, pCreateDataObjectOptions); - assertNotNull(dataObject); - dataObject = dataApi.getDataObject(containerName, - dataObjectNameIn); - assertNotNull(dataObject); - System.out.println(dataObject); - System.out.println("value: " + dataObject.getValueAsString()); - assertEquals(dataObject.getMimetype(), "text/plain"); - assertEquals(dataObject.getValueAsString(), value); - dataObjectMetaDataOut = dataObject.getUserMetadata(); - assertNotNull(dataObjectMetaDataOut); - assertEquals(dataObjectMetaDataOut.isEmpty(),true); - assertEquals( - Integer.parseInt(dataObject.getSystemMetadata().get( - "cdmi_size")), value.length()); - assertEquals(dataObject.getObjectName(), dataObjectNameIn); - assertEquals(dataObject.getObjectType(), "application/cdmi-object"); - assertEquals(dataObject.getParentURI(), "/" + containerName); - assertEquals(containerApi.getContainer(containerName) - .getChildren().contains(dataObjectNameIn), true); - dataApi.deleteDataObject(containerName, dataObjectNameIn); - assertEquals(containerApi.getContainer(containerName) - .getChildren().contains(dataObjectNameIn), false); + // exercise create data object with value mimetype and metadata + value = "Hello CDMI data object with value mimetype and metadata"; + pCreateDataObjectOptions = CreateDataObjectOptions.Builder.value(value).mimetype("text/plain") + .metadata(pDataObjectMetaDataIn); + dataObject = dataApi.create(dataObjectNameIn, pCreateDataObjectOptions); + assertNotNull(dataObject); + dataObject = dataApi.get(dataObjectNameIn); + assertNotNull(dataObject); + System.out.println(dataObject); + System.out.println("value: " + dataObject.getValueAsString()); + assertEquals(dataObject.getMimetype(), "text/plain"); + assertEquals(dataObject.getValueAsString(), value); + dataObjectMetaDataOut = dataObject.getUserMetadata(); + assertNotNull(dataObjectMetaDataOut); + keys = pDataObjectMetaDataIn.keySet().iterator(); + while (keys.hasNext()) { + String key = keys.next(); + assertEquals(dataObjectMetaDataOut.containsKey(key), true); + assertEquals(dataObjectMetaDataOut.get(key), pDataObjectMetaDataIn.get(key)); + } + assertEquals(Integer.parseInt(dataObject.getSystemMetadata().get("cdmi_size")), value.length()); + assertEquals(dataObject.getObjectName(), dataObjectNameIn); + assertEquals(dataObject.getObjectType(), "application/cdmi-object"); + assertEquals(dataObject.getParentURI(), "/" + containerName); + assertEquals(containerApi.get(containerName).getChildren().contains(dataObjectNameIn), true); - // exercise create data object with null metadata - value = "Hello CDMI World5"; - pCreateDataObjectOptions = CreateDataObjectOptions.Builder.value( - value).mimetype("text/plain"); - dataObject = dataApi.createDataObject(containerName, - dataObjectNameIn, pCreateDataObjectOptions); - assertNotNull(dataObject); - dataObject = dataApi.getDataObject(containerName, - dataObjectNameIn); - assertNotNull(dataObject); - System.out.println(dataObject); - System.out.println("value: " + dataObject.getValueAsString()); - assertEquals(dataObject.getMimetype(), "text/plain"); - assertEquals(dataObject.getValueAsString(), value); - dataObjectMetaDataOut = dataObject.getUserMetadata(); - assertNotNull(dataObjectMetaDataOut); - assertEquals(true, dataObjectMetaDataOut.isEmpty()); - assertEquals( - Integer.parseInt(dataObject.getSystemMetadata().get( - "cdmi_size")), value.length()); - assertEquals(dataObject.getObjectName(), dataObjectNameIn); - assertEquals(dataObject.getObjectType(), "application/cdmi-object"); - assertEquals(dataObject.getParentURI(), "/" + containerName); - assertEquals(containerApi.getContainer(containerName) - .getChildren().contains(dataObjectNameIn), true); - dataApi.deleteDataObject(containerName, dataObjectNameIn); - assertEquals(containerApi.getContainer(containerName) - .getChildren().contains(dataObjectNameIn), false); + dataApi.delete(dataObjectNameIn); + assertEquals(containerApi.get(containerName).getChildren().contains(dataObjectNameIn), false); - // exercise create data object with only value - value = "Hello CDMI World6"; - pCreateDataObjectOptions = CreateDataObjectOptions.Builder - .value(value); - dataObject = dataApi.createDataObject(containerName, - dataObjectNameIn, pCreateDataObjectOptions); - assertNotNull(dataObject); - dataObject = dataApi.getDataObject(containerName, - dataObjectNameIn); - assertNotNull(dataObject); - System.out.println(dataObject); - System.out.println("value: " + dataObject.getValueAsString()); - assertEquals(dataObject.getValueAsString(), value); - dataObjectMetaDataOut = dataObject.getUserMetadata(); - assertNotNull(dataObjectMetaDataOut); - assertEquals(dataObjectMetaDataOut.isEmpty(),true); - assertEquals( - Integer.parseInt(dataObject.getSystemMetadata().get( - "cdmi_size")), value.length()); - assertEquals(dataObject.getObjectName(), dataObjectNameIn); - assertEquals(dataObject.getObjectType(), "application/cdmi-object"); - assertEquals(dataObject.getParentURI(), "/" + containerName); - assertEquals(containerApi.getContainer(containerName) - .getChildren().contains(dataObjectNameIn), true); - dataApi.deleteDataObject(containerName, dataObjectNameIn); - assertEquals(containerApi.getContainer(containerName) - .getChildren().contains(dataObjectNameIn), false); + // verify that options order does not matter + value = "Hello CDMI World3"; + pCreateDataObjectOptions = CreateDataObjectOptions.Builder.metadata(pDataObjectMetaDataIn) + .mimetype("text/plain").value(value); + dataObject = dataApi.create(dataObjectNameIn, pCreateDataObjectOptions); + assertNotNull(dataObject); + dataObject = dataApi.get(dataObjectNameIn); + assertNotNull(dataObject); + System.out.println(dataObject); + System.out.println("value: " + dataObject.getValueAsString()); + assertEquals(dataObject.getMimetype(), "text/plain"); + assertEquals(dataObject.getValueAsString(), value); + dataObjectMetaDataOut = dataObject.getUserMetadata(); + assertNotNull(dataObjectMetaDataOut); + keys = pDataObjectMetaDataIn.keySet().iterator(); + while (keys.hasNext()) { + String key = keys.next(); + assertEquals(dataObjectMetaDataOut.containsKey(key), true); + assertEquals(dataObjectMetaDataOut.get(key), pDataObjectMetaDataIn.get(key)); + } + assertEquals(Integer.parseInt(dataObject.getSystemMetadata().get("cdmi_size")), value.length()); + assertEquals(dataObject.getObjectName(), dataObjectNameIn); + assertEquals(dataObject.getObjectType(), "application/cdmi-object"); + assertEquals(dataObject.getParentURI(), "/" + containerName); + assertEquals(containerApi.get(containerName).getChildren().contains(dataObjectNameIn), true); + dataApi.delete(dataObjectNameIn); + assertEquals(containerApi.get(containerName).getChildren().contains(dataObjectNameIn), false); - // exercise create data object with empty mimetype only - value = ""; - pCreateDataObjectOptions = CreateDataObjectOptions.Builder - .mimetype(new String()); - dataObject = dataApi.createDataObject(containerName, - dataObjectNameIn, pCreateDataObjectOptions); - assertNotNull(dataObject); - dataObject = dataApi.getDataObject(containerName, - dataObjectNameIn); - assertNotNull(dataObject); - System.out.println(dataObject); - System.out.println("value: " + dataObject.getValueAsString()); - //assertEquals(dataObject.getMimetype(), ""); - assertEquals(dataObject.getValueAsString(), ""); - dataObjectMetaDataOut = dataObject.getUserMetadata(); - assertNotNull(dataObjectMetaDataOut); - //assertEquals(dataObjectMetaDataOut.isEmpty(),true); + // exercise create data object with empty metadata + value = "Hello CDMI World4"; + pDataObjectMetaDataIn.clear(); + pCreateDataObjectOptions = CreateDataObjectOptions.Builder.value(value).mimetype("text/plain") + .metadata(pDataObjectMetaDataIn); + dataObject = dataApi.create(dataObjectNameIn, pCreateDataObjectOptions); + assertNotNull(dataObject); + dataObject = dataApi.get(dataObjectNameIn); + assertNotNull(dataObject); + System.out.println(dataObject); + System.out.println("value: " + dataObject.getValueAsString()); + assertEquals(dataObject.getMimetype(), "text/plain"); + assertEquals(dataObject.getValueAsString(), value); + dataObjectMetaDataOut = dataObject.getUserMetadata(); + assertNotNull(dataObjectMetaDataOut); + assertEquals(dataObjectMetaDataOut.isEmpty(), true); + assertEquals(Integer.parseInt(dataObject.getSystemMetadata().get("cdmi_size")), value.length()); + assertEquals(dataObject.getObjectName(), dataObjectNameIn); + assertEquals(dataObject.getObjectType(), "application/cdmi-object"); + assertEquals(dataObject.getParentURI(), "/" + containerName); + assertEquals(containerApi.get(containerName).getChildren().contains(dataObjectNameIn), true); + dataApi.delete(dataObjectNameIn); + assertEquals(containerApi.get(containerName).getChildren().contains(dataObjectNameIn), false); - dataApi.deleteDataObject(containerName, dataObjectNameIn); + // exercise create data object with null metadata + value = "Hello CDMI World5"; + pCreateDataObjectOptions = CreateDataObjectOptions.Builder.value(value).mimetype("text/plain"); + dataObject = dataApi.create(dataObjectNameIn, pCreateDataObjectOptions); + assertNotNull(dataObject); + dataObject = dataApi.get(dataObjectNameIn); + assertNotNull(dataObject); + System.out.println(dataObject); + System.out.println("value: " + dataObject.getValueAsString()); + assertEquals(dataObject.getMimetype(), "text/plain"); + assertEquals(dataObject.getValueAsString(), value); + dataObjectMetaDataOut = dataObject.getUserMetadata(); + assertNotNull(dataObjectMetaDataOut); + assertEquals(true, dataObjectMetaDataOut.isEmpty()); + assertEquals(Integer.parseInt(dataObject.getSystemMetadata().get("cdmi_size")), value.length()); + assertEquals(dataObject.getObjectName(), dataObjectNameIn); + assertEquals(dataObject.getObjectType(), "application/cdmi-object"); + assertEquals(dataObject.getParentURI(), "/" + containerName); + assertEquals(containerApi.get(containerName).getChildren().contains(dataObjectNameIn), true); + dataApi.delete(dataObjectNameIn); + assertEquals(containerApi.get(containerName).getChildren().contains(dataObjectNameIn), false); - // exercise create data object with no value - value = ""; - pCreateDataObjectOptions = CreateDataObjectOptions.Builder.value(); - dataObject = dataApi.createDataObject(containerName, - dataObjectNameIn, pCreateDataObjectOptions); - assertNotNull(dataObject); - dataObject = dataApi.getDataObject(containerName, - dataObjectNameIn); - assertNotNull(dataObject); - System.out.println(dataObject); - System.out.println("value: " + dataObject.getValueAsString()); - assertEquals(dataObject.getValueAsString(), ""); - dataObjectMetaDataOut = dataObject.getUserMetadata(); - assertNotNull(dataObjectMetaDataOut); - assertEquals(dataObjectMetaDataOut.isEmpty(),true); - assertEquals( - Integer.parseInt(dataObject.getSystemMetadata().get( - "cdmi_size")), value.length()); - assertEquals(dataObject.getObjectName(), dataObjectNameIn); - assertEquals(dataObject.getObjectType(), "application/cdmi-object"); - assertEquals(dataObject.getParentURI(), "/" + containerName); - assertEquals(containerApi.getContainer(containerName) - .getChildren().contains(dataObjectNameIn), true); - dataApi.deleteDataObject(containerName, dataObjectNameIn); - assertEquals(containerApi.getContainer(containerName) - .getChildren().contains(dataObjectNameIn), false); + // exercise create data object with only value + value = "Hello CDMI World6"; + pCreateDataObjectOptions = CreateDataObjectOptions.Builder.value(value); + dataObject = dataApi.create(dataObjectNameIn, pCreateDataObjectOptions); + assertNotNull(dataObject); + dataObject = dataApi.get(dataObjectNameIn); + assertNotNull(dataObject); + System.out.println(dataObject); + System.out.println("value: " + dataObject.getValueAsString()); + assertEquals(dataObject.getValueAsString(), value); + dataObjectMetaDataOut = dataObject.getUserMetadata(); + assertNotNull(dataObjectMetaDataOut); + assertEquals(dataObjectMetaDataOut.isEmpty(), true); + assertEquals(Integer.parseInt(dataObject.getSystemMetadata().get("cdmi_size")), value.length()); + assertEquals(dataObject.getObjectName(), dataObjectNameIn); + assertEquals(dataObject.getObjectType(), "application/cdmi-object"); + assertEquals(dataObject.getParentURI(), "/" + containerName); + assertEquals(containerApi.get(containerName).getChildren().contains(dataObjectNameIn), true); + dataApi.delete(dataObjectNameIn); + assertEquals(containerApi.get(containerName).getChildren().contains(dataObjectNameIn), false); - // exercise create data object with byte array - value = "Hello CDMI World 7"; - out.writeUTF(value); - out.close(); - bytes = bos.toByteArray(); - // String.getBytes causes an exception CreateDataObjectOptions need to investigate byte arrays - //bytes = value.getBytes("UTF-8"); - pCreateDataObjectOptions = CreateDataObjectOptions.Builder - .value(bytes); - dataObject = dataApi.createDataObject(containerName, - dataObjectNameIn, pCreateDataObjectOptions); - assertNotNull(dataObject); - dataObject = dataApi.getDataObject(containerName, - dataObjectNameIn); - assertNotNull(dataObject); - System.out.println(dataObject); - System.out.println("value: " + dataObject.getValueAsString()); - assertEquals(dataObject.getValueAsString(), value); - assertEquals(new String(dataObject.getValueAsByteArray()), value); - assertEquals( - Integer.parseInt(dataObject.getSystemMetadata().get( - "cdmi_size")), value.length()); - assertEquals(dataObject.getObjectName(), dataObjectNameIn); - assertEquals(dataObject.getObjectType(), "application/cdmi-object"); - assertEquals(dataObject.getParentURI(), "/" + containerName); - assertEquals(containerApi.getContainer(containerName) - .getChildren().contains(dataObjectNameIn), true); - dataApi.deleteDataObject(containerName, dataObjectNameIn); - assertEquals(containerApi.getContainer(containerName) - .getChildren().contains(dataObjectNameIn), false); + // exercise create data object with empty mimetype only + value = ""; + pCreateDataObjectOptions = CreateDataObjectOptions.Builder.mimetype(new String()); + dataObject = dataApi.create(dataObjectNameIn, pCreateDataObjectOptions); + assertNotNull(dataObject); + dataObject = dataApi.get(dataObjectNameIn); + assertNotNull(dataObject); + System.out.println(dataObject); + System.out.println("value: " + dataObject.getValueAsString()); + // assertEquals(dataObject.getMimetype(), ""); + assertEquals(dataObject.getValueAsString(), ""); + dataObjectMetaDataOut = dataObject.getUserMetadata(); + assertNotNull(dataObjectMetaDataOut); + // assertEquals(dataObjectMetaDataOut.isEmpty(),true); - // exercise create data object with an existing file - inFile = new File(System.getProperty("user.dir") - + "/src/test/resources/container.json"); - assertEquals(true, inFile.isFile()); - pCreateDataObjectOptions = CreateDataObjectOptions.Builder - .value(inFile); - dataObject = dataApi.createDataObject(containerName, - dataObjectNameIn, pCreateDataObjectOptions); - assertNotNull(dataObject); - dataObject = dataApi.getDataObject(containerName, - dataObjectNameIn); - assertNotNull(dataObject); - System.out.println(dataObject); - System.out.println("value: " + dataObject.getValueAsString()); - tmpFileOut = dataObject.getValueAsFile(Files.createTempDir()); - assertEquals(true, Files.equal(tmpFileOut, inFile)); - tmpFileOut.delete(); - assertEquals( - Integer.parseInt(dataObject.getSystemMetadata().get( - "cdmi_size")), - Files.toString(inFile, Charsets.UTF_8).length()); - assertEquals(dataObject.getObjectName(), dataObjectNameIn); - assertEquals(dataObject.getObjectType(), "application/cdmi-object"); - assertEquals(dataObject.getParentURI(), "/" + containerName); - assertEquals(containerApi.getContainer(containerName) - .getChildren().contains(dataObjectNameIn), true); - dataApi.deleteDataObject(containerName, dataObjectNameIn); - assertEquals(containerApi.getContainer(containerName) - .getChildren().contains(dataObjectNameIn), false); + dataApi.delete(dataObjectNameIn); - // exercise create data object with a temporary file that we create - // on the fly - // with default Charset - value = "Hello CDMI World 10"; - Files.write(value, tmpFileIn, Charsets.UTF_8); - pCreateDataObjectOptions = CreateDataObjectOptions.Builder - .value(tmpFileIn); - dataObject = dataApi.createDataObject(containerName, - dataObjectNameIn, pCreateDataObjectOptions); - assertNotNull(dataObject); - dataObject = dataApi.getDataObject(containerName, - dataObjectNameIn); - assertNotNull(dataObject); - System.out.println(dataObject); - System.out.println("value: " + dataObject.getValueAsString()); - assertEquals(dataObject.getValueAsString(), value); - tmpFileOut = dataObject.getValueAsFile(Files.createTempDir()); - assertEquals(true, Files.equal(tmpFileOut, tmpFileIn)); - tmpFileOut.delete(); - assertEquals( - Integer.parseInt(dataObject.getSystemMetadata().get( - "cdmi_size")), value.length()); - assertEquals(dataObject.getObjectName(), dataObjectNameIn); - assertEquals(dataObject.getObjectType(), "application/cdmi-object"); - assertEquals(dataObject.getParentURI(), "/" + containerName); - assertEquals(containerApi.getContainer(containerName) - .getChildren().contains(dataObjectNameIn), true); - dataApi.deleteDataObject(containerName, dataObjectNameIn); - assertEquals(containerApi.getContainer(containerName) - .getChildren().contains(dataObjectNameIn), false); + // exercise create data object with no value + value = ""; + pCreateDataObjectOptions = CreateDataObjectOptions.Builder.value(); + dataObject = dataApi.create(dataObjectNameIn, pCreateDataObjectOptions); + assertNotNull(dataObject); + dataObject = dataApi.get(dataObjectNameIn); + assertNotNull(dataObject); + System.out.println(dataObject); + System.out.println("value: " + dataObject.getValueAsString()); + assertEquals(dataObject.getValueAsString(), ""); + dataObjectMetaDataOut = dataObject.getUserMetadata(); + assertNotNull(dataObjectMetaDataOut); + assertEquals(dataObjectMetaDataOut.isEmpty(), true); + assertEquals(Integer.parseInt(dataObject.getSystemMetadata().get("cdmi_size")), value.length()); + assertEquals(dataObject.getObjectName(), dataObjectNameIn); + assertEquals(dataObject.getObjectType(), "application/cdmi-object"); + assertEquals(dataObject.getParentURI(), "/" + containerName); + assertEquals(containerApi.get(containerName).getChildren().contains(dataObjectNameIn), true); + dataApi.delete(dataObjectNameIn); + assertEquals(containerApi.get(containerName).getChildren().contains(dataObjectNameIn), false); - // exercise create data object with a temporary file that we create - // on the fly - // specify charset UTF_8 - Files.write(value, tmpFileIn, Charsets.UTF_8); - pCreateDataObjectOptions = CreateDataObjectOptions.Builder.value( - tmpFileIn, Charsets.UTF_8); - dataObject = dataApi.createDataObject(containerName, - dataObjectNameIn, pCreateDataObjectOptions); - assertNotNull(dataObject); - dataObject = dataApi.getDataObject(containerName, - dataObjectNameIn); - assertNotNull(dataObject); - System.out.println(dataObject); - System.out.println("value: " + dataObject.getValueAsString()); - assertEquals(dataObject.getValueAsString(), value); - tmpFileOut = dataObject.getValueAsFile(Files.createTempDir()); - assertEquals(true, Files.equal(tmpFileOut, tmpFileIn)); - tmpFileOut.delete(); - assertEquals( - Integer.parseInt(dataObject.getSystemMetadata().get( - "cdmi_size")), value.length()); - assertEquals(dataObject.getObjectName(), dataObjectNameIn); - assertEquals(dataObject.getObjectType(), "application/cdmi-object"); - assertEquals(dataObject.getParentURI(), "/" + containerName); - assertEquals(containerApi.getContainer(containerName) - .getChildren().contains(dataObjectNameIn), true); - dataApi.deleteDataObject(containerName, dataObjectNameIn); - assertEquals(containerApi.getContainer(containerName) - .getChildren().contains(dataObjectNameIn), false); + // exercise create data object with byte array + value = "Hello CDMI World 7"; + out.writeUTF(value); + out.close(); + bytes = bos.toByteArray(); + // String.getBytes causes an exception CreateDataObjectOptions need to investigate byte + // arrays + // bytes = value.getBytes(Charsets.UTF_8); + pCreateDataObjectOptions = CreateDataObjectOptions.Builder.value(bytes); + dataObject = dataApi.create(dataObjectNameIn, pCreateDataObjectOptions); + assertNotNull(dataObject); + dataObject = dataApi.get(dataObjectNameIn); + assertNotNull(dataObject); + System.out.println(dataObject); + System.out.println("value: " + dataObject.getValueAsString()); + assertEquals(dataObject.getValueAsString(), value); + assertEquals(new String(dataObject.getValueAsByteArray()), value); + assertEquals(Integer.parseInt(dataObject.getSystemMetadata().get("cdmi_size")), value.length()); + assertEquals(dataObject.getObjectName(), dataObjectNameIn); + assertEquals(dataObject.getObjectType(), "application/cdmi-object"); + assertEquals(dataObject.getParentURI(), "/" + containerName); + assertEquals(containerApi.get(containerName).getChildren().contains(dataObjectNameIn), true); + dataApi.delete(dataObjectNameIn); + assertEquals(containerApi.get(containerName).getChildren().contains(dataObjectNameIn), false); - // exercise create data object with a temporary file that we create - // on the fly - // specify charset US_ASCII - Files.write(value, tmpFileIn, Charsets.US_ASCII); - pCreateDataObjectOptions = CreateDataObjectOptions.Builder.value( - tmpFileIn, Charsets.US_ASCII); - dataObject = dataApi.createDataObject(containerName, - dataObjectNameIn, pCreateDataObjectOptions); - assertNotNull(dataObject); - dataObject = dataApi.getDataObject(containerName, - dataObjectNameIn); - assertNotNull(dataObject); - System.out.println(dataObject); - System.out.println("value: " + dataObject.getValueAsString()); - assertEquals(dataObject.getValueAsString(), value); - tmpFileOut = dataObject.getValueAsFile(Files.createTempDir()); - assertEquals(true, Files.equal(tmpFileOut, tmpFileIn)); - tmpFileOut.delete(); - assertEquals( - Integer.parseInt(dataObject.getSystemMetadata().get( - "cdmi_size")), value.length()); - assertEquals(dataObject.getObjectName(), dataObjectNameIn); - assertEquals(dataObject.getObjectType(), "application/cdmi-object"); - assertEquals(dataObject.getParentURI(), "/" + containerName); - assertEquals(containerApi.getContainer(containerName) - .getChildren().contains(dataObjectNameIn), true); - dataApi.deleteDataObject(containerName, dataObjectNameIn); - assertEquals(containerApi.getContainer(containerName) - .getChildren().contains(dataObjectNameIn), false); + // exercise create data object with an existing file + inFile = new File(System.getProperty("user.dir") + "/src/test/resources/container.json"); + assertEquals(true, inFile.isFile()); + pCreateDataObjectOptions = CreateDataObjectOptions.Builder.value(inFile); + dataObject = dataApi.create(dataObjectNameIn, pCreateDataObjectOptions); + assertNotNull(dataObject); + dataObject = dataApi.get(dataObjectNameIn); + assertNotNull(dataObject); + System.out.println(dataObject); + System.out.println("value: " + dataObject.getValueAsString()); + tmpFileOut = dataObject.getValueAsFile(Files.createTempDir()); + assertEquals(true, Files.equal(tmpFileOut, inFile)); + tmpFileOut.delete(); + assertEquals(Integer.parseInt(dataObject.getSystemMetadata().get("cdmi_size")), + Files.toString(inFile, Charsets.UTF_8).length()); + assertEquals(dataObject.getObjectName(), dataObjectNameIn); + assertEquals(dataObject.getObjectType(), "application/cdmi-object"); + assertEquals(dataObject.getParentURI(), "/" + containerName); + assertEquals(containerApi.get(containerName).getChildren().contains(dataObjectNameIn), true); + dataApi.delete(dataObjectNameIn); + assertEquals(containerApi.get(containerName).getChildren().contains(dataObjectNameIn), false); - // exercise create data object with a temporary file with multiple - // lines - // with default Charset - Files.write("line1", tmpFileIn, Charsets.UTF_8); - Files.append("\nline2", tmpFileIn, Charsets.UTF_8); - Files.append("\nline3", tmpFileIn, Charsets.UTF_8); - pCreateDataObjectOptions = CreateDataObjectOptions.Builder - .value(tmpFileIn); - dataObject = dataApi.createDataObject(containerName, - dataObjectNameIn, pCreateDataObjectOptions); - assertNotNull(dataObject); - dataObject = dataApi.getDataObject(containerName, - dataObjectNameIn); - assertNotNull(dataObject); - System.out.println(dataObject); - System.out.println("value: " + dataObject.getValueAsString()); - assertEquals(dataObject.getValueAsString(), "line1\nline2\nline3"); - tmpFileOut = dataObject.getValueAsFile(Files.createTempDir()); - assertEquals(true, Files.equal(tmpFileOut, tmpFileIn)); - tmpFileOut.delete(); - assertEquals( - Integer.parseInt(dataObject.getSystemMetadata().get( - "cdmi_size")), - Files.toString(tmpFileIn, Charsets.UTF_8).length()); - assertEquals(dataObject.getObjectName(), dataObjectNameIn); - assertEquals(dataObject.getObjectType(), "application/cdmi-object"); - assertEquals(dataObject.getParentURI(), "/" + containerName); - assertEquals(containerApi.getContainer(containerName) - .getChildren().contains(dataObjectNameIn), true); - dataApi.deleteDataObject(containerName, dataObjectNameIn); - assertEquals(containerApi.getContainer(containerName) - .getChildren().contains(dataObjectNameIn), false); + // exercise create data object with a temporary file that we create + // on the fly + // with default Charset + value = "Hello CDMI World 10"; + Files.write(value, tmpFileIn, Charsets.UTF_8); + pCreateDataObjectOptions = CreateDataObjectOptions.Builder.value(tmpFileIn); + dataObject = dataApi.create(dataObjectNameIn, pCreateDataObjectOptions); + assertNotNull(dataObject); + dataObject = dataApi.get(dataObjectNameIn); + assertNotNull(dataObject); + System.out.println(dataObject); + System.out.println("value: " + dataObject.getValueAsString()); + assertEquals(dataObject.getValueAsString(), value); + tmpFileOut = dataObject.getValueAsFile(Files.createTempDir()); + assertEquals(true, Files.equal(tmpFileOut, tmpFileIn)); + tmpFileOut.delete(); + assertEquals(Integer.parseInt(dataObject.getSystemMetadata().get("cdmi_size")), value.length()); + assertEquals(dataObject.getObjectName(), dataObjectNameIn); + assertEquals(dataObject.getObjectType(), "application/cdmi-object"); + assertEquals(dataObject.getParentURI(), "/" + containerName); + assertEquals(containerApi.get(containerName).getChildren().contains(dataObjectNameIn), true); + dataApi.delete(dataObjectNameIn); + assertEquals(containerApi.get(containerName).getChildren().contains(dataObjectNameIn), false); - // exercise create data object with a temporary file with multiple - // lines - // with Charset UTF_8 - Files.write("line1", tmpFileIn, Charsets.UTF_8); - Files.append("\nline2", tmpFileIn, Charsets.UTF_8); - Files.append("\nline3", tmpFileIn, Charsets.UTF_8); - pCreateDataObjectOptions = CreateDataObjectOptions.Builder - .value(new FileInputStream(tmpFileIn)); - dataObject = dataApi.createDataObject(containerName, - dataObjectNameIn, pCreateDataObjectOptions); - assertNotNull(dataObject); - dataObject = dataApi.getDataObject(containerName, - dataObjectNameIn); - assertNotNull(dataObject); - System.out.println(dataObject); - System.out.println("value: " + dataObject.getValueAsString()); - assertEquals(dataObject.getValueAsString(), "line1\nline2\nline3"); - tmpFileOut = dataObject.getValueAsFile(Files.createTempDir()); - assertEquals(true, Files.equal(tmpFileOut, tmpFileIn)); - tmpFileOut.delete(); - assertEquals( - Integer.parseInt(dataObject.getSystemMetadata().get( - "cdmi_size")), - Files.toString(tmpFileIn, Charsets.UTF_8).length()); - assertEquals(dataObject.getObjectName(), dataObjectNameIn); - assertEquals(dataObject.getObjectType(), "application/cdmi-object"); - assertEquals(dataObject.getParentURI(), "/" + containerName); - assertEquals(containerApi.getContainer(containerName) - .getChildren().contains(dataObjectNameIn), true); - dataApi.deleteDataObject(containerName, dataObjectNameIn); - assertEquals(containerApi.getContainer(containerName) - .getChildren().contains(dataObjectNameIn), false); + // exercise create data object with a temporary file that we create + // on the fly + // specify charset UTF_8 + Files.write(value, tmpFileIn, Charsets.UTF_8); + pCreateDataObjectOptions = CreateDataObjectOptions.Builder.value(tmpFileIn, Charsets.UTF_8); + dataObject = dataApi.create(dataObjectNameIn, pCreateDataObjectOptions); + assertNotNull(dataObject); + dataObject = dataApi.get(dataObjectNameIn); + assertNotNull(dataObject); + System.out.println(dataObject); + System.out.println("value: " + dataObject.getValueAsString()); + assertEquals(dataObject.getValueAsString(), value); + tmpFileOut = dataObject.getValueAsFile(Files.createTempDir()); + assertEquals(true, Files.equal(tmpFileOut, tmpFileIn)); + tmpFileOut.delete(); + assertEquals(Integer.parseInt(dataObject.getSystemMetadata().get("cdmi_size")), value.length()); + assertEquals(dataObject.getObjectName(), dataObjectNameIn); + assertEquals(dataObject.getObjectType(), "application/cdmi-object"); + assertEquals(dataObject.getParentURI(), "/" + containerName); + assertEquals(containerApi.get(containerName).getChildren().contains(dataObjectNameIn), true); + dataApi.delete(dataObjectNameIn); + assertEquals(containerApi.get(containerName).getChildren().contains(dataObjectNameIn), false); - // exercise create data object with a temporary file with multiple - // lines - // with Charset ISO_8859_1 - Files.write("line1", tmpFileIn, Charsets.ISO_8859_1); - Files.append("\nline2", tmpFileIn, Charsets.ISO_8859_1); - Files.append("\nline3", tmpFileIn, Charsets.ISO_8859_1); - pCreateDataObjectOptions = CreateDataObjectOptions.Builder.value( - new FileInputStream(tmpFileIn), Charsets.ISO_8859_1); - dataObject = dataApi.createDataObject(containerName, - dataObjectNameIn, pCreateDataObjectOptions); - assertNotNull(dataObject); - dataObject = dataApi.getDataObject(containerName, - dataObjectNameIn); - assertNotNull(dataObject); - System.out.println(dataObject); - System.out.println("value: " + dataObject.getValueAsString()); - assertEquals(dataObject.getValueAsString(), "line1\nline2\nline3"); - tmpFileOut = dataObject.getValueAsFile(Files.createTempDir()); - assertEquals(true, Files.equal(tmpFileOut, tmpFileIn)); - tmpFileOut.delete(); - assertEquals( - Integer.parseInt(dataObject.getSystemMetadata().get( - "cdmi_size")), - Files.toString(tmpFileIn, Charsets.ISO_8859_1).length()); - assertEquals(dataObject.getObjectName(), dataObjectNameIn); - assertEquals(dataObject.getObjectType(), "application/cdmi-object"); - assertEquals(dataObject.getParentURI(), "/" + containerName); - assertEquals(containerApi.getContainer(containerName) - .getChildren().contains(dataObjectNameIn), true); - dataApi.deleteDataObject(containerName, dataObjectNameIn); - assertEquals(containerApi.getContainer(containerName) - .getChildren().contains(dataObjectNameIn), false); + // exercise create data object with a temporary file that we create + // on the fly + // specify charset US_ASCII + Files.write(value, tmpFileIn, Charsets.US_ASCII); + pCreateDataObjectOptions = CreateDataObjectOptions.Builder.value(tmpFileIn, Charsets.US_ASCII); + dataObject = dataApi.create(dataObjectNameIn, pCreateDataObjectOptions); + assertNotNull(dataObject); + dataObject = dataApi.get(dataObjectNameIn); + assertNotNull(dataObject); + System.out.println(dataObject); + System.out.println("value: " + dataObject.getValueAsString()); + assertEquals(dataObject.getValueAsString(), value); + tmpFileOut = dataObject.getValueAsFile(Files.createTempDir()); + assertEquals(true, Files.equal(tmpFileOut, tmpFileIn)); + tmpFileOut.delete(); + assertEquals(Integer.parseInt(dataObject.getSystemMetadata().get("cdmi_size")), value.length()); + assertEquals(dataObject.getObjectName(), dataObjectNameIn); + assertEquals(dataObject.getObjectType(), "application/cdmi-object"); + assertEquals(dataObject.getParentURI(), "/" + containerName); + assertEquals(containerApi.get(containerName).getChildren().contains(dataObjectNameIn), true); + dataApi.delete(dataObjectNameIn); + assertEquals(containerApi.get(containerName).getChildren().contains(dataObjectNameIn), false); - // exercise create data object with an inputstream - is = new ByteArrayInputStream(value.getBytes()); - pCreateDataObjectOptions = CreateDataObjectOptions.Builder - .value(is); - dataObject = dataApi.createDataObject(containerName, - dataObjectNameIn, pCreateDataObjectOptions); - assertNotNull(dataObject); - dataObject = dataApi.getDataObject(containerName, - dataObjectNameIn); - assertNotNull(dataObject); - System.out.println(dataObject); - System.out.println("value: " + dataObject.getValueAsString()); - assertEquals(dataObject.getValueAsString(), value); - assertNotNull(dataObject.getValueAsInputSupplier()); - assertEquals(CharStreams.toString(CharStreams.newReaderSupplier(dataObject - .getValueAsInputSupplier(Charsets.UTF_8),Charsets.UTF_8)), value); - assertEquals( - Integer.parseInt(dataObject.getSystemMetadata().get( - "cdmi_size")), value.length()); - assertEquals(dataObject.getObjectName(), dataObjectNameIn); - assertEquals(dataObject.getObjectType(), "application/cdmi-object"); - assertEquals(dataObject.getParentURI(), "/" + containerName); - assertEquals(containerApi.getContainer(containerName) - .getChildren().contains(dataObjectNameIn), true); - dataApi.deleteDataObject(containerName, dataObjectNameIn); - assertEquals(containerApi.getContainer(containerName) - .getChildren().contains(dataObjectNameIn), false); - } finally { - tmpFileIn.delete(); - containerApi.deleteContainer(containerName); + // exercise create data object with a temporary file with multiple + // lines + // with default Charset + Files.write("line1", tmpFileIn, Charsets.UTF_8); + Files.append("\nline2", tmpFileIn, Charsets.UTF_8); + Files.append("\nline3", tmpFileIn, Charsets.UTF_8); + pCreateDataObjectOptions = CreateDataObjectOptions.Builder.value(tmpFileIn); + dataObject = dataApi.create(dataObjectNameIn, pCreateDataObjectOptions); + assertNotNull(dataObject); + dataObject = dataApi.get(dataObjectNameIn); + assertNotNull(dataObject); + System.out.println(dataObject); + System.out.println("value: " + dataObject.getValueAsString()); + assertEquals(dataObject.getValueAsString(), "line1\nline2\nline3"); + tmpFileOut = dataObject.getValueAsFile(Files.createTempDir()); + assertEquals(true, Files.equal(tmpFileOut, tmpFileIn)); + tmpFileOut.delete(); + assertEquals(Integer.parseInt(dataObject.getSystemMetadata().get("cdmi_size")), + Files.toString(tmpFileIn, Charsets.UTF_8).length()); + assertEquals(dataObject.getObjectName(), dataObjectNameIn); + assertEquals(dataObject.getObjectType(), "application/cdmi-object"); + assertEquals(dataObject.getParentURI(), "/" + containerName); + assertEquals(containerApi.get(containerName).getChildren().contains(dataObjectNameIn), true); + dataApi.delete(dataObjectNameIn); + assertEquals(containerApi.get(containerName).getChildren().contains(dataObjectNameIn), false); - } + // exercise create data object with a temporary file with multiple + // lines + // with Charset UTF_8 + Files.write("line1", tmpFileIn, Charsets.UTF_8); + Files.append("\nline2", tmpFileIn, Charsets.UTF_8); + Files.append("\nline3", tmpFileIn, Charsets.UTF_8); + pCreateDataObjectOptions = CreateDataObjectOptions.Builder.value(new FileInputStream(tmpFileIn)); + dataObject = dataApi.create(dataObjectNameIn, pCreateDataObjectOptions); + assertNotNull(dataObject); + dataObject = dataApi.get(dataObjectNameIn); + assertNotNull(dataObject); + System.out.println(dataObject); + System.out.println("value: " + dataObject.getValueAsString()); + assertEquals(dataObject.getValueAsString(), "line1\nline2\nline3"); + tmpFileOut = dataObject.getValueAsFile(Files.createTempDir()); + assertEquals(true, Files.equal(tmpFileOut, tmpFileIn)); + tmpFileOut.delete(); + assertEquals(Integer.parseInt(dataObject.getSystemMetadata().get("cdmi_size")), + Files.toString(tmpFileIn, Charsets.UTF_8).length()); + assertEquals(dataObject.getObjectName(), dataObjectNameIn); + assertEquals(dataObject.getObjectType(), "application/cdmi-object"); + assertEquals(dataObject.getParentURI(), "/" + containerName); + assertEquals(containerApi.get(containerName).getChildren().contains(dataObjectNameIn), true); + dataApi.delete(dataObjectNameIn); + assertEquals(containerApi.get(containerName).getChildren().contains(dataObjectNameIn), false); - } - - @Test - public void testGetDataObjects() throws Exception { + // exercise create data object with a temporary file with multiple + // lines + // with Charset ISO_8859_1 + Files.write("line1", tmpFileIn, Charsets.ISO_8859_1); + Files.append("\nline2", tmpFileIn, Charsets.ISO_8859_1); + Files.append("\nline3", tmpFileIn, Charsets.ISO_8859_1); + pCreateDataObjectOptions = CreateDataObjectOptions.Builder.value(new FileInputStream(tmpFileIn), + Charsets.ISO_8859_1); + dataObject = dataApi.create(dataObjectNameIn, pCreateDataObjectOptions); + assertNotNull(dataObject); + dataObject = dataApi.get(dataObjectNameIn); + assertNotNull(dataObject); + System.out.println(dataObject); + System.out.println("value: " + dataObject.getValueAsString()); + assertEquals(dataObject.getValueAsString(), "line1\nline2\nline3"); + tmpFileOut = dataObject.getValueAsFile(Files.createTempDir()); + assertEquals(true, Files.equal(tmpFileOut, tmpFileIn)); + tmpFileOut.delete(); + assertEquals(Integer.parseInt(dataObject.getSystemMetadata().get("cdmi_size")), + Files.toString(tmpFileIn, Charsets.ISO_8859_1).length()); + assertEquals(dataObject.getObjectName(), dataObjectNameIn); + assertEquals(dataObject.getObjectType(), "application/cdmi-object"); + assertEquals(dataObject.getParentURI(), "/" + containerName); + assertEquals(containerApi.get(containerName).getChildren().contains(dataObjectNameIn), true); + dataApi.delete(dataObjectNameIn); + assertEquals(containerApi.get(containerName).getChildren().contains(dataObjectNameIn), false); - String containerName = "MyContainer" + System.currentTimeMillis() + "/"; - String dataObjectNameIn = "dataobject08121.txt"; - File tmpFileIn = new File("temp.txt"); - String value; - Files.touch(tmpFileIn); - - CreateDataObjectOptions pCreateDataObjectOptions; - DataObject dataObject; - Iterator keys; - Map dataObjectMetaDataOut; - Map pContainerMetaDataIn = new HashMap(); - Map pDataObjectMetaDataIn = new LinkedHashMap(); - pDataObjectMetaDataIn.put("dataObjectkey1", "value1"); - pDataObjectMetaDataIn.put("dataObjectkey2", "value2"); - pDataObjectMetaDataIn.put("dataObjectkey3", "value3"); + // exercise create data object with an inputstream + is = new ByteArrayInputStream(value.getBytes()); + pCreateDataObjectOptions = CreateDataObjectOptions.Builder.value(is); + dataObject = dataApi.create(dataObjectNameIn, pCreateDataObjectOptions); + assertNotNull(dataObject); + dataObject = dataApi.get(dataObjectNameIn); + assertNotNull(dataObject); + System.out.println(dataObject); + System.out.println("value: " + dataObject.getValueAsString()); + assertEquals(dataObject.getValueAsString(), value); + assertNotNull(dataObject.getValueAsInputSupplier()); + assertEquals(CharStreams.toString(CharStreams.newReaderSupplier( + dataObject.getValueAsInputSupplier(Charsets.UTF_8), Charsets.UTF_8)), value); + assertEquals(Integer.parseInt(dataObject.getSystemMetadata().get("cdmi_size")), value.length()); + assertEquals(dataObject.getObjectName(), dataObjectNameIn); + assertEquals(dataObject.getObjectType(), "application/cdmi-object"); + assertEquals(dataObject.getParentURI(), "/" + containerName); + assertEquals(containerApi.get(containerName).getChildren().contains(dataObjectNameIn), true); + dataApi.delete(dataObjectNameIn); + assertEquals(containerApi.get(containerName).getChildren().contains(dataObjectNameIn), false); + } finally { + tmpFileIn.delete(); + containerApi.delete(containerName); - CreateContainerOptions pCreateContainerOptions = CreateContainerOptions.Builder - .metadata(pContainerMetaDataIn); - ContainerApi containerApi = cdmiContext.getApi() - .getContainerApi(); - DataApi dataApi = cdmiContext.getApi().getDataApi(); - Logger.getAnonymousLogger().info("createContainer: " + containerName); - Container container = containerApi.createContainer(containerName, - pCreateContainerOptions); - try { - assertNotNull(container); - System.out.println(container); - container = containerApi.getContainer(containerName); - assertNotNull(container); - assertNotNull(container.getChildren()); - assertEquals(container.getChildren().isEmpty(), true); - - // exercise create data object with value mimetype and metadata - value = "Hello CDMI data object with value mimetype and metadata"; - pCreateDataObjectOptions = CreateDataObjectOptions.Builder - .value(value).mimetype("text/plain") - .metadata(pDataObjectMetaDataIn); - dataObject = dataApi.createDataObject(containerName, - dataObjectNameIn, pCreateDataObjectOptions); - assertNotNull(dataObject); - dataObject = dataApi.getDataObject(containerName, - dataObjectNameIn); - assertNotNull(dataObject); - System.out.println(dataObject); - System.out.println("value: " + dataObject.getValueAsString()); - assertEquals(dataObject.getMimetype(), "text/plain"); - assertEquals(dataObject.getValueAsString(), value); - dataObjectMetaDataOut = dataObject.getUserMetadata(); - assertNotNull(dataObjectMetaDataOut); - keys = pDataObjectMetaDataIn.keySet().iterator(); - while (keys.hasNext()) { - String key = keys.next(); - assertEquals(dataObjectMetaDataOut.containsKey(key), true); - assertEquals(dataObjectMetaDataOut.get(key), - pDataObjectMetaDataIn.get(key)); - } - assertEquals( - Integer.parseInt(dataObject.getSystemMetadata().get( - "cdmi_size")), value.length()); - assertEquals(dataObject.getObjectName(), dataObjectNameIn); - assertEquals(dataObject.getObjectType(), "application/cdmi-object"); - assertEquals(dataObject.getParentURI(), "/" + containerName); - assertEquals(containerApi.getContainer(containerName) - .getChildren().contains(dataObjectNameIn), true); - - dataObject = dataApi.getDataObject(containerName, - dataObjectNameIn,DataObjectQueryParams.Builder.field("parentURI")); - assertNotNull(dataObject); - System.out.println(dataObject); - assertEquals(dataObject.getParentURI(),container.getParentURI()+container.getObjectName()); - - dataObject = dataApi.getDataObject(containerName, - dataObjectNameIn,DataObjectQueryParams.Builder.field("parentURI").field("objectName")); - assertNotNull(dataObject); - System.out.println(dataObject); - assertEquals(dataObject.getParentURI(),container.getParentURI()+container.getObjectName()); - assertEquals(dataObject.getObjectName(),dataObjectNameIn); + } - dataObject = dataApi.getDataObject(containerName, - dataObjectNameIn,DataObjectQueryParams.Builder.field("parentURI").field("objectName").field("mimetype")); - assertNotNull(dataObject); - System.out.println(dataObject); - assertEquals(dataObject.getParentURI(),container.getParentURI()+container.getObjectName()); - assertEquals(dataObject.getObjectName(),dataObjectNameIn); - assertEquals(dataObject.getMimetype(),"text/plain"); + } - dataObject = dataApi.getDataObject(containerName, - dataObjectNameIn,DataObjectQueryParams.Builder.field("parentURI").field("objectName").field("mimetype").metadata()); - assertNotNull(dataObject); - System.out.println(dataObject); - assertEquals(dataObject.getParentURI(),container.getParentURI()+container.getObjectName()); - assertEquals(dataObject.getObjectName(),dataObjectNameIn); - assertEquals(dataObject.getMimetype(),"text/plain"); - dataObjectMetaDataOut = dataObject.getUserMetadata(); - assertNotNull(dataObjectMetaDataOut); - keys = pDataObjectMetaDataIn.keySet().iterator(); - while (keys.hasNext()) { - String key = keys.next(); - assertEquals(dataObjectMetaDataOut.containsKey(key), true); - assertEquals(dataObjectMetaDataOut.get(key), - pDataObjectMetaDataIn.get(key)); - } - assertEquals( - Integer.parseInt(dataObject.getSystemMetadata().get( - "cdmi_size")), value.length()); - - dataObject = dataApi.getDataObject(containerName, - dataObjectNameIn,DataObjectQueryParams.Builder.metadata("cdmi_size")); - assertNotNull(dataObject); - System.out.println(dataObject); - assertEquals( - Integer.parseInt(dataObject.getSystemMetadata().get( - "cdmi_size")), value.length()); + @Test + public void testGetDataObjects() throws Exception { - dataObject = dataApi.getDataObject(containerName, - dataObjectNameIn,DataObjectQueryParams.Builder.field("mimetype").value()); - assertNotNull(dataObject); - System.out.println(dataObject); - System.out.println(dataObject.getValueAsString()); - assertEquals(dataObject.getMimetype(),"text/plain"); - assertEquals(dataObject.getValueAsString(),value); - - dataObject = dataApi.getDataObject(containerName, - dataObjectNameIn,DataObjectQueryParams.Builder.field("mimetype").value(0,3)); - assertNotNull(dataObject); - System.out.println(dataObject); - System.out.println(dataObject.getValueAsString()); - assertEquals(dataObject.getMimetype(),"text/plain"); - //value is SGVsbA==. This needs investigating to determine if this - //is problem with CDMI server or the jcloud client or must understanding of spec + String containerName = "MyContainer" + System.currentTimeMillis() + "/"; + String dataObjectNameIn = "dataobject08121.txt"; + File tmpFileIn = new File("temp.txt"); + String value; + Files.touch(tmpFileIn); + CreateDataObjectOptions pCreateDataObjectOptions; + DataObject dataObject; + Iterator keys; + Map dataObjectMetaDataOut; + Map pContainerMetaDataIn = new HashMap(); + Map pDataObjectMetaDataIn = new LinkedHashMap(); + pDataObjectMetaDataIn.put("dataObjectkey1", "value1"); + pDataObjectMetaDataIn.put("dataObjectkey2", "value2"); + pDataObjectMetaDataIn.put("dataObjectkey3", "value3"); - dataApi.deleteDataObject(containerName, dataObjectNameIn); - assertEquals(containerApi.getContainer(containerName) - .getChildren().contains(dataObjectNameIn), false); - } finally { - tmpFileIn.delete(); - containerApi.deleteContainer(containerName); + CreateContainerOptions pCreateContainerOptions = CreateContainerOptions.Builder.metadata(pContainerMetaDataIn); + ContainerApi containerApi = cdmiContext.getApi().getApi(); + DataApi dataApi = cdmiContext.getApi().getDataApiForContainer(containerName); + Logger.getAnonymousLogger().info("create: " + containerName); + Container container = containerApi.create(containerName, pCreateContainerOptions); + try { + assertNotNull(container); + System.out.println(container); + container = containerApi.get(containerName); + assertNotNull(container); + assertNotNull(container.getChildren()); + assertEquals(container.getChildren().isEmpty(), true); - } + // exercise create data object with value mimetype and metadata + value = "Hello CDMI data object with value mimetype and metadata"; + pCreateDataObjectOptions = CreateDataObjectOptions.Builder.value(value).mimetype("text/plain") + .metadata(pDataObjectMetaDataIn); + dataObject = dataApi.create(dataObjectNameIn, pCreateDataObjectOptions); + assertNotNull(dataObject); + dataObject = dataApi.get(dataObjectNameIn); + assertNotNull(dataObject); + System.out.println(dataObject); + System.out.println("value: " + dataObject.getValueAsString()); + assertEquals(dataObject.getMimetype(), "text/plain"); + assertEquals(dataObject.getValueAsString(), value); + dataObjectMetaDataOut = dataObject.getUserMetadata(); + assertNotNull(dataObjectMetaDataOut); + keys = pDataObjectMetaDataIn.keySet().iterator(); + while (keys.hasNext()) { + String key = keys.next(); + assertEquals(dataObjectMetaDataOut.containsKey(key), true); + assertEquals(dataObjectMetaDataOut.get(key), pDataObjectMetaDataIn.get(key)); + } + assertEquals(Integer.parseInt(dataObject.getSystemMetadata().get("cdmi_size")), value.length()); + assertEquals(dataObject.getObjectName(), dataObjectNameIn); + assertEquals(dataObject.getObjectType(), "application/cdmi-object"); + assertEquals(dataObject.getParentURI(), "/" + containerName); + assertEquals(containerApi.get(containerName).getChildren().contains(dataObjectNameIn), true); - } + dataObject = dataApi.get(dataObjectNameIn, DataObjectQueryParams.Builder.field("parentURI")); + assertNotNull(dataObject); + System.out.println(dataObject); + assertEquals(dataObject.getParentURI(), container.getParentURI() + container.getObjectName()); + dataObject = dataApi.get(dataObjectNameIn, DataObjectQueryParams.Builder.field("parentURI") + .field("objectName")); + assertNotNull(dataObject); + System.out.println(dataObject); + assertEquals(dataObject.getParentURI(), container.getParentURI() + container.getObjectName()); + assertEquals(dataObject.getObjectName(), dataObjectNameIn); + + dataObject = dataApi.get(dataObjectNameIn, DataObjectQueryParams.Builder.field("parentURI") + .field("objectName").field("mimetype")); + assertNotNull(dataObject); + System.out.println(dataObject); + assertEquals(dataObject.getParentURI(), container.getParentURI() + container.getObjectName()); + assertEquals(dataObject.getObjectName(), dataObjectNameIn); + assertEquals(dataObject.getMimetype(), "text/plain"); + + dataObject = dataApi.get(dataObjectNameIn, DataObjectQueryParams.Builder.field("parentURI") + .field("objectName").field("mimetype").metadata()); + assertNotNull(dataObject); + System.out.println(dataObject); + assertEquals(dataObject.getParentURI(), container.getParentURI() + container.getObjectName()); + assertEquals(dataObject.getObjectName(), dataObjectNameIn); + assertEquals(dataObject.getMimetype(), "text/plain"); + dataObjectMetaDataOut = dataObject.getUserMetadata(); + assertNotNull(dataObjectMetaDataOut); + keys = pDataObjectMetaDataIn.keySet().iterator(); + while (keys.hasNext()) { + String key = keys.next(); + assertEquals(dataObjectMetaDataOut.containsKey(key), true); + assertEquals(dataObjectMetaDataOut.get(key), pDataObjectMetaDataIn.get(key)); + } + assertEquals(Integer.parseInt(dataObject.getSystemMetadata().get("cdmi_size")), value.length()); + + dataObject = dataApi.get(dataObjectNameIn, DataObjectQueryParams.Builder.metadata("cdmi_size")); + assertNotNull(dataObject); + System.out.println(dataObject); + assertEquals(Integer.parseInt(dataObject.getSystemMetadata().get("cdmi_size")), value.length()); + + dataObject = dataApi.get(dataObjectNameIn, DataObjectQueryParams.Builder.field("mimetype").value()); + assertNotNull(dataObject); + System.out.println(dataObject); + System.out.println(dataObject.getValueAsString()); + assertEquals(dataObject.getMimetype(), "text/plain"); + assertEquals(dataObject.getValueAsString(), value); + + dataObject = dataApi.get(dataObjectNameIn, DataObjectQueryParams.Builder.field("mimetype").value(0, 3)); + assertNotNull(dataObject); + System.out.println(dataObject); + System.out.println(dataObject.getValueAsString()); + assertEquals(dataObject.getMimetype(), "text/plain"); + // value is SGVsbA==. This needs investigating to determine if this + // is problem with CDMI server or the jcloud client or must understanding of spec + + dataApi.delete(dataObjectNameIn); + assertEquals(containerApi.get(containerName).getChildren().contains(dataObjectNameIn), false); + } finally { + tmpFileIn.delete(); + containerApi.delete(containerName); + + } + + } } diff --git a/labs/cdmi/src/test/java/org/jclouds/snia/cdmi/v1/features/DataNonCDMIContentTypeApiLiveTest.java b/labs/cdmi/src/test/java/org/jclouds/snia/cdmi/v1/features/DataNonCDMIContentTypeApiLiveTest.java index 649b32c1fd..c30ce137d6 100644 --- a/labs/cdmi/src/test/java/org/jclouds/snia/cdmi/v1/features/DataNonCDMIContentTypeApiLiveTest.java +++ b/labs/cdmi/src/test/java/org/jclouds/snia/cdmi/v1/features/DataNonCDMIContentTypeApiLiveTest.java @@ -31,6 +31,7 @@ import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.logging.Logger; + import org.jclouds.io.Payload; import org.jclouds.io.payloads.BaseMutableContentMetadata; import org.jclouds.io.payloads.ByteArrayPayload; @@ -42,6 +43,7 @@ import org.jclouds.snia.cdmi.v1.domain.DataObject; import org.jclouds.snia.cdmi.v1.internal.BaseCDMIApiLiveTest; import org.jclouds.snia.cdmi.v1.options.CreateContainerOptions; import org.jclouds.snia.cdmi.v1.queryparams.DataObjectQueryParams; +import org.jclouds.util.Strings2; import org.testng.annotations.Test; import com.google.common.base.Charsets; @@ -55,367 +57,297 @@ import com.google.common.net.MediaType; */ @Test(groups = "live", testName = "DataNonCDMIContentTypeApiLiveTest") public class DataNonCDMIContentTypeApiLiveTest extends BaseCDMIApiLiveTest { - @Test - public void testCreateDataObjectsNonCDMI() throws Exception { + @Test + public void testCreateDataObjectsNonCDMI() throws Exception { - String containerName = "MyContainer" + System.currentTimeMillis() + "/"; - String dataObjectNameIn = "dataobject.txt"; - File tmpFileIn = new File("temp.txt"); - String value; - InputStream is; - File tmpFileOut; - File inFile; - Files.touch(tmpFileIn); - byte[] bytes; - DataObject dataObject; - Map pContainerMetaDataIn = new HashMap(); - Map pDataObjectMetaDataIn = new LinkedHashMap(); - pDataObjectMetaDataIn.put("dataObjectkey1", "value1"); - pDataObjectMetaDataIn.put("dataObjectkey2", "value2"); - pDataObjectMetaDataIn.put("dataObjectkey3", "value3"); - - Payload payloadIn; - Payload payloadOut; - FileOutputStream fos; - + String containerName = "MyContainer" + System.currentTimeMillis() + "/"; + String dataObjectNameIn = "dataobject.txt"; + File tmpFileIn = new File("temp.txt"); + String value; + InputStream is; + File tmpFileOut; + File inFile; + Files.touch(tmpFileIn); + byte[] bytes; + DataObject dataObject; + Map pContainerMetaDataIn = new HashMap(); + Map pDataObjectMetaDataIn = new LinkedHashMap(); + pDataObjectMetaDataIn.put("dataObjectkey1", "value1"); + pDataObjectMetaDataIn.put("dataObjectkey2", "value2"); + pDataObjectMetaDataIn.put("dataObjectkey3", "value3"); - CreateContainerOptions pCreateContainerOptions = CreateContainerOptions.Builder - .metadata(pContainerMetaDataIn); - ContainerApi containerApi = cdmiContext.getApi() - .getContainerApi(); - DataApi dataApi = cdmiContext.getApi().getDataApi(); - DataNonCDMIContentTypeApi dataNonCDMIContentTypeApi = cdmiContext.getApi().getDataNonCDMIContentTypeApi(); - Logger.getAnonymousLogger().info("createContainer: " + containerName); - Container container = containerApi.createContainer(containerName, - pCreateContainerOptions); - try { - - assertNotNull(container); - System.out.println(container); - container = containerApi.getContainer(containerName); - assertNotNull(container); - assertNotNull(container.getChildren()); - assertEquals(container.getChildren().isEmpty(), true); - - // exercise create data object with none cdmi put with payload string. - value = "Hello CDMI World non-cdmi String"; - dataNonCDMIContentTypeApi.createDataObject(containerName, dataObjectNameIn, - value); - payloadOut = dataNonCDMIContentTypeApi.getDataObjectValue(containerName, dataObjectNameIn); - assertNotNull(payloadOut); - assertEquals(CharStreams.toString(new InputStreamReader(payloadOut.getInput(), "UTF-8")),value); - - payloadIn = new StringPayload(value); - payloadIn.setContentMetadata(BaseMutableContentMetadata.fromContentMetadata(payloadIn.getContentMetadata().toBuilder() - .contentType(MediaType.PLAIN_TEXT_UTF_8.toString()) - .build())); - dataNonCDMIContentTypeApi.createDataObject(containerName, dataObjectNameIn, - payloadIn); + Payload payloadIn; + Payload payloadOut; + FileOutputStream fos; - payloadOut = dataNonCDMIContentTypeApi.getDataObjectValue(containerName, dataObjectNameIn); - assertNotNull(payloadOut); - assertEquals(CharStreams.toString(new InputStreamReader(payloadOut.getInput(), "UTF-8")),value); - - dataObject = dataNonCDMIContentTypeApi.getDataObject(containerName, dataObjectNameIn, - DataObjectQueryParams.Builder.field("parentURI")); - assertNotNull(dataObject); - System.out.println(dataObject); - assertEquals(dataObject.getParentURI(), "/" + containerName); - dataObject = dataNonCDMIContentTypeApi.getDataObject(containerName, dataObjectNameIn, - DataObjectQueryParams.Builder.metadata() - .field("parentURI") - .field("objectName") - .field("objectType") - .field("mimetype")); - assertEquals( - Integer.parseInt(dataObject.getSystemMetadata().get( - "cdmi_size")), value.length()); - assertEquals(dataObject.getObjectName(), dataObjectNameIn); - assertEquals(dataObject.getObjectType(), "application/cdmi-object"); - assertEquals(dataObject.getParentURI(), "/" + containerName); - assertEquals(dataObject.getMimetype(),MediaType.PLAIN_TEXT_UTF_8.toString()); - + CreateContainerOptions pCreateContainerOptions = CreateContainerOptions.Builder.metadata(pContainerMetaDataIn); + ContainerApi containerApi = cdmiContext.getApi().getApi(); + DataApi dataApi = cdmiContext.getApi().getDataApiForContainer(containerName); + DataNonCDMIContentTypeApi dataNonCDMIContentTypeApi = cdmiContext.getApi() + .getDataNonCDMIContentTypeApiForContainer(containerName); + Logger.getAnonymousLogger().info("create: " + containerName); + Container container = containerApi.create(containerName, pCreateContainerOptions); + try { - - dataNonCDMIContentTypeApi.deleteDataObject(containerName, dataObjectNameIn); - assertEquals(containerApi.getContainer(containerName) - .getChildren().contains(dataObjectNameIn), false); + assertNotNull(container); + System.out.println(container); + container = containerApi.get(containerName); + assertNotNull(container); + assertNotNull(container.getChildren()); + assertEquals(container.getChildren().isEmpty(), true); - // exercise create data object with none cdmi put with payload byte array. - value = "Hello CDMI World non-cdmi byte array"; - bytes = value.getBytes("UTF-8"); - payloadIn = new ByteArrayPayload(bytes); - payloadIn.setContentMetadata(BaseMutableContentMetadata.fromContentMetadata(payloadIn.getContentMetadata().toBuilder() - .contentType(MediaType.PLAIN_TEXT_UTF_8.toString()) - .build())); - dataNonCDMIContentTypeApi.createDataObject(containerName, dataObjectNameIn, - payloadIn); - System.out.println(containerApi.getContainer(containerName)); - dataObject = dataApi.getDataObject(containerName, - dataObjectNameIn); - assertNotNull(dataObject); - System.out.println(dataObject); - System.out.println("value: " + dataObject.getValueAsString()); - assertEquals(dataObject.getValueAsString(), value); - assertEquals(new String(dataObject.getValueAsByteArray()), value); - assertEquals(dataObject.getUserMetadata().isEmpty(), true); - assertEquals( - Integer.parseInt(dataObject.getSystemMetadata().get( - "cdmi_size")), value.length()); - assertEquals(dataObject.getObjectName(), dataObjectNameIn); - assertEquals(dataObject.getObjectType(), "application/cdmi-object"); - assertEquals(dataObject.getParentURI(), "/" + containerName); - assertEquals(containerApi.getContainer(containerName) - .getChildren().contains(dataObjectNameIn), true); - payloadOut = dataNonCDMIContentTypeApi.getDataObjectValue(containerName, dataObjectNameIn); - assertNotNull(payloadOut); - assertEquals(CharStreams.toString(new InputStreamReader(payloadOut.getInput(), "UTF-8")),value); + // exercise create data object with none cdmi put with payload string. + value = "Hello CDMI World non-cdmi String"; + dataNonCDMIContentTypeApi.create(dataObjectNameIn, value); + payloadOut = dataNonCDMIContentTypeApi.getValue(dataObjectNameIn); + assertNotNull(payloadOut); + assertEquals(Strings2.toString(payloadOut), value); - - - dataNonCDMIContentTypeApi.deleteDataObject(containerName, dataObjectNameIn); - assertEquals(containerApi.getContainer(containerName) - .getChildren().contains(dataObjectNameIn), false); - - - + payloadIn = new StringPayload(value); + payloadIn.setContentMetadata(BaseMutableContentMetadata.fromContentMetadata(payloadIn.getContentMetadata() + .toBuilder().contentType(MediaType.PLAIN_TEXT_UTF_8.toString()).build())); + dataNonCDMIContentTypeApi.create(dataObjectNameIn, payloadIn); - // exercise create data object with none cdmi put with payload file. - value = "Hello CDMI World non-cdmi File"; - Files.write(value, tmpFileIn, Charsets.UTF_8); - payloadIn = new FilePayload(tmpFileIn); - payloadIn.setContentMetadata(BaseMutableContentMetadata.fromContentMetadata(payloadIn.getContentMetadata().toBuilder() - .contentType(MediaType.PLAIN_TEXT_UTF_8.toString()) - .build())); - - dataNonCDMIContentTypeApi.createDataObject(containerName, dataObjectNameIn, - payloadIn); - System.out.println(containerApi.getContainer(containerName)); - dataObject = dataApi.getDataObject(containerName, - dataObjectNameIn); - assertNotNull(dataObject); - System.out.println(dataObject); - System.out.println("value: " + dataObject.getValueAsString()); - assertEquals(dataObject.getValueAsString(), value); - tmpFileOut = dataObject.getValueAsFile(Files.createTempDir()); - assertEquals(true, Files.equal(tmpFileOut, tmpFileIn)); - tmpFileOut.delete(); - assertEquals(dataObject.getUserMetadata().isEmpty(), true); - System.out.println("My Metadata: "+dataObject.getUserMetadata()); - assertEquals( - Integer.parseInt(dataObject.getSystemMetadata().get( - "cdmi_size")), value.length()); - assertEquals(dataObject.getObjectName(), dataObjectNameIn); - assertEquals(dataObject.getObjectType(), "application/cdmi-object"); - assertEquals(dataObject.getParentURI(), "/" + containerName); - assertEquals(containerApi.getContainer(containerName) - .getChildren().contains(dataObjectNameIn), true); - - payloadOut = dataNonCDMIContentTypeApi.getDataObjectValue(containerName, dataObjectNameIn); - assertNotNull(payloadOut); - //assertEquals(CharStreams.toString(new InputStreamReader(payloadOut.getInput(), "UTF-8")),value); - //byte[] _bytes = ByteStreams.toByteArray(payloadOut.getInput()); - tmpFileOut = new File(Files.createTempDir(),"temp.txt"); - fos = new FileOutputStream(tmpFileOut); - ByteStreams.copy(payloadOut.getInput(), fos); - fos.flush(); - fos.close(); - assertEquals(Files.equal(tmpFileOut, tmpFileIn),true); - tmpFileOut.delete(); - - dataNonCDMIContentTypeApi.deleteDataObject(containerName, dataObjectNameIn); - assertEquals(containerApi.getContainer(containerName) - .getChildren().contains(dataObjectNameIn), false); + payloadOut = dataNonCDMIContentTypeApi.getValue(dataObjectNameIn); + assertNotNull(payloadOut); + assertEquals(Strings2.toString(payloadOut), value); - // exercise create data object with none cdmi put with text file payload file. - inFile = new File(System.getProperty("user.dir") - + "/src/test/resources/container.json"); - assertEquals(true, inFile.isFile()); - payloadIn = new FilePayload(inFile); - payloadIn.setContentMetadata(BaseMutableContentMetadata.fromContentMetadata(payloadIn.getContentMetadata().toBuilder() - .contentType(MediaType.JSON_UTF_8.toString()) - .build())); - - dataNonCDMIContentTypeApi.createDataObject(containerName, inFile.getName(), - payloadIn); - System.out.println(containerApi.getContainer(containerName)); - dataObject = dataApi.getDataObject(containerName, - inFile.getName()); - assertNotNull(dataObject); - System.out.println(dataObject); - //System.out.println("value: " + dataObject.getValueAsString()); - //assertEquals(dataObject.getValueAsString(), value); - tmpFileOut = dataObject.getValueAsFile(Files.createTempDir()); - assertEquals(true, Files.equal(tmpFileOut, inFile)); - tmpFileOut.delete(); - assertEquals(dataObject.getUserMetadata().isEmpty(), true); - //System.out.println("My Metadata: "+dataObject.getUserMetadata()); - assertEquals( - Integer.parseInt(dataObject.getSystemMetadata().get( - "cdmi_size")), inFile.length()); - assertEquals(dataObject.getObjectName(), inFile.getName()); - assertEquals(dataObject.getObjectType(), "application/cdmi-object"); - assertEquals(dataObject.getParentURI(), "/" + containerName); - assertEquals(containerApi.getContainer(containerName) - .getChildren().contains(inFile.getName()), true); - dataApi.deleteDataObject(containerName, inFile.getName()); - assertEquals(containerApi.getContainer(containerName) - .getChildren().contains(dataObjectNameIn), false); - - // exercise create data object with none cdmi put with text file payload file. - //inFile = new File(System.getProperty("user.dir") - // + "/src/test/resources/Jellyfish.jpg"); // takes too long when working from home - inFile = new File(System.getProperty("user.dir") - + "/src/test/resources/yellow-flowers.jpg"); - assertEquals(true, inFile.isFile()); - payloadIn = new FilePayload(inFile); - payloadIn.setContentMetadata(BaseMutableContentMetadata.fromContentMetadata(payloadIn.getContentMetadata().toBuilder() - .contentType(MediaType.JPEG.toString()) - .build())); - dataNonCDMIContentTypeApi.createDataObject(containerName, inFile.getName(), - payloadIn); - System.out.println(containerApi.getContainer(containerName)); - //note dataApi.getDataObject when the data object is not a string - payloadOut = dataNonCDMIContentTypeApi.getDataObjectValue(containerName, inFile.getName()); - assertNotNull(payloadOut); - tmpFileOut = new File(Files.createTempDir(),"temp.jpg"); - fos = new FileOutputStream(tmpFileOut); - ByteStreams.copy(payloadOut.getInput(), fos); - fos.flush(); - fos.close(); - assertEquals(Files.equal(tmpFileOut, inFile),true); - tmpFileOut.delete(); - - assertEquals(containerApi.getContainer(containerName) - .getChildren().contains(inFile.getName()), true); - dataApi.deleteDataObject(containerName, inFile.getName()); - assertEquals(containerApi.getContainer(containerName) - .getChildren().contains(inFile.getName()), false); - + dataObject = dataNonCDMIContentTypeApi.get(dataObjectNameIn, DataObjectQueryParams.Builder.field("parentURI")); + assertNotNull(dataObject); + System.out.println(dataObject); + assertEquals(dataObject.getParentURI(), "/" + containerName); + dataObject = dataNonCDMIContentTypeApi.get(dataObjectNameIn, + DataObjectQueryParams.Builder.metadata().field("parentURI").field("objectName").field("objectType") + .field("mimetype")); + assertEquals(Integer.parseInt(dataObject.getSystemMetadata().get("cdmi_size")), value.length()); + assertEquals(dataObject.getObjectName(), dataObjectNameIn); + assertEquals(dataObject.getObjectType(), "application/cdmi-object"); + assertEquals(dataObject.getParentURI(), "/" + containerName); + assertEquals(dataObject.getMimetype(), MediaType.PLAIN_TEXT_UTF_8.toString()); - // exercise create data object with none cdmi put with payload inputStream riginating from string. - value = "Hello CDMI World non-cdmi inputStream originating from string"; - is = new ByteArrayInputStream(value.getBytes()); - payloadIn = new InputStreamPayload(is); - payloadIn.setContentMetadata(BaseMutableContentMetadata.fromContentMetadata(payloadIn.getContentMetadata().toBuilder() - .contentType(MediaType.PLAIN_TEXT_UTF_8.toString()) - .contentLength(new Long(value.length())) - .build())); - dataNonCDMIContentTypeApi.createDataObject(containerName, dataObjectNameIn, - payloadIn); - System.out.println(containerApi.getContainer(containerName)); - dataObject = dataApi.getDataObject(containerName, - dataObjectNameIn); - assertNotNull(dataObject); - System.out.println(dataObject); - System.out.println("value: " + dataObject.getValueAsString()); - assertEquals(dataObject.getValueAsString(), value); - assertNotNull(dataObject.getValueAsInputSupplier()); - assertEquals(CharStreams.toString(CharStreams.newReaderSupplier(dataObject - .getValueAsInputSupplier(Charsets.UTF_8),Charsets.UTF_8)), value); - assertEquals(dataObject.getUserMetadata().isEmpty(), true); - System.out.println("My Metadata: "+dataObject.getUserMetadata()); - assertEquals( - Integer.parseInt(dataObject.getSystemMetadata().get( - "cdmi_size")), value.length()); - assertEquals(dataObject.getObjectName(), dataObjectNameIn); - assertEquals(dataObject.getObjectType(), "application/cdmi-object"); - assertEquals(dataObject.getParentURI(), "/" + containerName); - assertEquals(containerApi.getContainer(containerName) - .getChildren().contains(dataObjectNameIn), true); - dataNonCDMIContentTypeApi.deleteDataObject(containerName, dataObjectNameIn); - assertEquals(containerApi.getContainer(containerName) - .getChildren().contains(dataObjectNameIn), false); + dataNonCDMIContentTypeApi.delete(dataObjectNameIn); + assertEquals(containerApi.get(containerName).getChildren().contains(dataObjectNameIn), false); - // exercise create data object with none cdmi put with payload inputStream originating from jpeg file. - inFile = new File(System.getProperty("user.dir") - + "/src/test/resources/yellow-flowers.jpg"); - assertEquals(true, inFile.isFile()); - FileInputStream fileInputStream = new FileInputStream(inFile); - payloadIn = new InputStreamPayload(fileInputStream); - payloadIn.setContentMetadata(BaseMutableContentMetadata.fromContentMetadata(payloadIn.getContentMetadata().toBuilder() - .contentType(MediaType.JPEG.toString()) - .contentLength(new Long(inFile.length())) - .build())); - dataNonCDMIContentTypeApi.createDataObject(containerName, inFile.getName(), - payloadIn); - System.out.println(containerApi.getContainer(containerName)); - payloadOut = dataNonCDMIContentTypeApi.getDataObjectValue(containerName, inFile.getName()); - assertNotNull(payloadOut); - tmpFileOut = new File(Files.createTempDir(),"temp.jpg"); - fos = new FileOutputStream(tmpFileOut); - ByteStreams.copy(payloadOut.getInput(), fos); - fos.flush(); - fos.close(); - assertEquals(Files.equal(tmpFileOut, inFile),true); - tmpFileOut.delete(); - - assertEquals(containerApi.getContainer(containerName) - .getChildren().contains(inFile.getName()), true); - dataApi.deleteDataObject(containerName, inFile.getName()); - assertEquals(containerApi.getContainer(containerName) - .getChildren().contains(inFile.getName()), false); + // exercise create data object with none cdmi put with payload byte array. + value = "Hello CDMI World non-cdmi byte array"; + bytes = value.getBytes(Charsets.UTF_8); + payloadIn = new ByteArrayPayload(bytes); + payloadIn.setContentMetadata(BaseMutableContentMetadata.fromContentMetadata(payloadIn.getContentMetadata() + .toBuilder().contentType(MediaType.PLAIN_TEXT_UTF_8.toString()).build())); + dataNonCDMIContentTypeApi.create(dataObjectNameIn, payloadIn); + System.out.println(containerApi.get(containerName)); + dataObject = dataApi.get(dataObjectNameIn); + assertNotNull(dataObject); + System.out.println(dataObject); + System.out.println("value: " + dataObject.getValueAsString()); + assertEquals(dataObject.getValueAsString(), value); + assertEquals(new String(dataObject.getValueAsByteArray()), value); + assertEquals(dataObject.getUserMetadata().isEmpty(), true); + assertEquals(Integer.parseInt(dataObject.getSystemMetadata().get("cdmi_size")), value.length()); + assertEquals(dataObject.getObjectName(), dataObjectNameIn); + assertEquals(dataObject.getObjectType(), "application/cdmi-object"); + assertEquals(dataObject.getParentURI(), "/" + containerName); + assertEquals(containerApi.get(containerName).getChildren().contains(dataObjectNameIn), true); + payloadOut = dataNonCDMIContentTypeApi.getValue(dataObjectNameIn); + assertNotNull(payloadOut); + assertEquals(Strings2.toString(payloadOut), value); - // exercise get with none cdmi get range. - value = "Hello CDMI World non-cdmi String"; - payloadIn = new StringPayload(value); - payloadIn.setContentMetadata(BaseMutableContentMetadata.fromContentMetadata(payloadIn.getContentMetadata().toBuilder() - .contentType(MediaType.PLAIN_TEXT_UTF_8.toString()) - .build())); - dataNonCDMIContentTypeApi.createDataObject(containerName, dataObjectNameIn, - payloadIn); + dataNonCDMIContentTypeApi.delete(dataObjectNameIn); + assertEquals(containerApi.get(containerName).getChildren().contains(dataObjectNameIn), false); - payloadOut = dataNonCDMIContentTypeApi.getDataObjectValue(containerName, dataObjectNameIn, "bytes=0-10"); - assertNotNull(payloadOut); - assertEquals(CharStreams.toString(new InputStreamReader(payloadOut.getInput(), "UTF-8")),value.substring(0, 11)); - assertEquals(payloadOut.getContentMetadata().getContentLength(),new Long(11)); - - payloadOut = dataNonCDMIContentTypeApi.getDataObjectValue(containerName, dataObjectNameIn, "bytes=11-20"); - assertNotNull(payloadOut); - assertEquals(CharStreams.toString(new InputStreamReader(payloadOut.getInput(), "UTF-8")),value.substring(11, 21)); - assertEquals(payloadOut.getContentMetadata().getContentLength(),new Long(10)); - - dataNonCDMIContentTypeApi.deleteDataObject(containerName, dataObjectNameIn); - assertEquals(containerApi.getContainer(containerName) - .getChildren().contains(dataObjectNameIn), false); + // exercise create data object with none cdmi put with payload file. + value = "Hello CDMI World non-cdmi File"; + Files.write(value, tmpFileIn, Charsets.UTF_8); + payloadIn = new FilePayload(tmpFileIn); + payloadIn.setContentMetadata(BaseMutableContentMetadata.fromContentMetadata(payloadIn.getContentMetadata() + .toBuilder().contentType(MediaType.PLAIN_TEXT_UTF_8.toString()).build())); - // exercise create data object with none cdmi partial. - // server does not actually support cdmi partial but - // trace allows me to see that request was constructed properly - value = "Hello CDMI World non-cdmi String"; - payloadIn = new StringPayload(value); - payloadIn.setContentMetadata(BaseMutableContentMetadata.fromContentMetadata(payloadIn.getContentMetadata().toBuilder() - .contentType(MediaType.PLAIN_TEXT_UTF_8.toString()) - .build())); - dataNonCDMIContentTypeApi.createDataObjectPartial(containerName, dataObjectNameIn, - payloadIn); - payloadOut = dataNonCDMIContentTypeApi.getDataObjectValue(containerName, dataObjectNameIn); - assertNotNull(payloadOut); - System.out.println("payload "+payloadOut); - - dataNonCDMIContentTypeApi.createDataObjectPartial(containerName, dataObjectNameIn, - payloadIn); - payloadOut = dataNonCDMIContentTypeApi.getDataObjectValue(containerName, dataObjectNameIn); - assertNotNull(payloadOut); - System.out.println("payload "+payloadOut); + dataNonCDMIContentTypeApi.create(dataObjectNameIn, payloadIn); + System.out.println(containerApi.get(containerName)); + dataObject = dataApi.get(dataObjectNameIn); + assertNotNull(dataObject); + System.out.println(dataObject); + System.out.println("value: " + dataObject.getValueAsString()); + assertEquals(dataObject.getValueAsString(), value); + tmpFileOut = dataObject.getValueAsFile(Files.createTempDir()); + assertEquals(true, Files.equal(tmpFileOut, tmpFileIn)); + tmpFileOut.delete(); + assertEquals(dataObject.getUserMetadata().isEmpty(), true); + System.out.println("My Metadata: " + dataObject.getUserMetadata()); + assertEquals(Integer.parseInt(dataObject.getSystemMetadata().get("cdmi_size")), value.length()); + assertEquals(dataObject.getObjectName(), dataObjectNameIn); + assertEquals(dataObject.getObjectType(), "application/cdmi-object"); + assertEquals(dataObject.getParentURI(), "/" + containerName); + assertEquals(containerApi.get(containerName).getChildren().contains(dataObjectNameIn), true); - - - dataNonCDMIContentTypeApi.createDataObject(containerName, dataObjectNameIn, - payloadIn); + payloadOut = dataNonCDMIContentTypeApi.getValue(dataObjectNameIn); + assertNotNull(payloadOut); + // assertEquals(Strings2.toString(payloadOut), value); + // byte[] _bytes = ByteStreams.toByteArray(payloadOut); + tmpFileOut = new File(Files.createTempDir(), "temp.txt"); + fos = new FileOutputStream(tmpFileOut); + ByteStreams.copy(payloadOut, fos); + fos.flush(); + fos.close(); + assertEquals(Files.equal(tmpFileOut, tmpFileIn), true); + tmpFileOut.delete(); + dataNonCDMIContentTypeApi.delete(dataObjectNameIn); + assertEquals(containerApi.get(containerName).getChildren().contains(dataObjectNameIn), false); - payloadOut = dataNonCDMIContentTypeApi.getDataObjectValue(containerName, dataObjectNameIn); - assertNotNull(payloadOut); - System.out.println("payload "+payloadOut); - - - } finally { - tmpFileIn.delete(); - containerApi.deleteContainer(containerName); + // exercise create data object with none cdmi put with text file payload file. + inFile = new File(System.getProperty("user.dir") + "/src/test/resources/container.json"); + assertEquals(true, inFile.isFile()); + payloadIn = new FilePayload(inFile); + payloadIn.setContentMetadata(BaseMutableContentMetadata.fromContentMetadata(payloadIn.getContentMetadata() + .toBuilder().contentType(MediaType.JSON_UTF_8.toString()).build())); - } + dataNonCDMIContentTypeApi.create(inFile.getName(), payloadIn); + System.out.println(containerApi.get(containerName)); + dataObject = dataApi.get(inFile.getName()); + assertNotNull(dataObject); + System.out.println(dataObject); + // System.out.println("value: " + dataObject.getValueAsString()); + // assertEquals(dataObject.getValueAsString(), value); + tmpFileOut = dataObject.getValueAsFile(Files.createTempDir()); + assertEquals(true, Files.equal(tmpFileOut, inFile)); + tmpFileOut.delete(); + assertEquals(dataObject.getUserMetadata().isEmpty(), true); + // System.out.println("My Metadata: "+dataObject.getUserMetadata()); + assertEquals(Integer.parseInt(dataObject.getSystemMetadata().get("cdmi_size")), inFile.length()); + assertEquals(dataObject.getObjectName(), inFile.getName()); + assertEquals(dataObject.getObjectType(), "application/cdmi-object"); + assertEquals(dataObject.getParentURI(), "/" + containerName); + assertEquals(containerApi.get(containerName).getChildren().contains(inFile.getName()), true); + dataApi.delete(inFile.getName()); + assertEquals(containerApi.get(containerName).getChildren().contains(dataObjectNameIn), false); - } + // exercise create data object with none cdmi put with text file payload file. + // inFile = new File(System.getProperty("user.dir") + // + "/src/test/resources/Jellyfish.jpg"); // takes too long when working from home + inFile = new File(System.getProperty("user.dir") + "/src/test/resources/yellow-flowers.jpg"); + assertEquals(true, inFile.isFile()); + payloadIn = new FilePayload(inFile); + payloadIn.setContentMetadata(BaseMutableContentMetadata.fromContentMetadata(payloadIn.getContentMetadata() + .toBuilder().contentType(MediaType.JPEG.toString()).build())); + dataNonCDMIContentTypeApi.create(inFile.getName(), payloadIn); + System.out.println(containerApi.get(containerName)); + // note dataApi.get when the data object is not a string + payloadOut = dataNonCDMIContentTypeApi.getValue(inFile.getName()); + assertNotNull(payloadOut); + tmpFileOut = new File(Files.createTempDir(), "temp.jpg"); + fos = new FileOutputStream(tmpFileOut); + ByteStreams.copy(payloadOut, fos); + fos.flush(); + fos.close(); + assertEquals(Files.equal(tmpFileOut, inFile), true); + tmpFileOut.delete(); + + assertEquals(containerApi.get(containerName).getChildren().contains(inFile.getName()), true); + dataApi.delete(inFile.getName()); + assertEquals(containerApi.get(containerName).getChildren().contains(inFile.getName()), false); + + // exercise create data object with none cdmi put with payload inputStream riginating from + // string. + value = "Hello CDMI World non-cdmi inputStream originating from string"; + is = new ByteArrayInputStream(value.getBytes()); + payloadIn = new InputStreamPayload(is); + payloadIn.setContentMetadata(BaseMutableContentMetadata.fromContentMetadata(payloadIn.getContentMetadata() + .toBuilder().contentType(MediaType.PLAIN_TEXT_UTF_8.toString()) + .contentLength(new Long(value.length())).build())); + dataNonCDMIContentTypeApi.create(dataObjectNameIn, payloadIn); + System.out.println(containerApi.get(containerName)); + dataObject = dataApi.get(dataObjectNameIn); + assertNotNull(dataObject); + System.out.println(dataObject); + System.out.println("value: " + dataObject.getValueAsString()); + assertEquals(dataObject.getValueAsString(), value); + assertNotNull(dataObject.getValueAsInputSupplier()); + assertEquals(CharStreams.toString(CharStreams.newReaderSupplier( + dataObject.getValueAsInputSupplier(Charsets.UTF_8), Charsets.UTF_8)), value); + assertEquals(dataObject.getUserMetadata().isEmpty(), true); + System.out.println("My Metadata: " + dataObject.getUserMetadata()); + assertEquals(Integer.parseInt(dataObject.getSystemMetadata().get("cdmi_size")), value.length()); + assertEquals(dataObject.getObjectName(), dataObjectNameIn); + assertEquals(dataObject.getObjectType(), "application/cdmi-object"); + assertEquals(dataObject.getParentURI(), "/" + containerName); + assertEquals(containerApi.get(containerName).getChildren().contains(dataObjectNameIn), true); + dataNonCDMIContentTypeApi.delete(dataObjectNameIn); + assertEquals(containerApi.get(containerName).getChildren().contains(dataObjectNameIn), false); + + // exercise create data object with none cdmi put with payload inputStream originating from + // jpeg file. + inFile = new File(System.getProperty("user.dir") + "/src/test/resources/yellow-flowers.jpg"); + assertEquals(true, inFile.isFile()); + FileInputStream fileInputStream = new FileInputStream(inFile); + payloadIn = new InputStreamPayload(fileInputStream); + payloadIn.setContentMetadata(BaseMutableContentMetadata.fromContentMetadata(payloadIn.getContentMetadata() + .toBuilder().contentType(MediaType.JPEG.toString()).contentLength(new Long(inFile.length())).build())); + dataNonCDMIContentTypeApi.create(inFile.getName(), payloadIn); + System.out.println(containerApi.get(containerName)); + payloadOut = dataNonCDMIContentTypeApi.getValue(inFile.getName()); + assertNotNull(payloadOut); + tmpFileOut = new File(Files.createTempDir(), "temp.jpg"); + fos = new FileOutputStream(tmpFileOut); + ByteStreams.copy(payloadOut, fos); + fos.flush(); + fos.close(); + assertEquals(Files.equal(tmpFileOut, inFile), true); + tmpFileOut.delete(); + + assertEquals(containerApi.get(containerName).getChildren().contains(inFile.getName()), true); + dataApi.delete(inFile.getName()); + assertEquals(containerApi.get(containerName).getChildren().contains(inFile.getName()), false); + + // exercise get with none cdmi get range. + value = "Hello CDMI World non-cdmi String"; + payloadIn = new StringPayload(value); + payloadIn.setContentMetadata(BaseMutableContentMetadata.fromContentMetadata(payloadIn.getContentMetadata() + .toBuilder().contentType(MediaType.PLAIN_TEXT_UTF_8.toString()).build())); + dataNonCDMIContentTypeApi.create(dataObjectNameIn, payloadIn); + + payloadOut = dataNonCDMIContentTypeApi.getValue(dataObjectNameIn, "bytes=0-10"); + assertNotNull(payloadOut); + assertEquals(Strings2.toString(payloadOut), value.substring(0, 11)); + assertEquals(payloadOut.getContentMetadata().getContentLength(), new Long(11)); + + payloadOut = dataNonCDMIContentTypeApi.getValue(dataObjectNameIn, "bytes=11-20"); + assertNotNull(payloadOut); + assertEquals(Strings2.toString(payloadOut), value.substring(11, 21)); + assertEquals(payloadOut.getContentMetadata().getContentLength(), new Long(10)); + + dataNonCDMIContentTypeApi.delete(dataObjectNameIn); + assertEquals(containerApi.get(containerName).getChildren().contains(dataObjectNameIn), false); + + // exercise create data object with none cdmi partial. + // server does not actually support cdmi partial but + // trace allows me to see that request was constructed properly + value = "Hello CDMI World non-cdmi String"; + payloadIn = new StringPayload(value); + payloadIn.setContentMetadata(BaseMutableContentMetadata.fromContentMetadata(payloadIn.getContentMetadata() + .toBuilder().contentType(MediaType.PLAIN_TEXT_UTF_8.toString()).build())); + dataNonCDMIContentTypeApi.createPartial(dataObjectNameIn, payloadIn); + payloadOut = dataNonCDMIContentTypeApi.getValue(dataObjectNameIn); + assertNotNull(payloadOut); + System.out.println("payload " + payloadOut); + + dataNonCDMIContentTypeApi.createPartial(dataObjectNameIn, payloadIn); + payloadOut = dataNonCDMIContentTypeApi.getValue(dataObjectNameIn); + assertNotNull(payloadOut); + System.out.println("payload " + payloadOut); + + dataNonCDMIContentTypeApi.create(dataObjectNameIn, payloadIn); + + payloadOut = dataNonCDMIContentTypeApi.getValue(dataObjectNameIn); + assertNotNull(payloadOut); + System.out.println("payload " + payloadOut); + + } finally { + tmpFileIn.delete(); + containerApi.delete(containerName); + + } + + } } diff --git a/labs/cdmi/src/test/java/org/jclouds/snia/cdmi/v1/internal/BaseCDMIApiLiveTest.java b/labs/cdmi/src/test/java/org/jclouds/snia/cdmi/v1/internal/BaseCDMIApiLiveTest.java index c7afe80d70..1c3e412632 100644 --- a/labs/cdmi/src/test/java/org/jclouds/snia/cdmi/v1/internal/BaseCDMIApiLiveTest.java +++ b/labs/cdmi/src/test/java/org/jclouds/snia/cdmi/v1/internal/BaseCDMIApiLiveTest.java @@ -20,9 +20,9 @@ package org.jclouds.snia.cdmi.v1.internal; import org.jclouds.apis.BaseContextLiveTest; import org.jclouds.rest.RestContext; +import org.jclouds.snia.cdmi.v1.CDMIApi; import org.jclouds.snia.cdmi.v1.CDMIApiMetadata; import org.jclouds.snia.cdmi.v1.CDMIAsyncApi; -import org.jclouds.snia.cdmi.v1.CDMIApi; import org.testng.annotations.AfterGroups; import org.testng.annotations.BeforeGroups; import org.testng.annotations.Test; diff --git a/labs/cdmi/src/test/java/org/jclouds/snia/cdmi/v1/options/ListContainersOptionsTest.java b/labs/cdmi/src/test/java/org/jclouds/snia/cdmi/v1/options/ListContainersOptionsTest.java index 7753483dda..d533ebfd3f 100644 --- a/labs/cdmi/src/test/java/org/jclouds/snia/cdmi/v1/options/ListContainersOptionsTest.java +++ b/labs/cdmi/src/test/java/org/jclouds/snia/cdmi/v1/options/ListContainersOptionsTest.java @@ -22,7 +22,7 @@ import static org.jclouds.snia.cdmi.v1.options.ListContainersOptions.Builder.lim import static org.jclouds.snia.cdmi.v1.options.ListContainersOptions.Builder.marker; import static org.testng.Assert.assertEquals; -import java.util.Collections; +import com.google.common.collect.ImmutableList; import org.jclouds.http.options.HttpRequestOptions; import org.testng.annotations.Test; @@ -40,6 +40,7 @@ public class ListContainersOptionsTest { assert HttpRequestOptions.class.isAssignableFrom(ListContainersOptions.class); assert !String.class.isAssignableFrom(ListContainersOptions.class); } + @Test public void testNoOptionsQueryString() { HttpRequestOptions options = new ListContainersOptions(); @@ -50,19 +51,19 @@ public class ListContainersOptionsTest { public void testMarker() { ListContainersOptions options = new ListContainersOptions(); options.marker("test"); - assertEquals(options.buildQueryParameters().get("marker"), Collections.singletonList("test")); + assertEquals(options.buildQueryParameters().get("marker"), ImmutableList.of("test")); } @Test public void testNullMarker() { ListContainersOptions options = new ListContainersOptions(); - assertEquals(options.buildQueryParameters().get("marker"), Collections.EMPTY_LIST); + assertEquals(options.buildQueryParameters().get("marker"), ImmutableList.of()); } @Test public void testMarkerStatic() { ListContainersOptions options = marker("test"); - assertEquals(options.buildQueryParameters().get("marker"), Collections.singletonList("test")); + assertEquals(options.buildQueryParameters().get("marker"), ImmutableList.of("test")); } @Test(expectedExceptions = NullPointerException.class) @@ -74,19 +75,19 @@ public class ListContainersOptionsTest { public void testLimit() { ListContainersOptions options = new ListContainersOptions(); options.limit(1000); - assertEquals(options.buildQueryParameters().get("limit"), Collections.singletonList("1000")); + assertEquals(options.buildQueryParameters().get("limit"), ImmutableList.of("1000")); } @Test public void testNullLimit() { ListContainersOptions options = new ListContainersOptions(); - assertEquals(options.buildQueryParameters().get("limit"), Collections.EMPTY_LIST); + assertEquals(options.buildQueryParameters().get("limit"), ImmutableList.of()); } @Test public void testLimitStatic() { ListContainersOptions options = limit(1000); - assertEquals(options.buildQueryParameters().get("limit"), Collections.singletonList("1000")); + assertEquals(options.buildQueryParameters().get("limit"), ImmutableList.of("1000")); } @Test(expectedExceptions = IllegalStateException.class) diff --git a/labs/cdmi/src/test/java/org/jclouds/snia/cdmi/v1/parse/ParseContainerTest.java b/labs/cdmi/src/test/java/org/jclouds/snia/cdmi/v1/parse/ParseContainerTest.java index bdb4f8bd3b..af43df3fd3 100644 --- a/labs/cdmi/src/test/java/org/jclouds/snia/cdmi/v1/parse/ParseContainerTest.java +++ b/labs/cdmi/src/test/java/org/jclouds/snia/cdmi/v1/parse/ParseContainerTest.java @@ -44,17 +44,9 @@ public class ParseContainerTest extends BaseItemParserTest { @Override @Consumes(MediaType.APPLICATION_JSON) public Container expected() { - return Container.builder() - .objectType("application/cdmi-container") - .objectID("00007E7F00102E230ED82694DAA975D2") - .objectName("MyContainer/") - .parentURI("/") - .metadata(ImmutableMap.builder() - .put("cdmi_size", new JsonBall("\"83\"")) - .build()) - .children(ImmutableSet.builder() - .add("MyDataObject.txt") - .build()) - .build(); + return Container.builder().objectType("application/cdmi-container").objectID("00007E7F00102E230ED82694DAA975D2") + .objectName("MyContainer/").parentURI("/") + .metadata(ImmutableMap. builder().put("cdmi_size", new JsonBall("\"83\"")).build()) + .children(ImmutableSet. builder().add("MyDataObject.txt").build()).build(); } } diff --git a/labs/cloudstack-ec2/pom.xml b/labs/cloudstack-ec2/pom.xml index 8911b73cfe..9b8848bfe3 100644 --- a/labs/cloudstack-ec2/pom.xml +++ b/labs/cloudstack-ec2/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.labs diff --git a/labs/dmtf/pom.xml b/labs/dmtf/pom.xml index 996c936a41..e62c7da0f1 100644 --- a/labs/dmtf/pom.xml +++ b/labs/dmtf/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.labs diff --git a/labs/dmtf/src/main/java/org/jclouds/dmtf/cim/ResourceAllocationSettingData.java b/labs/dmtf/src/main/java/org/jclouds/dmtf/cim/ResourceAllocationSettingData.java index 27e966b67c..e6b6165ecf 100644 --- a/labs/dmtf/src/main/java/org/jclouds/dmtf/cim/ResourceAllocationSettingData.java +++ b/labs/dmtf/src/main/java/org/jclouds/dmtf/cim/ResourceAllocationSettingData.java @@ -24,7 +24,6 @@ import static org.jclouds.dmtf.DMTFConstants.CIM_RASD_NS; import static org.jclouds.dmtf.DMTFConstants.OVF_NS; import java.math.BigInteger; -import java.util.Collections; import java.util.Map; import java.util.Set; @@ -584,8 +583,8 @@ public class ResourceAllocationSettingData { this.virtualQuantity = builder.virtualQuantity; this.virtualQuantityUnits = builder.virtualQuantityUnits; this.weight = builder.weight; - this.connections = builder.connections != null ? ImmutableSet.copyOf(builder.connections) : Collections.emptySet(); - this.hostResources = builder.hostResources != null ? ImmutableSet.copyOf(builder.hostResources) : Collections.emptySet(); + this.connections = builder.connections != null ? ImmutableSet.copyOf(builder.connections) : ImmutableSet.of(); + this.hostResources = builder.hostResources != null ? ImmutableSet.copyOf(builder.hostResources) : ImmutableSet.of(); } protected ResourceAllocationSettingData() { @@ -904,4 +903,4 @@ public class ResourceAllocationSettingData { equal(this.weight, that.weight); } -} \ No newline at end of file +} diff --git a/labs/dmtf/src/main/java/org/jclouds/dmtf/ovf/ProductSection.java b/labs/dmtf/src/main/java/org/jclouds/dmtf/ovf/ProductSection.java index f75f8db476..d0daa1cbd6 100644 --- a/labs/dmtf/src/main/java/org/jclouds/dmtf/ovf/ProductSection.java +++ b/labs/dmtf/src/main/java/org/jclouds/dmtf/ovf/ProductSection.java @@ -22,7 +22,6 @@ import static com.google.common.base.Objects.equal; import static com.google.common.base.Preconditions.checkNotNull; import static org.jclouds.dmtf.DMTFConstants.CIM_NS; -import java.util.Collections; import java.util.Set; import javax.xml.bind.annotation.XmlElement; @@ -185,7 +184,7 @@ public class ProductSection extends SectionType { this.productUrl = builder.productUrl; this.vendorUrl = builder.vendorUrl; this.appUrl = builder.appUrl; - this.properties = builder.properties != null ? ImmutableSet.copyOf(checkNotNull(builder.properties, "properties")) : Collections.emptySet(); + this.properties = builder.properties != null ? ImmutableSet.copyOf(checkNotNull(builder.properties, "properties")) : ImmutableSet.of(); } private ProductSection() { diff --git a/labs/dmtf/src/main/java/org/jclouds/dmtf/ovf/StartupSection.java b/labs/dmtf/src/main/java/org/jclouds/dmtf/ovf/StartupSection.java index 03f70b95ff..cf3799f96c 100644 --- a/labs/dmtf/src/main/java/org/jclouds/dmtf/ovf/StartupSection.java +++ b/labs/dmtf/src/main/java/org/jclouds/dmtf/ovf/StartupSection.java @@ -21,7 +21,6 @@ package org.jclouds.dmtf.ovf; import static com.google.common.base.Objects.equal; import static com.google.common.base.Preconditions.checkNotNull; -import java.util.Collections; import java.util.List; import javax.xml.bind.annotation.XmlElement; @@ -94,7 +93,7 @@ public class StartupSection extends SectionType { public StartupSection(Builder builder) { super(builder); - this.items = (items != null) ? ImmutableList.copyOf(builder.items) : Collections.emptyList(); + this.items = (items != null) ? ImmutableList.copyOf(builder.items) : ImmutableList.of(); } /** diff --git a/labs/elb/pom.xml b/labs/elb/pom.xml index e490da9497..64dbe4ea06 100644 --- a/labs/elb/pom.xml +++ b/labs/elb/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.labs diff --git a/labs/elb/src/main/java/org/jclouds/elb/features/LoadBalancerApi.java b/labs/elb/src/main/java/org/jclouds/elb/features/LoadBalancerApi.java index 3c2f0d3379..2f31b15f2b 100644 --- a/labs/elb/src/main/java/org/jclouds/elb/features/LoadBalancerApi.java +++ b/labs/elb/src/main/java/org/jclouds/elb/features/LoadBalancerApi.java @@ -39,16 +39,16 @@ import org.jclouds.javax.annotation.Nullable; @Timeout(duration = 30, timeUnit = TimeUnit.SECONDS) public interface LoadBalancerApi { - String createLoadBalancerListeningInAvailabilityZones(String name, Iterable listeners, + String createListeningInAvailabilityZones(String name, Iterable listeners, Iterable availabilityZones); - String createLoadBalancerListeningInAvailabilityZones(String name, Listener listeners, + String createListeningInAvailabilityZones(String name, Listener listeners, Iterable availabilityZones); - String createLoadBalancerListeningInSubnetAssignedToSecurityGroups(String name, String subnetId, + String createListeningInSubnetAssignedToSecurityGroups(String name, String subnetId, Iterable securityGroupIds); - String createLoadBalancerListeningInSubnetsAssignedToSecurityGroups(String name, Iterable subnetIds, + String createListeningInSubnetsAssignedToSecurityGroups(String name, Iterable subnetIds, Iterable securityGroupIds); diff --git a/labs/elb/src/main/java/org/jclouds/elb/features/LoadBalancerAsyncApi.java b/labs/elb/src/main/java/org/jclouds/elb/features/LoadBalancerAsyncApi.java index a38804185f..a88b74c23b 100644 --- a/labs/elb/src/main/java/org/jclouds/elb/features/LoadBalancerAsyncApi.java +++ b/labs/elb/src/main/java/org/jclouds/elb/features/LoadBalancerAsyncApi.java @@ -45,6 +45,8 @@ import org.jclouds.rest.annotations.RequestFilters; import org.jclouds.rest.annotations.Transform; import org.jclouds.rest.annotations.VirtualHost; import org.jclouds.rest.annotations.XMLResponseParser; +import org.jclouds.rest.functions.ReturnEmptyIterableWithMarkerOnNotFoundOr404; +import org.jclouds.rest.functions.ReturnEmptyPagedIterableOnNotFoundOr404; import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; import org.jclouds.rest.functions.ReturnVoidOnNotFoundOr404; @@ -63,47 +65,47 @@ import com.google.common.util.concurrent.ListenableFuture; @VirtualHost public interface LoadBalancerAsyncApi { /** - * @see LoadBalancerApi#createLoadBalancerListeningInAvailabilityZones() + * @see LoadBalancerApi#createListeningInAvailabilityZones() */ @POST @Path("/") @XMLResponseParser(CreateLoadBalancerResponseHandler.class) @FormParams(keys = ACTION, values = "CreateLoadBalancer") - ListenableFuture createLoadBalancerListeningInAvailabilityZones(@FormParam("LoadBalancerName") String name, + ListenableFuture createListeningInAvailabilityZones(@FormParam("LoadBalancerName") String name, @BinderParam(BindListenersToFormParams.class) Listener listeners, @BinderParam(BindAvailabilityZonesToIndexedFormParams.class) Iterable availabilityZones); /** - * @see LoadBalancerApi#createLoadBalancerListeningInAvailabilityZones() + * @see LoadBalancerApi#createListeningInAvailabilityZones() */ @POST @Path("/") @XMLResponseParser(CreateLoadBalancerResponseHandler.class) @FormParams(keys = ACTION, values = "CreateLoadBalancer") - ListenableFuture createLoadBalancerListeningInAvailabilityZones(@FormParam("LoadBalancerName") String name, + ListenableFuture createListeningInAvailabilityZones(@FormParam("LoadBalancerName") String name, @BinderParam(BindListenersToFormParams.class) Iterable listeners, @BinderParam(BindAvailabilityZonesToIndexedFormParams.class) Iterable availabilityZones); /** - * @see LoadBalancerApi#createLoadBalancerListeningInSubnetAssignedToSecurityGroups() + * @see LoadBalancerApi#createListeningInSubnetAssignedToSecurityGroups() */ @POST @Path("/") @XMLResponseParser(CreateLoadBalancerResponseHandler.class) @FormParams(keys = ACTION, values = "CreateLoadBalancer") - ListenableFuture createLoadBalancerListeningInSubnetAssignedToSecurityGroups( + ListenableFuture createListeningInSubnetAssignedToSecurityGroups( @FormParam("LoadBalancerName") String name, @FormParam("Subnets.member.1") String subnetId, @BinderParam(BindSecurityGroupsToIndexedFormParams.class) Iterable securityGroupIds); /** - * @see LoadBalancerApi#createLoadBalancerListeningInSubnetsAssignedToSecurityGroups() + * @see LoadBalancerApi#createListeningInSubnetsAssignedToSecurityGroups() */ @POST @Path("/") @XMLResponseParser(CreateLoadBalancerResponseHandler.class) @FormParams(keys = ACTION, values = "CreateLoadBalancer") - ListenableFuture createLoadBalancerListeningInSubnetsAssignedToSecurityGroups( + ListenableFuture createListeningInSubnetsAssignedToSecurityGroups( @FormParam("LoadBalancerName") String name, @BinderParam(BindSubnetsToIndexedFormParams.class) Iterable subnetIds, @BinderParam(BindSecurityGroupsToIndexedFormParams.class) Iterable securityGroupIds); @@ -125,6 +127,7 @@ public interface LoadBalancerAsyncApi { @Path("/") @XMLResponseParser(DescribeLoadBalancersResultHandler.class) @Transform(LoadBalancersToPagedIterable.class) + @ExceptionParser(ReturnEmptyPagedIterableOnNotFoundOr404.class) @FormParams(keys = "Action", values = "DescribeLoadBalancers") ListenableFuture> list(); @@ -134,6 +137,7 @@ public interface LoadBalancerAsyncApi { @POST @Path("/") @XMLResponseParser(DescribeLoadBalancersResultHandler.class) + @ExceptionParser(ReturnEmptyIterableWithMarkerOnNotFoundOr404.class) @FormParams(keys = "Action", values = "DescribeLoadBalancers") ListenableFuture> list(ListLoadBalancersOptions options); diff --git a/labs/elb/src/main/java/org/jclouds/elb/loadbalancer/strategy/ELBLoadBalanceNodesStrategy.java b/labs/elb/src/main/java/org/jclouds/elb/loadbalancer/strategy/ELBLoadBalanceNodesStrategy.java index e7f901c34b..be5a952183 100644 --- a/labs/elb/src/main/java/org/jclouds/elb/loadbalancer/strategy/ELBLoadBalanceNodesStrategy.java +++ b/labs/elb/src/main/java/org/jclouds/elb/loadbalancer/strategy/ELBLoadBalanceNodesStrategy.java @@ -82,7 +82,7 @@ public class ELBLoadBalanceNodesStrategy implements LoadBalanceNodesStrategy { logger.debug(">> creating loadBalancer(%s) in zones(%s)", name, zonesDesired); try { - String dnsName = api.getLoadBalancerApiForRegion(region).createLoadBalancerListeningInAvailabilityZones( + String dnsName = api.getLoadBalancerApiForRegion(region).createListeningInAvailabilityZones( name, ImmutableSet.of(Listener.builder().port(loadBalancerPort).instancePort(instancePort) .protocol(Protocol.valueOf(protocol)).build()), zonesDesired); diff --git a/labs/elb/src/test/java/org/jclouds/elb/features/LoadBalancerApiExpectTest.java b/labs/elb/src/test/java/org/jclouds/elb/features/LoadBalancerApiExpectTest.java index ab4ddb4778..f82a6eddef 100644 --- a/labs/elb/src/test/java/org/jclouds/elb/features/LoadBalancerApiExpectTest.java +++ b/labs/elb/src/test/java/org/jclouds/elb/features/LoadBalancerApiExpectTest.java @@ -24,6 +24,7 @@ import static org.testng.Assert.assertNull; import java.util.TimeZone; +import org.jclouds.collect.IterableWithMarkers; import org.jclouds.elb.ELBApi; import org.jclouds.elb.domain.LoadBalancer; import org.jclouds.elb.internal.BaseELBApiExpectTest; @@ -31,7 +32,6 @@ import org.jclouds.elb.parse.DescribeLoadBalancersResponseTest; import org.jclouds.elb.parse.GetLoadBalancerResponseTest; import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpResponse; -import org.jclouds.rest.ResourceNotFoundException; import org.testng.annotations.Test; import com.google.common.collect.ImmutableSet; @@ -197,8 +197,6 @@ public class LoadBalancerApiExpectTest extends BaseELBApiExpectTest { assertEquals(ImmutableSet.copyOf(Iterables.concat(apiWhenExist.getLoadBalancerApiForRegion("eu-west-1").list())), ImmutableSet.of(lb1, lb2)); } - // TODO: this should really be an empty set - @Test(expectedExceptions = ResourceNotFoundException.class) public void testListWhenResponseIs404() throws Exception { HttpResponse listResponse = HttpResponse.builder().statusCode(404).build(); @@ -206,7 +204,8 @@ public class LoadBalancerApiExpectTest extends BaseELBApiExpectTest { ELBApi apiWhenDontExist = requestSendsResponse( list, listResponse); - apiWhenDontExist.getLoadBalancerApi().list(); + assertEquals(apiWhenDontExist.getLoadBalancerApi().list().get(0), IterableWithMarkers.EMPTY); + } public void testListWithOptionsWhenResponseIs2xx() throws Exception { diff --git a/labs/fgcp-au/pom.xml b/labs/fgcp-au/pom.xml index e32cc3d801..e998446166 100644 --- a/labs/fgcp-au/pom.xml +++ b/labs/fgcp-au/pom.xml @@ -25,7 +25,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.labs diff --git a/labs/fgcp-au/src/main/java/org/jclouds/fujitsu/fgcp/FGCPAUProviderMetadata.java b/labs/fgcp-au/src/main/java/org/jclouds/fujitsu/fgcp/FGCPAUProviderMetadata.java index b17d6caf96..b3efbe729a 100644 --- a/labs/fgcp-au/src/main/java/org/jclouds/fujitsu/fgcp/FGCPAUProviderMetadata.java +++ b/labs/fgcp-au/src/main/java/org/jclouds/fujitsu/fgcp/FGCPAUProviderMetadata.java @@ -30,48 +30,51 @@ import org.jclouds.providers.internal.BaseProviderMetadata; */ public class FGCPAUProviderMetadata extends FGCPProviderMetadata { - public static Builder builder() { - return new Builder(); - } + /** The serialVersionUID */ + private static final long serialVersionUID = 1735901960026547803L; - public FGCPAUProviderMetadata() { - super(builder()); - } + public static Builder builder() { + return new Builder(); + } - public FGCPAUProviderMetadata(Builder builder) { - super(builder); - } + public FGCPAUProviderMetadata() { + super(builder()); + } - @Override - public Builder toBuilder() { - return builder().fromProviderMetadata(this); - } + public FGCPAUProviderMetadata(Builder builder) { + super(builder); + } - public static class Builder extends BaseProviderMetadata.Builder { + @Override + public Builder toBuilder() { + return builder().fromProviderMetadata(this); + } - protected Builder() { - id("fgcp-au") - .name("Fujitsu Global Cloud Platform (FGCP) - AU") - .apiMetadata(new FGCPApiMetadata()) - .homepage( - URI.create("http://www.fujitsu.com/global/solutions/cloud/solutions/global-cloud-platform/index.html")) - .console(URI.create("http://globalcloud.fujitsu.com.au")) - .defaultProperties(FGCPApiMetadata.defaultProperties()) - .iso3166Codes("AU-NSW") - .endpoint( - "https://api.globalcloud.fujitsu.com.au/ovissapi/endpoint") - .defaultProperties(FGCPProviderMetadata.defaultProperties()); - } + public static class Builder extends BaseProviderMetadata.Builder { - @Override - public FGCPAUProviderMetadata build() { - return new FGCPAUProviderMetadata(this); - } + protected Builder() { + id("fgcp-au") + .name("Fujitsu Global Cloud Platform (FGCP) - AU") + .apiMetadata(new FGCPApiMetadata()) + .homepage( + URI.create("http://www.fujitsu.com/global/solutions/cloud/solutions/global-cloud-platform/index.html")) + .console(URI.create("http://globalcloud.fujitsu.com.au")) + .defaultProperties(FGCPApiMetadata.defaultProperties()) + .iso3166Codes("AU-NSW") + .endpoint( + "https://api.globalcloud.fujitsu.com.au/ovissapi/endpoint") + .defaultProperties(FGCPProviderMetadata.defaultProperties()); + } - @Override - public Builder fromProviderMetadata(ProviderMetadata in) { - super.fromProviderMetadata(in); - return this; - } - } + @Override + public FGCPAUProviderMetadata build() { + return new FGCPAUProviderMetadata(this); + } + + @Override + public Builder fromProviderMetadata(ProviderMetadata in) { + super.fromProviderMetadata(in); + return this; + } + } } \ No newline at end of file diff --git a/labs/fgcp-au/src/test/java/org/jclouds/fujitsu/fgcp/FGCPAUProviderTest.java b/labs/fgcp-au/src/test/java/org/jclouds/fujitsu/fgcp/FGCPAUProviderTest.java index 9a2ddbce86..fa37d4d2f2 100644 --- a/labs/fgcp-au/src/test/java/org/jclouds/fujitsu/fgcp/FGCPAUProviderTest.java +++ b/labs/fgcp-au/src/test/java/org/jclouds/fujitsu/fgcp/FGCPAUProviderTest.java @@ -28,7 +28,7 @@ import org.testng.annotations.Test; public class FGCPAUProviderTest extends BaseProviderMetadataTest { public FGCPAUProviderTest() { - super(new FGCPAUProviderMetadata(), new FGCPApiMetadata()); + super(new FGCPAUProviderMetadata(), new FGCPApiMetadata()); } } diff --git a/labs/fgcp-au/src/test/java/org/jclouds/fujitsu/fgcp/compute/FGCPAUTemplateBuilderLiveTest.java b/labs/fgcp-au/src/test/java/org/jclouds/fujitsu/fgcp/compute/FGCPAUTemplateBuilderLiveTest.java index 30f12dea7e..b3881e66df 100644 --- a/labs/fgcp-au/src/test/java/org/jclouds/fujitsu/fgcp/compute/FGCPAUTemplateBuilderLiveTest.java +++ b/labs/fgcp-au/src/test/java/org/jclouds/fujitsu/fgcp/compute/FGCPAUTemplateBuilderLiveTest.java @@ -30,14 +30,14 @@ import com.google.common.collect.ImmutableSet; */ @Test(groups = "live", enabled = true, singleThreaded = true, testName = "FGCPAUTemplateBuilderLiveTest") public class FGCPAUTemplateBuilderLiveTest extends - FGCPBaseTemplateBuilderLiveTest { + FGCPBaseTemplateBuilderLiveTest { - public FGCPAUTemplateBuilderLiveTest() { - provider = "fgcp-au"; - } + public FGCPAUTemplateBuilderLiveTest() { + provider = "fgcp-au"; + } - @Override - protected Set getIso3166Codes() { - return ImmutableSet. of("AU-NSW"); - } + @Override + protected Set getIso3166Codes() { + return ImmutableSet. of("AU-NSW"); + } } diff --git a/labs/fgcp-au/src/test/java/org/jclouds/fujitsu/fgcp/compute/config/FGCPAUComputeServiceLiveTest.java b/labs/fgcp-au/src/test/java/org/jclouds/fujitsu/fgcp/compute/config/FGCPAUComputeServiceLiveTest.java index 49c23ffe47..15f8ab1c81 100644 --- a/labs/fgcp-au/src/test/java/org/jclouds/fujitsu/fgcp/compute/config/FGCPAUComputeServiceLiveTest.java +++ b/labs/fgcp-au/src/test/java/org/jclouds/fujitsu/fgcp/compute/config/FGCPAUComputeServiceLiveTest.java @@ -29,9 +29,9 @@ import org.testng.annotations.Test; @Test(groups = "live", enabled = true, singleThreaded = true, testName = "FGCPAUComputeServiceLiveTest") public class FGCPAUComputeServiceLiveTest extends FGCPBaseComputeServiceLiveTest { - @Override - public void setServiceDefaults() { - provider = "fgcp-au"; - } + @Override + public void setServiceDefaults() { + provider = "fgcp-au"; + } } diff --git a/labs/fgcp-de/pom.xml b/labs/fgcp-de/pom.xml index 6aa954ab0e..77a372674a 100644 --- a/labs/fgcp-de/pom.xml +++ b/labs/fgcp-de/pom.xml @@ -25,7 +25,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.labs diff --git a/labs/fgcp-de/src/main/java/org/jclouds/fujitsu/fgcp/FGCPDEProviderMetadata.java b/labs/fgcp-de/src/main/java/org/jclouds/fujitsu/fgcp/FGCPDEProviderMetadata.java index db087a580f..2868f3591b 100644 --- a/labs/fgcp-de/src/main/java/org/jclouds/fujitsu/fgcp/FGCPDEProviderMetadata.java +++ b/labs/fgcp-de/src/main/java/org/jclouds/fujitsu/fgcp/FGCPDEProviderMetadata.java @@ -30,50 +30,50 @@ import org.jclouds.providers.internal.BaseProviderMetadata; */ public class FGCPDEProviderMetadata extends FGCPProviderMetadata { - private static final long serialVersionUID = -8498457904032259345L; + private static final long serialVersionUID = -8498457904032259345L; - public static Builder builder() { - return new Builder(); - } + public static Builder builder() { + return new Builder(); + } - public FGCPDEProviderMetadata() { - super(builder()); - } + public FGCPDEProviderMetadata() { + super(builder()); + } - public FGCPDEProviderMetadata(Builder builder) { - super(builder); - } + public FGCPDEProviderMetadata(Builder builder) { + super(builder); + } - @Override - public Builder toBuilder() { - return builder().fromProviderMetadata(this); - } + @Override + public Builder toBuilder() { + return builder().fromProviderMetadata(this); + } - public static class Builder extends BaseProviderMetadata.Builder { + public static class Builder extends BaseProviderMetadata.Builder { - protected Builder() { - id("fgcp-de") - .name("Fujitsu Global Cloud Platform (FGCP) - DE") - .apiMetadata(new FGCPApiMetadata()) - .homepage( - URI.create("http://www.fujitsu.com/global/solutions/cloud/solutions/global-cloud-platform/index.html")) - .console(URI.create("http://globalcloud.de.fujitsu.com")) - .defaultProperties(FGCPApiMetadata.defaultProperties()) - .iso3166Codes("DE-BY") - .endpoint( - "https://api.globalcloud.de.fujitsu.com/ovissapi/endpoint") - .defaultProperties(FGCPProviderMetadata.defaultProperties()); - } + protected Builder() { + id("fgcp-de") + .name("Fujitsu Global Cloud Platform (FGCP) - DE") + .apiMetadata(new FGCPApiMetadata()) + .homepage( + URI.create("http://www.fujitsu.com/global/solutions/cloud/solutions/global-cloud-platform/index.html")) + .console(URI.create("http://globalcloud.de.fujitsu.com")) + .defaultProperties(FGCPApiMetadata.defaultProperties()) + .iso3166Codes("DE-BY") + .endpoint( + "https://api.globalcloud.de.fujitsu.com/ovissapi/endpoint") + .defaultProperties(FGCPProviderMetadata.defaultProperties()); + } - @Override - public FGCPDEProviderMetadata build() { - return new FGCPDEProviderMetadata(this); - } + @Override + public FGCPDEProviderMetadata build() { + return new FGCPDEProviderMetadata(this); + } - @Override - public Builder fromProviderMetadata(ProviderMetadata in) { - super.fromProviderMetadata(in); - return this; - } - } + @Override + public Builder fromProviderMetadata(ProviderMetadata in) { + super.fromProviderMetadata(in); + return this; + } + } } \ No newline at end of file diff --git a/labs/fgcp-de/src/test/java/org/jclouds/fujitsu/fgcp/FGCPDEProviderTest.java b/labs/fgcp-de/src/test/java/org/jclouds/fujitsu/fgcp/FGCPDEProviderTest.java index 99b37d255b..175cb3d2a4 100644 --- a/labs/fgcp-de/src/test/java/org/jclouds/fujitsu/fgcp/FGCPDEProviderTest.java +++ b/labs/fgcp-de/src/test/java/org/jclouds/fujitsu/fgcp/FGCPDEProviderTest.java @@ -28,7 +28,7 @@ import org.testng.annotations.Test; public class FGCPDEProviderTest extends BaseProviderMetadataTest { public FGCPDEProviderTest() { - super(new FGCPDEProviderMetadata(), new FGCPApiMetadata()); + super(new FGCPDEProviderMetadata(), new FGCPApiMetadata()); } } diff --git a/labs/fgcp-de/src/test/java/org/jclouds/fujitsu/fgcp/compute/FGCPDETemplateBuilderLiveTest.java b/labs/fgcp-de/src/test/java/org/jclouds/fujitsu/fgcp/compute/FGCPDETemplateBuilderLiveTest.java index 0894978822..eaf6aeaf14 100644 --- a/labs/fgcp-de/src/test/java/org/jclouds/fujitsu/fgcp/compute/FGCPDETemplateBuilderLiveTest.java +++ b/labs/fgcp-de/src/test/java/org/jclouds/fujitsu/fgcp/compute/FGCPDETemplateBuilderLiveTest.java @@ -30,14 +30,14 @@ import com.google.common.collect.ImmutableSet; */ @Test(groups = "live", enabled = true, singleThreaded = true, testName = "FGCPDETemplateBuilderLiveTest") public class FGCPDETemplateBuilderLiveTest extends - FGCPBaseTemplateBuilderLiveTest { + FGCPBaseTemplateBuilderLiveTest { - public FGCPDETemplateBuilderLiveTest() { - provider = "fgcp-de"; - } + public FGCPDETemplateBuilderLiveTest() { + provider = "fgcp-de"; + } - @Override - protected Set getIso3166Codes() { - return ImmutableSet. of("DE-BY"); - } + @Override + protected Set getIso3166Codes() { + return ImmutableSet. of("DE-BY"); + } } diff --git a/labs/fgcp-de/src/test/java/org/jclouds/fujitsu/fgcp/compute/config/FGCPDEComputeServiceLiveTest.java b/labs/fgcp-de/src/test/java/org/jclouds/fujitsu/fgcp/compute/config/FGCPDEComputeServiceLiveTest.java index f0de55992f..23f1cd72c7 100644 --- a/labs/fgcp-de/src/test/java/org/jclouds/fujitsu/fgcp/compute/config/FGCPDEComputeServiceLiveTest.java +++ b/labs/fgcp-de/src/test/java/org/jclouds/fujitsu/fgcp/compute/config/FGCPDEComputeServiceLiveTest.java @@ -29,9 +29,9 @@ import org.testng.annotations.Test; @Test(groups = "live", enabled = true, singleThreaded = true, testName = "FGCPDEComputeServiceLiveTest") public class FGCPDEComputeServiceLiveTest extends FGCPBaseComputeServiceLiveTest { - @Override - public void setServiceDefaults() { - provider = "fgcp-de"; - } + @Override + public void setServiceDefaults() { + provider = "fgcp-de"; + } } diff --git a/labs/fgcp/pom.xml b/labs/fgcp/pom.xml index cc1e81fe45..ac4c92c5cc 100644 --- a/labs/fgcp/pom.xml +++ b/labs/fgcp/pom.xml @@ -25,7 +25,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.labs diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/FGCPApi.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/FGCPApi.java index 54561af058..c2175f9fef 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/FGCPApi.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/FGCPApi.java @@ -40,30 +40,30 @@ import org.jclouds.rest.annotations.Delegate; @Timeout(duration = 180, timeUnit = TimeUnit.SECONDS) public interface FGCPApi { - @Delegate - VirtualDCApi getVirtualDCApi(); + @Delegate + VirtualDCApi getVirtualDCApi(); - @Delegate - VirtualSystemApi getVirtualSystemApi(); + @Delegate + VirtualSystemApi getVirtualSystemApi(); - @Delegate - VirtualServerApi getVirtualServerApi(); + @Delegate + VirtualServerApi getVirtualServerApi(); - @Delegate - AdditionalDiskApi getAdditionalDiskApi(); + @Delegate + AdditionalDiskApi getAdditionalDiskApi(); - @Delegate - SystemTemplateApi getSystemTemplateApi(); + @Delegate + SystemTemplateApi getSystemTemplateApi(); - @Delegate - DiskImageApi getDiskImageApi(); + @Delegate + DiskImageApi getDiskImageApi(); - @Delegate - FirewallApi getFirewallApi(); + @Delegate + FirewallApi getFirewallApi(); - @Delegate - LoadBalancerApi getLoadBalancerApi(); + @Delegate + LoadBalancerApi getLoadBalancerApi(); - @Delegate - PublicIPAddressApi getPublicIPAddressApi(); + @Delegate + PublicIPAddressApi getPublicIPAddressApi(); } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/FGCPApiMetadata.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/FGCPApiMetadata.java index 0f5e9fdb44..c187b7edee 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/FGCPApiMetadata.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/FGCPApiMetadata.java @@ -40,60 +40,63 @@ import com.google.inject.Module; */ public class FGCPApiMetadata extends BaseRestApiMetadata { - @Override - public Builder toBuilder() { - return new Builder().fromApiMetadata(this); - } + /** The serialVersionUID */ + private static final long serialVersionUID = -8430912756058292588L; - public FGCPApiMetadata() { - this(new Builder()); - } + @Override + public Builder toBuilder() { + return new Builder().fromApiMetadata(this); + } - protected FGCPApiMetadata(Builder builder) { - super(builder); - } + public FGCPApiMetadata() { + this(new Builder()); + } - public static Properties defaultProperties() { - Properties properties = BaseRestApiMetadata.defaultProperties(); - // enables peer verification using the CAs bundled with the JRE (or - // value of javax.net.ssl.trustStore if set) - properties.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, "false"); - // properties.setProperty("jclouds.ssh.max-retries", "5"); - // properties.setProperty("jclouds.ssh.retry-auth", "true"); - return properties; - } + protected FGCPApiMetadata(Builder builder) { + super(builder); + } - public static class Builder extends BaseRestApiMetadata.Builder { + public static Properties defaultProperties() { + Properties properties = BaseRestApiMetadata.defaultProperties(); + // enables peer verification using the CAs bundled with the JRE (or + // value of javax.net.ssl.trustStore if set) + properties.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, "false"); + // properties.setProperty("jclouds.ssh.max-retries", "5"); + // properties.setProperty("jclouds.ssh.retry-auth", "true"); + return properties; + } - protected Builder() { - super(FGCPApi.class, FGCPAsyncApi.class); - id("fgcp") - .name("Fujitsu Global Cloud Platform (FGCP)") - .identityName("User certificate (PEM file)") - .credentialName("User certificate password") - .documentation( - URI.create("https://globalcloud.fujitsu.com.au/portala/ctrl/aboutSopManual")) - .version(FGCPAsyncApi.VERSION) - .defaultEndpoint( - "https://api.globalcloud.fujitsu.com.au/ovissapi/endpoint") - .defaultProperties(FGCPApiMetadata.defaultProperties()) - .view(TypeToken.of(ComputeServiceContext.class)) - .defaultModules( - ImmutableSet.> of( - FGCPComputeServiceContextModule.class, - FGCPRestClientModule.class)); - } + public static class Builder extends BaseRestApiMetadata.Builder { - @Override - public FGCPApiMetadata build() { - return new FGCPApiMetadata(this); - } + protected Builder() { + super(FGCPApi.class, FGCPAsyncApi.class); + id("fgcp") + .name("Fujitsu Global Cloud Platform (FGCP)") + .identityName("User certificate (PEM file)") + .credentialName("User certificate password") + .documentation( + URI.create("https://globalcloud.fujitsu.com.au/portala/ctrl/aboutSopManual")) + .version(FGCPAsyncApi.VERSION) + .defaultEndpoint( + "https://api.globalcloud.fujitsu.com.au/ovissapi/endpoint") + .defaultProperties(FGCPApiMetadata.defaultProperties()) + .view(TypeToken.of(ComputeServiceContext.class)) + .defaultModules( + ImmutableSet.> of( + FGCPComputeServiceContextModule.class, + FGCPRestClientModule.class)); + } - @Override - public Builder fromApiMetadata(ApiMetadata in) { - super.fromApiMetadata(in); - return this; - } + @Override + public FGCPApiMetadata build() { + return new FGCPApiMetadata(this); + } - } + @Override + public Builder fromApiMetadata(ApiMetadata in) { + super.fromApiMetadata(in); + return this; + } + + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/FGCPAsyncApi.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/FGCPAsyncApi.java index 9eda1dde95..5a3d5e4ac5 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/FGCPAsyncApi.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/FGCPAsyncApi.java @@ -35,32 +35,32 @@ import org.jclouds.rest.annotations.Delegate; * @author Dies Koper */ public interface FGCPAsyncApi { - public final static String VERSION = "2012-02-18"; + public final static String VERSION = "2012-02-18"; - @Delegate - VirtualDCAsyncApi getVirtualDCApi(); + @Delegate + VirtualDCAsyncApi getVirtualDCApi(); - @Delegate - VirtualSystemAsyncApi getVirtualSystemApi(); + @Delegate + VirtualSystemAsyncApi getVirtualSystemApi(); - @Delegate - VirtualServerAsyncApi getVirtualServerApi(); + @Delegate + VirtualServerAsyncApi getVirtualServerApi(); - @Delegate - AdditionalDiskAsyncApi getAdditionalDiskApi(); + @Delegate + AdditionalDiskAsyncApi getAdditionalDiskApi(); - @Delegate - SystemTemplateAsyncApi getSystemTemplateApi(); + @Delegate + SystemTemplateAsyncApi getSystemTemplateApi(); - @Delegate - DiskImageAsyncApi getDiskImageApi(); + @Delegate + DiskImageAsyncApi getDiskImageApi(); - @Delegate - FirewallAsyncApi getFirewallApi(); + @Delegate + FirewallAsyncApi getFirewallApi(); - @Delegate - LoadBalancerAsyncApi getLoadBalancerApi(); + @Delegate + LoadBalancerAsyncApi getLoadBalancerApi(); - @Delegate - PublicIPAddressAsyncApi getPublicIPAddressApi(); + @Delegate + PublicIPAddressAsyncApi getPublicIPAddressApi(); } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/FGCPProviderMetadata.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/FGCPProviderMetadata.java index a7718d4c2e..7989cda470 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/FGCPProviderMetadata.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/FGCPProviderMetadata.java @@ -32,26 +32,26 @@ import org.jclouds.providers.internal.BaseProviderMetadata; */ public class FGCPProviderMetadata extends BaseProviderMetadata { - private static final long serialVersionUID = 7527265705102650456L; + private static final long serialVersionUID = 7527265705102650456L; - public static Builder builder() { - return new Builder(); - } + public static Builder builder() { + return new Builder(); + } - public FGCPProviderMetadata() { - super(builder()); - } + public FGCPProviderMetadata() { + super(builder()); + } - public FGCPProviderMetadata(Builder builder) { - super(builder); - } + public FGCPProviderMetadata(Builder builder) { + super(builder); + } - public static Properties defaultProperties() { - Properties properties = new Properties(); + public static Properties defaultProperties() { + Properties properties = new Properties(); - properties.setProperty(TEMPLATE, - "osFamily=CENTOS,osVersionMatches=6.2,os64Bit=true"); + properties.setProperty(TEMPLATE, + "osFamily=CENTOS,osVersionMatches=6.2,os64Bit=true"); - return properties; - } + return properties; + } } \ No newline at end of file diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/binders/BindAlsoToSystemId.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/binders/BindAlsoToSystemId.java index 0986997dbf..887d52b4f4 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/binders/BindAlsoToSystemId.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/binders/BindAlsoToSystemId.java @@ -38,33 +38,33 @@ import org.jclouds.rest.Binder; @Singleton public class BindAlsoToSystemId implements Binder { - /** - * - * @param request - * request where the query params will be set - * @param input - * array of String params - */ - @SuppressWarnings("unchecked") - @Override - public R bindToRequest(R request, Object input) { + /** + * + * @param request + * request where the query params will be set + * @param input + * array of String params + */ + @SuppressWarnings("unchecked") + @Override + public R bindToRequest(R request, Object input) { - checkNotNull(input); - checkArgument( - input instanceof String, - "this binder only applies to String arguments: " - + input.getClass()); + checkNotNull(input); + checkArgument( + input instanceof String, + "this binder only applies to String arguments: " + + input.getClass()); - Pattern pattern = Pattern.compile("^(\\w+-\\w+)\\b.*"); - Matcher matcher = pattern.matcher((String) input); + Pattern pattern = Pattern.compile("^(\\w+-\\w+)\\b.*"); + Matcher matcher = pattern.matcher((String) input); - checkArgument(matcher.find(), - "no valid resource id found to construct vsys id from: " - + input.toString()); + checkArgument(matcher.find(), + "no valid resource id found to construct vsys id from: " + + input.toString()); - Builder builder = request.toBuilder(); - builder.replaceQueryParam("vsysId", matcher.group(1)); + Builder builder = request.toBuilder(); + builder.replaceQueryParam("vsysId", matcher.group(1)); - return (R) builder.build(); - } + return (R) builder.build(); + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/FGCPRestClientModule.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/FGCPRestClientModule.java index c86abea2ea..1d5e4a3b5d 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/FGCPRestClientModule.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/FGCPRestClientModule.java @@ -79,6 +79,7 @@ import org.jclouds.rest.annotations.Identity; import org.jclouds.rest.config.RestClientModule; import org.jclouds.xml.XMLParser; +import com.google.common.base.Charsets; import com.google.common.base.Supplier; import com.google.common.collect.ImmutableMap; import com.google.inject.Provides; @@ -92,284 +93,284 @@ import com.google.inject.TypeLiteral; */ @ConfiguresRestClient public class FGCPRestClientModule extends - RestClientModule { + RestClientModule { - @Resource - Logger logger = Logger.NULL; + @Resource + Logger logger = Logger.NULL; - public static final Map, Class> DELEGATE_MAP = ImmutableMap - ., Class> builder() - // - .put(VirtualDCApi.class, VirtualDCAsyncApi.class) - .put(VirtualSystemApi.class, VirtualSystemAsyncApi.class) - .put(VirtualServerApi.class, VirtualServerAsyncApi.class) - .put(AdditionalDiskApi.class, AdditionalDiskAsyncApi.class) - .put(SystemTemplateApi.class, SystemTemplateAsyncApi.class) - .put(DiskImageApi.class, DiskImageAsyncApi.class) - .put(BuiltinServerApi.class, BuiltinServerAsyncApi.class) - .put(FirewallApi.class, FirewallAsyncApi.class) - .put(LoadBalancerApi.class, LoadBalancerAsyncApi.class) - .put(PublicIPAddressApi.class, PublicIPAddressAsyncApi.class) - .build(); + public static final Map, Class> DELEGATE_MAP = ImmutableMap + ., Class> builder() + // + .put(VirtualDCApi.class, VirtualDCAsyncApi.class) + .put(VirtualSystemApi.class, VirtualSystemAsyncApi.class) + .put(VirtualServerApi.class, VirtualServerAsyncApi.class) + .put(AdditionalDiskApi.class, AdditionalDiskAsyncApi.class) + .put(SystemTemplateApi.class, SystemTemplateAsyncApi.class) + .put(DiskImageApi.class, DiskImageAsyncApi.class) + .put(BuiltinServerApi.class, BuiltinServerAsyncApi.class) + .put(FirewallApi.class, FirewallAsyncApi.class) + .put(LoadBalancerApi.class, LoadBalancerAsyncApi.class) + .put(PublicIPAddressApi.class, PublicIPAddressAsyncApi.class) + .build(); - public FGCPRestClientModule() { - super(DELEGATE_MAP); - } + public FGCPRestClientModule() { + super(DELEGATE_MAP); + } - @Override - protected void bindErrorHandlers() { - // bind(HttpErrorHandler.class).annotatedWith(Redirection.class).to(ParseAWSErrorFromXmlContent.class); - // bind(HttpErrorHandler.class).annotatedWith(ClientError.class).to(ParseAWSErrorFromXmlContent.class); - // bind(HttpErrorHandler.class).annotatedWith(ServerError.class).to(ParseAWSErrorFromXmlContent.class); - } + @Override + protected void bindErrorHandlers() { + // bind(HttpErrorHandler.class).annotatedWith(Redirection.class).to(ParseAWSErrorFromXmlContent.class); + // bind(HttpErrorHandler.class).annotatedWith(ClientError.class).to(ParseAWSErrorFromXmlContent.class); + // bind(HttpErrorHandler.class).annotatedWith(ServerError.class).to(ParseAWSErrorFromXmlContent.class); + } - @Override - protected void installLocations() { - super.installLocations(); - bind(ImplicitLocationSupplier.class).to(FirstNetwork.class).in( - Scopes.SINGLETON); - bind(LocationsSupplier.class).to( - SystemAndNetworkSegmentToLocationSupplier.class).in( - Scopes.SINGLETON); - } + @Override + protected void installLocations() { + super.installLocations(); + bind(ImplicitLocationSupplier.class).to(FirstNetwork.class).in( + Scopes.SINGLETON); + bind(LocationsSupplier.class).to( + SystemAndNetworkSegmentToLocationSupplier.class).in( + Scopes.SINGLETON); + } - @Override - protected void bindRetryHandlers() { - bind(HttpRetryHandler.class).annotatedWith(ClientError.class).to( - FGCPRetryIfNotProxyAuthenticationFailureHandler.class); - } + @Override + protected void bindRetryHandlers() { + bind(HttpRetryHandler.class).annotatedWith(ClientError.class).to( + FGCPRetryIfNotProxyAuthenticationFailureHandler.class); + } - @Override - protected void configure() { - super.configure(); - bind(XMLParser.class).to(FGCPJAXBParser.class); - bind(new TypeLiteral>() { - }).to(new TypeLiteral() { - }); - } + @Override + protected void configure() { + super.configure(); + bind(XMLParser.class).to(FGCPJAXBParser.class); + bind(new TypeLiteral>() { + }).to(new TypeLiteral() { + }); + } - @Provides - @TimeStamp - protected Calendar provideCalendar() { - return Calendar.getInstance(); - } + @Provides + @TimeStamp + protected Calendar provideCalendar() { + return Calendar.getInstance(); + } - /* - * - * @Provides - * - * @Singleton protected KeyStore - * provideKeyStore(@Named(Constants.PROPERTY_IDENTITY) String - * keyStoreFilename, @Named(Constants.PROPERTY_CREDENTIAL) String - * keyStorePassword) throws KeyStoreException { KeyStore keyStore = - * KeyStore.getInstance("pkcs12"); - * - * try { FileInputStream is = new - * FileInputStream(checkNotNull(keyStoreFilename, - * Constants.PROPERTY_IDENTITY)); keyStore.load(is, - * checkNotNull(keyStorePassword, - * Constants.PROPERTY_CREDENTIAL).toCharArray()); } catch (Exception e) { // - * expecting IOException, NoSuchAlgorithmException, CertificateException - * logger.error(e, "Keystore could not be opened: %s", keyStoreFilename); } - * return keyStore; } - * - * @Provides - * - * @Singleton protected PrivateKey provideKey(Provider - * keyStoreProvider, @Named(Constants.PROPERTY_CREDENTIAL) String - * keyPassword) throws KeyStoreException, NoSuchAlgorithmException, - * UnrecoverableKeyException { KeyStore keyStore = keyStoreProvider.get(); - * if (keyStore == null) return null; - * - * // retrieving 1st alias in keystore as expecting only one String alias = - * checkNotNull(keyStore.aliases().nextElement(), - * "first alias in keystore"); return (PrivateKey) keyStore.getKey(alias, - * checkNotNull(keyPassword, Constants.PROPERTY_CREDENTIAL).toCharArray()); - * } - */ - /* - * maybe we can provide two authentication methods: - * - * 1. same as DeltaCloud: User passes a folder name as identity and cert - * password as credential Note: pass relative path (e.g. cert's path: - * c:\jclouds\certs\dkoper\UserCert.p12: user passes 'dkoper': provider - * impl. finds it under e.g. $USER_DIR or $CURRENT_DIR or pass absolute path - * 2. no file access for GAE: User passes cert in PEM format (converted from - * UserCert.p12 using openssl?) as identity and cert password as credential - */ - @Provides - @Singleton - protected KeyStore provideKeyStore(Crypto crypto, @Identity String cert, - @Credential String keyStorePassword) { - KeyStore keyStore = null; - try { - keyStore = KeyStore.getInstance("PKCS12"); + /* + * + * @Provides + * + * @Singleton protected KeyStore + * provideKeyStore(@Named(Constants.PROPERTY_IDENTITY) String + * keyStoreFilename, @Named(Constants.PROPERTY_CREDENTIAL) String + * keyStorePassword) throws KeyStoreException { KeyStore keyStore = + * KeyStore.getInstance("pkcs12"); + * + * try { FileInputStream is = new + * FileInputStream(checkNotNull(keyStoreFilename, + * Constants.PROPERTY_IDENTITY)); keyStore.load(is, + * checkNotNull(keyStorePassword, + * Constants.PROPERTY_CREDENTIAL).toCharArray()); } catch (Exception e) { // + * expecting IOException, NoSuchAlgorithmException, CertificateException + * logger.error(e, "Keystore could not be opened: %s", keyStoreFilename); } + * return keyStore; } + * + * @Provides + * + * @Singleton protected PrivateKey provideKey(Provider + * keyStoreProvider, @Named(Constants.PROPERTY_CREDENTIAL) String + * keyPassword) throws KeyStoreException, NoSuchAlgorithmException, + * UnrecoverableKeyException { KeyStore keyStore = keyStoreProvider.get(); + * if (keyStore == null) return null; + * + * // retrieving 1st alias in keystore as expecting only one String alias = + * checkNotNull(keyStore.aliases().nextElement(), + * "first alias in keystore"); return (PrivateKey) keyStore.getKey(alias, + * checkNotNull(keyPassword, Constants.PROPERTY_CREDENTIAL).toCharArray()); + * } + */ + /* + * maybe we can provide two authentication methods: + * + * 1. same as DeltaCloud: User passes a folder name as identity and cert + * password as credential Note: pass relative path (e.g. cert's path: + * c:\jclouds\certs\dkoper\UserCert.p12: user passes 'dkoper': provider + * impl. finds it under e.g. $USER_DIR or $CURRENT_DIR or pass absolute path + * 2. no file access for GAE: User passes cert in PEM format (converted from + * UserCert.p12 using openssl?) as identity and cert password as credential + */ + @Provides + @Singleton + protected KeyStore provideKeyStore(Crypto crypto, @Identity String cert, + @Credential String keyStorePassword) { + KeyStore keyStore = null; + try { + keyStore = KeyStore.getInstance("PKCS12"); - // System.out.println("cert: " + cert); - // System.out.println("pwd : " + keyStorePassword); - File certFile = new File(checkNotNull(cert)); - if (certFile.isFile()) { // cert is path to pkcs12 file + // System.out.println("cert: " + cert); + // System.out.println("pwd : " + keyStorePassword); + File certFile = new File(checkNotNull(cert)); + if (certFile.isFile()) { // cert is path to pkcs12 file - keyStore.load(new FileInputStream(certFile), - keyStorePassword.toCharArray()); - } else { // cert is PEM encoded, containing private key and certs + keyStore.load(new FileInputStream(certFile), + keyStorePassword.toCharArray()); + } else { // cert is PEM encoded, containing private key and certs - // System.out.println("cert:\n" + cert); - // split in private key and certs - int privateKeyBeginIdx = cert.indexOf("-----BEGIN PRIVATE KEY"); - int privateKeyEndIdx = cert.indexOf("-----END PRIVATE KEY"); - String pemPrivateKey = cert.substring(privateKeyBeginIdx, - privateKeyEndIdx + 26); - // System.out.println("***************"); - // System.out.println("pemPrivateKey:\n" + pemPrivateKey); - // System.out.println("***************"); + // System.out.println("cert:\n" + cert); + // split in private key and certs + int privateKeyBeginIdx = cert.indexOf("-----BEGIN PRIVATE KEY"); + int privateKeyEndIdx = cert.indexOf("-----END PRIVATE KEY"); + String pemPrivateKey = cert.substring(privateKeyBeginIdx, + privateKeyEndIdx + 26); + // System.out.println("***************"); + // System.out.println("pemPrivateKey:\n" + pemPrivateKey); + // System.out.println("***************"); - String pemCerts = ""; - int certsBeginIdx = 0; + String pemCerts = ""; + int certsBeginIdx = 0; - do { - certsBeginIdx = cert.indexOf("-----BEGIN CERTIFICATE", - certsBeginIdx); - // System.out.println("begin:" + certsBeginIdx); + do { + certsBeginIdx = cert.indexOf("-----BEGIN CERTIFICATE", + certsBeginIdx); + // System.out.println("begin:" + certsBeginIdx); - if (certsBeginIdx >= 0) { - int certsEndIdx = cert.indexOf("-----END CERTIFICATE", - certsBeginIdx) + 26; - // System.out.println("end :" + certsEndIdx); - pemCerts += cert.substring(certsBeginIdx, certsEndIdx); - certsBeginIdx = certsEndIdx; - } - } while (certsBeginIdx != -1); - // System.out.println("***************"); - // System.out.println("pemCerts:\n" + pemCerts); - // System.out.println("***************"); + if (certsBeginIdx >= 0) { + int certsEndIdx = cert.indexOf("-----END CERTIFICATE", + certsBeginIdx) + 26; + // System.out.println("end :" + certsEndIdx); + pemCerts += cert.substring(certsBeginIdx, certsEndIdx); + certsBeginIdx = certsEndIdx; + } + } while (certsBeginIdx != -1); + // System.out.println("***************"); + // System.out.println("pemCerts:\n" + pemCerts); + // System.out.println("***************"); - /* - * String pemCerts = "-----BEGIN "; Splitter pemSplitter = - * Splitter.on("-----BEGIN "); - * - * for (String part : pemSplitter.split(cert)) { - * System.out.println("***************"); - * System.out.println("Part:\n" + part); - * System.out.println("***************"); - * - * if (part.startsWith("PRIVATE KEY") - */ - /* || part.startsWith("RSA PRIVATE KEY)" *//* - * ) { - * - * int certEndIdx = - * part.lastIndexOf - * ("-----END"); - * pemPrivateKey += - * part.substring(0, - * certEndIdx + 26); - * // take up to next - * "-----" (i.e. - * "-----END") // - * Splitter - * keySplitter = - * Splitter - * .on("-----"). - * omitEmptyStrings - * ().trimResults(); - * // - * Iterator - * iter = - * keySplitter. - * split(part - * ).iterator(); // - * String keyName = - * iter.next() + - * "-----\n"; // - * pemPrivateKey += - * keyName; //// - * System.out - * .println - * ("Skipping: '" + - * iter.next() + - * "'"); // - * pemPrivateKey += - * iter.next(); // - * pemPrivateKey += - * "\n-----END " + - * keyName; - * System.out.println - * ( - * "/////////////////" - * ); - * System.out.println - * ( - * "pemPrivateKey:\n" - * + pemPrivateKey); - * System - * .out.println( - * "/////////////////" - * ); } else if - * (part.startsWith - * ("CERTIFICATE")) { - * - * // take up to next - * "-----" (i.e. - * "-----END") // or - * take up to last - * END CERTIFICATE? - * int certEndIdx = - * part.lastIndexOf ( - * "----- END CERTIFICATE" - * ); // pemCerts += - * part. // Splitter - * keySplitter = - * Splitter - * .on("-----"). - * omitEmptyStrings - * (); // pemCerts += - * keySplitter - * .split(part) - * .iterator - * ().next(); // - * pemCerts += - * "-----BEGIN "; } - * else { // ignore - * the fluff in - * between (Bag - * Attributes, etc.) - * } } - */ - - // parse private key - KeySpec keySpec = Pems.privateKeySpec(InputSuppliers - .of(pemPrivateKey)); - PrivateKey privateKey = crypto.rsaKeyFactory().generatePrivate( - keySpec); - - // populate keystore with private key and certs - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - @SuppressWarnings("unchecked") - Collection certs = (Collection) cf - .generateCertificates(new ByteArrayInputStream(pemCerts - .getBytes("UTF-8"))); - keyStore.load(null); - keyStore.setKeyEntry("dummy", privateKey, - keyStorePassword.toCharArray(), - certs.toArray(new java.security.cert.Certificate[0])); - - // System.out.println("private key: " + privateKey.getFormat() + - // "; " - // + privateKey.getAlgorithm() + "; class: " + - // privateKey.getClass().getName());// + "; " + new - // String(privateKey.getEncoded())); - - } - } catch (Exception e) { /* - * KeyStoreException, IOException, NoSuchAlgorithmException, - * CertificateException, InvalidKeySpecException + * String pemCerts = "-----BEGIN "; Splitter pemSplitter = + * Splitter.on("-----BEGIN "); + * + * for (String part : pemSplitter.split(cert)) { + * System.out.println("***************"); + * System.out.println("Part:\n" + part); + * System.out.println("***************"); + * + * if (part.startsWith("PRIVATE KEY") */ - throw new AuthorizationException("Error loading certificate", e); - } + /* || part.startsWith("RSA PRIVATE KEY)" *//* + * ) { + * + * int certEndIdx = + * part.lastIndexOf + * ("-----END"); + * pemPrivateKey += + * part.substring(0, + * certEndIdx + 26); + * // take up to next + * "-----" (i.e. + * "-----END") // + * Splitter + * keySplitter = + * Splitter + * .on("-----"). + * omitEmptyStrings + * ().trimResults(); + * // + * Iterator + * iter = + * keySplitter. + * split(part + * ).iterator(); // + * String keyName = + * iter.next() + + * "-----\n"; // + * pemPrivateKey += + * keyName; //// + * System.out + * .println + * ("Skipping: '" + + * iter.next() + + * "'"); // + * pemPrivateKey += + * iter.next(); // + * pemPrivateKey += + * "\n-----END " + + * keyName; + * System.out.println + * ( + * "/////////////////" + * ); + * System.out.println + * ( + * "pemPrivateKey:\n" + * + pemPrivateKey); + * System + * .out.println( + * "/////////////////" + * ); } else if + * (part.startsWith + * ("CERTIFICATE")) { + * + * // take up to next + * "-----" (i.e. + * "-----END") // or + * take up to last + * END CERTIFICATE? + * int certEndIdx = + * part.lastIndexOf ( + * "----- END CERTIFICATE" + * ); // pemCerts += + * part. // Splitter + * keySplitter = + * Splitter + * .on("-----"). + * omitEmptyStrings + * (); // pemCerts += + * keySplitter + * .split(part) + * .iterator + * ().next(); // + * pemCerts += + * "-----BEGIN "; } + * else { // ignore + * the fluff in + * between (Bag + * Attributes, etc.) + * } } + */ - return keyStore; - } + // parse private key + KeySpec keySpec = Pems.privateKeySpec(InputSuppliers + .of(pemPrivateKey)); + PrivateKey privateKey = crypto.rsaKeyFactory().generatePrivate( + keySpec); + + // populate keystore with private key and certs + CertificateFactory cf = CertificateFactory.getInstance("X.509"); + @SuppressWarnings("unchecked") + Collection certs = (Collection) cf + .generateCertificates(new ByteArrayInputStream(pemCerts + .getBytes(Charsets.UTF_8))); + keyStore.load(null); + keyStore.setKeyEntry("dummy", privateKey, + keyStorePassword.toCharArray(), + certs.toArray(new java.security.cert.Certificate[0])); + + // System.out.println("private key: " + privateKey.getFormat() + + // "; " + // + privateKey.getAlgorithm() + "; class: " + + // privateKey.getClass().getName());// + "; " + new + // String(privateKey.getEncoded())); + + } + } catch (Exception e) { + /* + * KeyStoreException, IOException, NoSuchAlgorithmException, + * CertificateException, InvalidKeySpecException + */ + throw new AuthorizationException("Error loading certificate", e); + } + + return keyStore; + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/config/FGCPComputeServiceContextModule.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/config/FGCPComputeServiceContextModule.java index 46f3646e6e..1c6d29f744 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/config/FGCPComputeServiceContextModule.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/config/FGCPComputeServiceContextModule.java @@ -53,88 +53,88 @@ import com.google.inject.TypeLiteral; * @author Dies Koper */ public class FGCPComputeServiceContextModule - extends - ComputeServiceAdapterContextModule { + extends + ComputeServiceAdapterContextModule { - @SuppressWarnings({ "unchecked", "rawtypes" }) - @Override - protected void configure() { - super.configure(); - // installDependencies(); + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Override + protected void configure() { + super.configure(); + // installDependencies(); - bind( - new TypeLiteral>() { - }).to(FGCPComputeServiceAdapter.class); + bind( + new TypeLiteral>() { + }).to(FGCPComputeServiceAdapter.class); - // the following bind functions that map FGCP domain specific resources - // to jclouds' - bind(new TypeLiteral>() { - }).to(VServerMetadataToNodeMetadata.class); - bind(new TypeLiteral>() { - }).to(DiskImageToImage.class); - bind(new TypeLiteral>() { - }).to(DiskImageToOperatingSystem.class); - bind(new TypeLiteral>() { - }).to(ServerTypeToHardware.class); - bind(new TypeLiteral>() { - }).to(DiskToVolume.class); - bind(new TypeLiteral>() { - }).to(CPUToProcessor.class); + // the following bind functions that map FGCP domain specific resources + // to jclouds' + bind(new TypeLiteral>() { + }).to(VServerMetadataToNodeMetadata.class); + bind(new TypeLiteral>() { + }).to(DiskImageToImage.class); + bind(new TypeLiteral>() { + }).to(DiskImageToOperatingSystem.class); + bind(new TypeLiteral>() { + }).to(ServerTypeToHardware.class); + bind(new TypeLiteral>() { + }).to(DiskToVolume.class); + bind(new TypeLiteral>() { + }).to(CPUToProcessor.class); - // we aren't converting hardware from a provider-specific type - bind(new TypeLiteral>() { - }).to((Class) IdentityFunction.class); - bind(new TypeLiteral>() { - }).to((Class) IdentityFunction.class); + // we aren't converting hardware from a provider-specific type + bind(new TypeLiteral>() { + }).to((Class) IdentityFunction.class); + bind(new TypeLiteral>() { + }).to((Class) IdentityFunction.class); - bind(TemplateOptions.class).to(FGCPTemplateOptions.class); + bind(TemplateOptions.class).to(FGCPTemplateOptions.class); - // bind(new TypeLiteral>() { - // }).to((Class) ServerStopped.class); + // bind(new TypeLiteral>() { + // }).to((Class) ServerStopped.class); - // need to look into the following later for to map (create) jclouds' - // location to FGCP. - // see LocationScope: - // PROVIDER: FGCP - // REGION: country?/country+state? - // ZONE: virtual DC: contractId - // NETWORK: VSYS? DMZ/SECURE1/SECURE2? - // RACK: N/A? - // HOST: N/A? - // there are no locations except the provider - // bind(new TypeLiteral>() { - // }).to(OnlyLocationOrFirstZone.class); + // need to look into the following later for to map (create) jclouds' + // location to FGCP. + // see LocationScope: + // PROVIDER: FGCP + // REGION: country?/country+state? + // ZONE: virtual DC: contractId + // NETWORK: VSYS? DMZ/SECURE1/SECURE2? + // RACK: N/A? + // HOST: N/A? + // there are no locations except the provider + // bind(new TypeLiteral>() { + // }).to(OnlyLocationOrFirstZone.class); - // install(new FGCPBindComputeStrategiesByClass()); - // install(new FGCPBindComputeSuppliersByClass()); - // bind(ReviseParsedImage.class).to(AWSEC2ReviseParsedImage.class); - // bind(CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class).to( - // CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions.class); - // bind(EC2HardwareSupplier.class).to(AWSEC2HardwareSupplier.class); - // bind(EC2TemplateBuilderImpl.class).to(AWSEC2TemplateBuilderImpl.class); - // bind(EC2GetNodeMetadataStrategy.class).to(AWSEC2GetNodeMetadataStrategy.class); - // bind(InstancePresent.class).to(AWSEC2InstancePresent.class); - // bind(EC2CreateNodesInGroupThenAddToSet.class).to(AWSEC2CreateNodesInGroupThenAddToSet.class); - // bind(RunningInstanceToNodeMetadata.class).to(AWSRunningInstanceToNodeMetadata.class); - } + // install(new FGCPBindComputeStrategiesByClass()); + // install(new FGCPBindComputeSuppliersByClass()); + // bind(ReviseParsedImage.class).to(AWSEC2ReviseParsedImage.class); + // bind(CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions.class).to( + // CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions.class); + // bind(EC2HardwareSupplier.class).to(AWSEC2HardwareSupplier.class); + // bind(EC2TemplateBuilderImpl.class).to(AWSEC2TemplateBuilderImpl.class); + // bind(EC2GetNodeMetadataStrategy.class).to(AWSEC2GetNodeMetadataStrategy.class); + // bind(InstancePresent.class).to(AWSEC2InstancePresent.class); + // bind(EC2CreateNodesInGroupThenAddToSet.class).to(AWSEC2CreateNodesInGroupThenAddToSet.class); + // bind(RunningInstanceToNodeMetadata.class).to(AWSRunningInstanceToNodeMetadata.class); + } - // @Provides - // @Singleton - // @Named("SECURITY") - // protected Predicate provideServerStopped(ServerStopped - // serverStopped, Timeouts timeouts) { - // return new RetryablePredicate(serverStopped, - // timeouts.nodeSuspended); - // } + // @Provides + // @Singleton + // @Named("SECURITY") + // protected Predicate provideServerStopped(ServerStopped + // serverStopped, Timeouts timeouts) { + // return new RetryablePredicate(serverStopped, + // timeouts.nodeSuspended); + // } - protected void installDependencies() { - // install(new FGCPComputeServiceDependenciesModule()); - } + protected void installDependencies() { + // install(new FGCPComputeServiceDependenciesModule()); + } - /* - * @Override protected TemplateBuilder provideTemplate(Injector injector, - * TemplateBuilder template) { return - * template.osFamily(CENTOS).os64Bit(true); } - */ + /* + * @Override protected TemplateBuilder provideTemplate(Injector injector, + * TemplateBuilder template) { return + * template.osFamily(CENTOS).os64Bit(true); } + */ } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/functions/CPUToProcessor.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/functions/CPUToProcessor.java index a26508e954..63079a76a0 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/functions/CPUToProcessor.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/functions/CPUToProcessor.java @@ -20,11 +20,12 @@ package org.jclouds.fujitsu.fgcp.compute.functions; import static com.google.common.base.Preconditions.checkNotNull; -import com.google.common.base.Function; +import javax.inject.Singleton; + import org.jclouds.compute.domain.Processor; import org.jclouds.fujitsu.fgcp.domain.CPU; -import javax.inject.Singleton; +import com.google.common.base.Function; /** * Created by IntelliJ IDEA. @@ -34,11 +35,11 @@ import javax.inject.Singleton; @Singleton public class CPUToProcessor implements Function { - @Override - public Processor apply(CPU cpu) { - checkNotNull(cpu, "cpu"); + @Override + public Processor apply(CPU cpu) { + checkNotNull(cpu, "cpu"); - return new Processor(Double.valueOf(cpu.getCores()), Double.valueOf(cpu - .getSpeedPerCore())); - } + return new Processor(Double.valueOf(cpu.getCores()), Double.valueOf(cpu + .getSpeedPerCore())); + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/functions/DiskImageToImage.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/functions/DiskImageToImage.java index e5200da051..8ea67fe8ba 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/functions/DiskImageToImage.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/functions/DiskImageToImage.java @@ -43,38 +43,38 @@ import com.google.common.collect.Iterables; @Singleton public class DiskImageToImage implements Function { - private final DiskImageToOperatingSystem diskImageToOperatingSystem; - private final RegionToProviderOrJustProvider regionSupplier; + private final DiskImageToOperatingSystem diskImageToOperatingSystem; + private final RegionToProviderOrJustProvider regionSupplier; - @Inject - public DiskImageToImage( - DiskImageToOperatingSystem diskImageToOperatingSystem, - RegionToProviderOrJustProvider locationSupplier) { - this.diskImageToOperatingSystem = checkNotNull( - diskImageToOperatingSystem, "diskImageToOperatingSystem"); - this.regionSupplier = checkNotNull(locationSupplier, "locationProvider"); - } + @Inject + public DiskImageToImage( + DiskImageToOperatingSystem diskImageToOperatingSystem, + RegionToProviderOrJustProvider locationSupplier) { + this.diskImageToOperatingSystem = checkNotNull( + diskImageToOperatingSystem, "diskImageToOperatingSystem"); + this.regionSupplier = checkNotNull(locationSupplier, "locationProvider"); + } - @Override - public Image apply(DiskImage from) { - checkNotNull(from, "disk image"); + @Override + public Image apply(DiskImage from) { + checkNotNull(from, "disk image"); - ImageBuilder builder = new ImageBuilder(); + ImageBuilder builder = new ImageBuilder(); - builder.ids(from.getId()); - builder.name(from.getName()); - builder.description(from.getDescription()); - builder.location(Iterables.getOnlyElement(regionSupplier.get())); - // in fgcp, if the image is listed it is available - builder.status(Status.AVAILABLE); + builder.ids(from.getId()); + builder.name(from.getName()); + builder.description(from.getDescription()); + builder.location(Iterables.getOnlyElement(regionSupplier.get())); + // in fgcp, if the image is listed it is available + builder.status(Status.AVAILABLE); - OperatingSystem os = diskImageToOperatingSystem.apply(from); - builder.operatingSystem(os); - String user = os.getFamily() == OsFamily.WINDOWS ? "Administrator" - : "root"; - builder.defaultCredentials(LoginCredentials.builder().identity(user) - .noPassword().build()); + OperatingSystem os = diskImageToOperatingSystem.apply(from); + builder.operatingSystem(os); + String user = os.getFamily() == OsFamily.WINDOWS ? "Administrator" + : "root"; + builder.defaultCredentials(LoginCredentials.builder().identity(user) + .noPassword().build()); - return builder.build(); - } + return builder.build(); + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/functions/DiskImageToOperatingSystem.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/functions/DiskImageToOperatingSystem.java index b1ce9a1aef..eeab199368 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/functions/DiskImageToOperatingSystem.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/functions/DiskImageToOperatingSystem.java @@ -38,36 +38,36 @@ import com.google.common.base.Function; */ @Singleton public class DiskImageToOperatingSystem implements - Function { + Function { - private static final Pattern OS_VERSION_PATTERN = Pattern - .compile("^.*?(\\d.*)\\s(32|64).*$"); + private static final Pattern OS_VERSION_PATTERN = Pattern + .compile("^.*?(\\d.*)\\s(32|64).*$"); - @Override - public OperatingSystem apply(DiskImage image) { - checkNotNull(image, "disk image"); + @Override + public OperatingSystem apply(DiskImage image) { + checkNotNull(image, "disk image"); - // convert to short name rhel to accommodate ComputeServiceUtils - // conventions - String shortOsName = image.getOsName().replace( - "Red Hat Enterprise Linux", "rhel"); - OsFamily osFamily = ComputeServiceUtils - .parseOsFamilyOrUnrecognized(shortOsName); - OperatingSystem.Builder builder = OperatingSystem.builder(); + // convert to short name rhel to accommodate ComputeServiceUtils + // conventions + String shortOsName = image.getOsName().replace( + "Red Hat Enterprise Linux", "rhel"); + OsFamily osFamily = ComputeServiceUtils + .parseOsFamilyOrUnrecognized(shortOsName); + OperatingSystem.Builder builder = OperatingSystem.builder(); - builder.name(image.getOsName()); - builder.family(osFamily); - builder.is64Bit(image.getOsName().contains("64bit") - || image.getOsName().contains("64 bit") - || image.getOsName().contains("x64")); - // OsType returns guest type (hvm, pv), which aws-ec2 is mapping to arch - builder.arch(image.getOsType()); - Matcher m = OS_VERSION_PATTERN.matcher(image.getOsName()); - if (m.matches()) { - builder.version(m.group(1)); - } - builder.description(image.getOsName()); + builder.name(image.getOsName()); + builder.family(osFamily); + builder.is64Bit(image.getOsName().contains("64bit") + || image.getOsName().contains("64 bit") + || image.getOsName().contains("x64")); + // OsType returns guest type (hvm, pv), which aws-ec2 is mapping to arch + builder.arch(image.getOsType()); + Matcher m = OS_VERSION_PATTERN.matcher(image.getOsName()); + if (m.matches()) { + builder.version(m.group(1)); + } + builder.description(image.getOsName()); - return builder.build(); - } + return builder.build(); + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/functions/DiskToVolume.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/functions/DiskToVolume.java index c9f4067632..e218cf0143 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/functions/DiskToVolume.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/functions/DiskToVolume.java @@ -20,12 +20,13 @@ package org.jclouds.fujitsu.fgcp.compute.functions; import static com.google.common.base.Preconditions.checkNotNull; -import com.google.common.base.Function; +import javax.inject.Singleton; + import org.jclouds.compute.domain.Volume; import org.jclouds.compute.domain.VolumeBuilder; import org.jclouds.fujitsu.fgcp.domain.Disk; -import javax.inject.Singleton; +import com.google.common.base.Function; /** * Created by IntelliJ IDEA. @@ -35,19 +36,19 @@ import javax.inject.Singleton; @Singleton public class DiskToVolume implements Function { - @Override - public Volume apply(Disk disk) { - checkNotNull(disk, "disk"); + @Override + public Volume apply(Disk disk) { + checkNotNull(disk, "disk"); - VolumeBuilder builder = new VolumeBuilder(); + VolumeBuilder builder = new VolumeBuilder(); - builder.size(1000f * Float.valueOf(disk.getSize())); - // "Disk"'s are additional disks; they can't be booted disk(?) - builder.bootDevice(false); - builder.durable(true); - builder.type(Volume.Type.SAN); - builder.id("type: " + disk.getType() + " usage: " + disk.getUsage()); + builder.size(1000f * Float.valueOf(disk.getSize())); + // "Disk"'s are additional disks; they can't be booted disk(?) + builder.bootDevice(false); + builder.durable(true); + builder.type(Volume.Type.SAN); + builder.id("type: " + disk.getType() + " usage: " + disk.getUsage()); - return builder.build(); - } + return builder.build(); + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/functions/ResourceIdToFirewallId.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/functions/ResourceIdToFirewallId.java index 2e91f2bb4a..82beebbef8 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/functions/ResourceIdToFirewallId.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/functions/ResourceIdToFirewallId.java @@ -34,18 +34,18 @@ import com.google.common.base.Function; @Singleton public class ResourceIdToFirewallId implements Function { - private ResourceIdToSystemId toSystemId; + private ResourceIdToSystemId toSystemId; - @Inject - private ResourceIdToFirewallId(ResourceIdToSystemId resourceIdToSystemId) { - this.toSystemId = checkNotNull(resourceIdToSystemId, - "resourceIdToSystemId"); - } + @Inject + private ResourceIdToFirewallId(ResourceIdToSystemId resourceIdToSystemId) { + this.toSystemId = checkNotNull(resourceIdToSystemId, + "resourceIdToSystemId"); + } - @Override - public String apply(String id) { - checkNotNull(id, "resource id"); + @Override + public String apply(String id) { + checkNotNull(id, "resource id"); - return toSystemId.apply(id) + "-S-0001"; - } + return toSystemId.apply(id) + "-S-0001"; + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/functions/ResourceIdToSystemId.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/functions/ResourceIdToSystemId.java index 01b1891cf7..229a236101 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/functions/ResourceIdToSystemId.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/functions/ResourceIdToSystemId.java @@ -37,16 +37,16 @@ import com.google.common.base.Function; @Singleton public class ResourceIdToSystemId implements Function { - @Override - public String apply(String id) { - checkNotNull(id, "resource id"); + @Override + public String apply(String id) { + checkNotNull(id, "resource id"); - Pattern pattern = Pattern.compile("^(\\w+-\\w+)\\b.*"); - Matcher matcher = pattern.matcher((String) id); + Pattern pattern = Pattern.compile("^(\\w+-\\w+)\\b.*"); + Matcher matcher = pattern.matcher((String) id); - checkArgument(matcher.find(), - "no valid resource id found: " + id.toString()); + checkArgument(matcher.find(), + "no valid resource id found: " + id.toString()); - return matcher.group(1); - } + return matcher.group(1); + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/functions/ServerTypeToHardware.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/functions/ServerTypeToHardware.java index ec99cf56f4..fc0ed61e2c 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/functions/ServerTypeToHardware.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/functions/ServerTypeToHardware.java @@ -39,30 +39,30 @@ import com.google.common.collect.Iterables; */ @Singleton public class ServerTypeToHardware implements Function { - private final CPUToProcessor cpuToProcessor; - private final DiskToVolume diskToVolume; + private final CPUToProcessor cpuToProcessor; + private final DiskToVolume diskToVolume; - @Inject - public ServerTypeToHardware(CPUToProcessor cpuToProcessor, - DiskToVolume diskToVolume) { - this.cpuToProcessor = checkNotNull(cpuToProcessor); - this.diskToVolume = checkNotNull(diskToVolume); - } + @Inject + public ServerTypeToHardware(CPUToProcessor cpuToProcessor, + DiskToVolume diskToVolume) { + this.cpuToProcessor = checkNotNull(cpuToProcessor); + this.diskToVolume = checkNotNull(diskToVolume); + } - @Override - public Hardware apply(ServerType from) { - checkNotNull(from, "ServerType"); - HardwareBuilder builder = new HardwareBuilder(); + @Override + public Hardware apply(ServerType from) { + checkNotNull(from, "ServerType"); + HardwareBuilder builder = new HardwareBuilder(); - builder.ids(from.getId()); - builder.name(from.getName()); - builder.ram((int) (1000d * Double.valueOf(from.getMemory().getSize()))); - builder.processor(cpuToProcessor.apply(from.getCpu())); - builder.supportsImage(Predicates. alwaysTrue()); - // all servers are 64bit. The OS however may be 32 bit. - builder.is64Bit(true); - builder.volumes(Iterables.transform(from.getDisks(), diskToVolume)); + builder.ids(from.getId()); + builder.name(from.getName()); + builder.ram((int) (1000d * Double.valueOf(from.getMemory().getSize()))); + builder.processor(cpuToProcessor.apply(from.getCpu())); + builder.supportsImage(Predicates. alwaysTrue()); + // all servers are 64bit. The OS however may be 32 bit. + builder.is64Bit(true); + builder.volumes(Iterables.transform(from.getDisks(), diskToVolume)); - return builder.build(); - } + return builder.build(); + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/functions/SingleElementResponseToElement.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/functions/SingleElementResponseToElement.java index b8677a4f96..3f672adcb8 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/functions/SingleElementResponseToElement.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/functions/SingleElementResponseToElement.java @@ -25,10 +25,10 @@ import org.jclouds.fujitsu.fgcp.xml.internal.SingleElementResponse; import com.google.common.base.Function; public class SingleElementResponseToElement implements - Function { + Function { - @Override - public Object apply(SingleElementResponse r) { - return checkNotNull(r, "response").getElement(); - } + @Override + public Object apply(SingleElementResponse r) { + return checkNotNull(r, "response").getElement(); + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/functions/VServerMetadataToNodeMetadata.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/functions/VServerMetadataToNodeMetadata.java index 66c390be0f..3da3d3e9dd 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/functions/VServerMetadataToNodeMetadata.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/functions/VServerMetadataToNodeMetadata.java @@ -59,187 +59,187 @@ import com.google.common.collect.Iterables; */ @Singleton public class VServerMetadataToNodeMetadata implements - Function { + Function { - public static final Map vServerToStatus = ImmutableMap - . builder() - .put(VServerStatus.DEPLOYING, Status.PENDING) - .put(VServerStatus.RUNNING, Status.RUNNING) - .put(VServerStatus.STOPPING, Status.PENDING) - .put(VServerStatus.STOPPED, Status.SUSPENDED) - .put(VServerStatus.STARTING, Status.PENDING) - .put(VServerStatus.FAILOVER, Status.RUNNING) - .put(VServerStatus.UNEXPECTED_STOP, Status.SUSPENDED) - .put(VServerStatus.RESTORING, Status.PENDING) - .put(VServerStatus.BACKUP_ING, Status.PENDING) - .put(VServerStatus.ERROR, Status.ERROR) - .put(VServerStatus.START_ERROR, Status.ERROR) - .put(VServerStatus.STOP_ERROR, Status.ERROR) - .put(VServerStatus.CHANGE_TYPE, Status.PENDING) - .put(VServerStatus.REGISTERING, Status.PENDING) - .put(VServerStatus.UNRECOGNIZED, Status.UNRECOGNIZED).build(); + public static final Map vServerToStatus = ImmutableMap + . builder() + .put(VServerStatus.DEPLOYING, Status.PENDING) + .put(VServerStatus.RUNNING, Status.RUNNING) + .put(VServerStatus.STOPPING, Status.PENDING) + .put(VServerStatus.STOPPED, Status.SUSPENDED) + .put(VServerStatus.STARTING, Status.PENDING) + .put(VServerStatus.FAILOVER, Status.RUNNING) + .put(VServerStatus.UNEXPECTED_STOP, Status.SUSPENDED) + .put(VServerStatus.RESTORING, Status.PENDING) + .put(VServerStatus.BACKUP_ING, Status.PENDING) + .put(VServerStatus.ERROR, Status.ERROR) + .put(VServerStatus.START_ERROR, Status.ERROR) + .put(VServerStatus.STOP_ERROR, Status.ERROR) + .put(VServerStatus.CHANGE_TYPE, Status.PENDING) + .put(VServerStatus.REGISTERING, Status.PENDING) + .put(VServerStatus.UNRECOGNIZED, Status.UNRECOGNIZED).build(); - @Resource - @Named(ComputeServiceConstants.COMPUTE_LOGGER) - protected Logger logger = Logger.NULL; + @Resource + @Named(ComputeServiceConstants.COMPUTE_LOGGER) + protected Logger logger = Logger.NULL; - protected final Supplier> locations; - protected final Supplier> images; - protected final Supplier> hardwares; - protected final GroupNamingConvention nodeNamingConvention; + protected final Supplier> locations; + protected final Supplier> images; + protected final Supplier> hardwares; + protected final GroupNamingConvention nodeNamingConvention; - private static class FindImageForVServer implements Predicate { - private final VServer server; + private static class FindImageForVServer implements Predicate { + private final VServer server; - private FindImageForVServer(VServer server) { - this.server = server; - } + private FindImageForVServer(VServer server) { + this.server = server; + } - @Override - public boolean apply(Image input) { - return input.getId().equals(server.getDiskimageId()); - } - } + @Override + public boolean apply(Image input) { + return input.getId().equals(server.getDiskimageId()); + } + } - protected Image parseImage(VServer from) { - try { - return Iterables.find(images.get(), new FindImageForVServer(from)); - } catch (NoSuchElementException e) { - logger.warn("could not find a matching image for server %s", from); - } - return null; - } + protected Image parseImage(VServer from) { + try { + return Iterables.find(images.get(), new FindImageForVServer(from)); + } catch (NoSuchElementException e) { + logger.warn("could not find a matching image for server %s", from); + } + return null; + } - private static class FindHardwareForServerType implements - Predicate { - private final String type; + private static class FindHardwareForServerType implements + Predicate { + private final String type; - private FindHardwareForServerType(String type) { - this.type = type; - } + private FindHardwareForServerType(String type) { + this.type = type; + } - @Override - public boolean apply(Hardware input) { - return input.getName().equals(type); - } - } + @Override + public boolean apply(Hardware input) { + return input.getName().equals(type); + } + } - protected Hardware parseHardware(String from) { - try { - return Iterables.find(hardwares.get(), - new FindHardwareForServerType(from)); - } catch (NoSuchElementException e) { - logger.warn( - "could not find a matching hardware for server type %s", - from); - } - return null; - } + protected Hardware parseHardware(String from) { + try { + return Iterables.find(hardwares.get(), + new FindHardwareForServerType(from)); + } catch (NoSuchElementException e) { + logger.warn( + "could not find a matching hardware for server type %s", + from); + } + return null; + } - private static class FindLocationForVServer implements Predicate { - private final VServerWithVNICs server; + private static class FindLocationForVServer implements Predicate { + private final VServerWithVNICs server; - private FindLocationForVServer(VServerWithVNICs server) { - this.server = server; - } + private FindLocationForVServer(VServerWithVNICs server) { + this.server = server; + } - @Override - public boolean apply(Location input) { - return input.getId().equals( - Iterables.getLast(server.getVnics()).getNetworkId()); - } - } + @Override + public boolean apply(Location input) { + return input.getId().equals( + Iterables.getLast(server.getVnics()).getNetworkId()); + } + } - protected Location parseLocation(VServerWithVNICs from) { - try { - return Iterables.find(locations.get(), new FindLocationForVServer( - from)); - } catch (NoSuchElementException e) { - logger.warn("could not find a matching realm for server %s", from); - } - return null; - } + protected Location parseLocation(VServerWithVNICs from) { + try { + return Iterables.find(locations.get(), new FindLocationForVServer( + from)); + } catch (NoSuchElementException e) { + logger.warn("could not find a matching realm for server %s", from); + } + return null; + } - @Inject - VServerMetadataToNodeMetadata( - @Memoized Supplier> locations, - @Memoized Supplier> images, - @Memoized Supplier> hardwares, - GroupNamingConvention.Factory namingConvention) { - this.images = checkNotNull(images, "images"); - this.locations = checkNotNull(locations, "locations"); - this.hardwares = checkNotNull(hardwares, "hardwares"); - this.nodeNamingConvention = checkNotNull(namingConvention, - "namingConvention").createWithoutPrefix(); - } + @Inject + VServerMetadataToNodeMetadata( + @Memoized Supplier> locations, + @Memoized Supplier> images, + @Memoized Supplier> hardwares, + GroupNamingConvention.Factory namingConvention) { + this.images = checkNotNull(images, "images"); + this.locations = checkNotNull(locations, "locations"); + this.hardwares = checkNotNull(hardwares, "hardwares"); + this.nodeNamingConvention = checkNotNull(namingConvention, + "namingConvention").createWithoutPrefix(); + } - @Override - public NodeMetadata apply(VServerMetadata from) { - NodeMetadataBuilder builder = new NodeMetadataBuilder(); + @Override + public NodeMetadata apply(VServerMetadata from) { + NodeMetadataBuilder builder = new NodeMetadataBuilder(); - builder.ids(from.getId()); - builder.name(from.getName()); - builder.group(nodeNamingConvention.groupInUniqueNameOrNull(from - .getName())); - if (from.getStatus() == null) - System.out.println("status null for: " + from.getId() + ": " - + from.getName()); + builder.ids(from.getId()); + builder.name(from.getName()); + builder.group(nodeNamingConvention.groupInUniqueNameOrNull(from + .getName())); + if (from.getStatus() == null) + System.out.println("status null for: " + from.getId() + ": " + + from.getName()); - builder.status(vServerToStatus.get(from.getStatus())); - builder.privateAddresses(ImmutableSet. of()); - builder.publicAddresses(ImmutableSet. of()); + builder.status(vServerToStatus.get(from.getStatus())); + builder.privateAddresses(ImmutableSet. of()); + builder.publicAddresses(ImmutableSet. of()); - // - // if (from.getIps() != null) { - // - // builder.publicAddresses(Collections2.transform(from.getIps(), - // new Function() { - // - // @Override - // public String apply(PublicIP input) { - // return input.getAddress(); - // } - // - // })); - // } + // + // if (from.getIps() != null) { + // + // builder.publicAddresses(Collections2.transform(from.getIps(), + // new Function() { + // + // @Override + // public String apply(PublicIP input) { + // return input.getAddress(); + // } + // + // })); + // } - if (from.getServer() != null) { + if (from.getServer() != null) { - builder.imageId(from.getServer().getDiskimageId()); - builder.hardware(parseHardware(from.getServer().getType())); + builder.imageId(from.getServer().getDiskimageId()); + builder.hardware(parseHardware(from.getServer().getType())); - LoginCredentials.Builder credentialsBuilder = LoginCredentials - .builder().password(from.getInitialPassword()); + LoginCredentials.Builder credentialsBuilder = LoginCredentials + .builder().password(from.getInitialPassword()); - Image image = parseImage(from.getServer()); - // image will not be found if server was created a while back and - // the image has since been destroyed or discontinued (like an old - // CentOS version) - if (image != null) { + Image image = parseImage(from.getServer()); + // image will not be found if server was created a while back and + // the image has since been destroyed or discontinued (like an old + // CentOS version) + if (image != null) { - builder.operatingSystem(image.getOperatingSystem()); - String user = image.getDefaultCredentials().getUser(); - credentialsBuilder.identity(user); + builder.operatingSystem(image.getOperatingSystem()); + String user = image.getDefaultCredentials().getUser(); + credentialsBuilder.identity(user); + } + + builder.credentials(credentialsBuilder.build()); + + if (from.getServer() instanceof VServerWithVNICs) { + + VServerWithVNICs server = (VServerWithVNICs) from.getServer(); + builder.location(parseLocation(server)); + List ips = new ArrayList(); + if (server.getVnics() != null && server.getVnics().iterator().next().getPrivateIp() != null) { + ips.add(server.getVnics().iterator().next().getPrivateIp()); } + builder.privateAddresses(ips); + } + } + if (from.getTemplate() != null) { + // when creating a new node + builder.location(from.getTemplate().getLocation()); + } - builder.credentials(credentialsBuilder.build()); - - if (from.getServer() instanceof VServerWithVNICs) { - - VServerWithVNICs server = (VServerWithVNICs) from.getServer(); - builder.location(parseLocation(server)); - List ips = new ArrayList(); - if (server.getVnics() != null && server.getVnics().iterator().next().getPrivateIp() != null) { - ips.add(server.getVnics().iterator().next().getPrivateIp()); - } - builder.privateAddresses(ips); - } - } - if (from.getTemplate() != null) { - // when creating a new node - builder.location(from.getTemplate().getLocation()); - } - - return builder.build(); - } + return builder.build(); + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/predicates/ServerStopped.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/predicates/ServerStopped.java index bda281ca71..4c9c96bc6a 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/predicates/ServerStopped.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/predicates/ServerStopped.java @@ -37,27 +37,27 @@ import com.google.common.base.Predicate; @Singleton public class ServerStopped implements Predicate { - private final FGCPApi api; + private final FGCPApi api; - @Resource - protected Logger logger = Logger.NULL; + @Resource + protected Logger logger = Logger.NULL; - @Inject - public ServerStopped(FGCPApi api) { - this.api = api; - } + @Inject + public ServerStopped(FGCPApi api) { + this.api = api; + } - public boolean apply(String serverId) { - logger.trace("looking for status on server %s", serverId); + public boolean apply(String serverId) { + logger.trace("looking for status on server %s", serverId); - VServerStatus status = api.getVirtualServerApi().getStatus(serverId); - logger.trace("looking for status on server %s: currently: %s", - serverId, status); + VServerStatus status = api.getVirtualServerApi().getStatus(serverId); + logger.trace("looking for status on server %s: currently: %s", + serverId, status); - if (status == VServerStatus.ERROR || status == VServerStatus.STOP_ERROR) - throw new IllegalStateException("server not around or in error: " - + status); - return status == VServerStatus.STOPPED; - } + if (status == VServerStatus.ERROR || status == VServerStatus.STOP_ERROR) + throw new IllegalStateException("server not around or in error: " + + status); + return status == VServerStatus.STOPPED; + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/predicates/SystemStatusNormal.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/predicates/SystemStatusNormal.java index 881233560e..c11191edf7 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/predicates/SystemStatusNormal.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/predicates/SystemStatusNormal.java @@ -23,7 +23,6 @@ import javax.inject.Inject; import javax.inject.Singleton; import org.jclouds.fujitsu.fgcp.FGCPApi; -import org.jclouds.fujitsu.fgcp.domain.VServerStatus; import org.jclouds.fujitsu.fgcp.domain.VSystemStatus; import org.jclouds.logging.Logger; @@ -37,26 +36,26 @@ import com.google.common.base.Predicate; @Singleton public class SystemStatusNormal implements Predicate { - private final FGCPApi api; + private final FGCPApi api; - @Resource - protected Logger logger = Logger.NULL; + @Resource + protected Logger logger = Logger.NULL; - @Inject - public SystemStatusNormal(FGCPApi api) { - this.api = api; - } + @Inject + public SystemStatusNormal(FGCPApi api) { + this.api = api; + } - public boolean apply(String systemId) { - logger.trace("looking for status on system %s", systemId); + public boolean apply(String systemId) { + logger.trace("looking for status on system %s", systemId); - VSystemStatus status = api.getVirtualSystemApi().getStatus(systemId); - logger.trace("looking for status on system %s: currently: %s", - systemId, status); + VSystemStatus status = api.getVirtualSystemApi().getStatus(systemId); + logger.trace("looking for status on system %s: currently: %s", + systemId, status); - if (status == VSystemStatus.ERROR) - throw new IllegalStateException("system in error: " + status); - return status == VSystemStatus.NORMAL; - } + if (status == VSystemStatus.ERROR) + throw new IllegalStateException("system in error: " + status); + return status == VSystemStatus.NORMAL; + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/strategy/FGCPComputeServiceAdapter.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/strategy/FGCPComputeServiceAdapter.java index 732a8a6d09..ef989c5254 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/strategy/FGCPComputeServiceAdapter.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/strategy/FGCPComputeServiceAdapter.java @@ -44,10 +44,8 @@ import org.jclouds.fujitsu.fgcp.compute.functions.ResourceIdToSystemId; import org.jclouds.fujitsu.fgcp.compute.predicates.ServerStopped; import org.jclouds.fujitsu.fgcp.compute.predicates.SystemStatusNormal; import org.jclouds.fujitsu.fgcp.compute.strategy.VServerMetadata.Builder; -import org.jclouds.fujitsu.fgcp.domain.BuiltinServerConfiguration; import org.jclouds.fujitsu.fgcp.domain.DiskImage; import org.jclouds.fujitsu.fgcp.domain.ServerType; -import org.jclouds.fujitsu.fgcp.domain.VServer; import org.jclouds.fujitsu.fgcp.domain.VServerStatus; import org.jclouds.fujitsu.fgcp.domain.VServerWithDetails; import org.jclouds.fujitsu.fgcp.domain.VServerWithVNICs; @@ -59,7 +57,6 @@ import org.jclouds.predicates.RetryablePredicate; import com.google.common.base.Predicate; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Iterables; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; @@ -72,223 +69,223 @@ import com.google.common.util.concurrent.ListenableFuture; */ @Singleton public class FGCPComputeServiceAdapter implements - ComputeServiceAdapter { + ComputeServiceAdapter { - @Resource - @Named(ComputeServiceConstants.COMPUTE_LOGGER) - protected Logger logger = Logger.NULL; + @Resource + @Named(ComputeServiceConstants.COMPUTE_LOGGER) + protected Logger logger = Logger.NULL; - private final FGCPApi api; - private final FGCPAsyncApi asyncApi; - protected Predicate serverStopped = null; - protected Predicate serverCreated = null; - protected Predicate systemNormal = null; - protected ResourceIdToFirewallId toFirewallId = null; - protected ResourceIdToSystemId toSystemId = null; + private final FGCPApi api; + private final FGCPAsyncApi asyncApi; + protected Predicate serverStopped = null; + protected Predicate serverCreated = null; + protected Predicate systemNormal = null; + protected ResourceIdToFirewallId toFirewallId = null; + protected ResourceIdToSystemId toSystemId = null; - @Inject - public FGCPComputeServiceAdapter(FGCPApi api, FGCPAsyncApi asyncApi, - ServerStopped serverStopped, SystemStatusNormal systemNormal, - Timeouts timeouts, ResourceIdToFirewallId toFirewallId, - ResourceIdToSystemId toSystemId) { - this.api = checkNotNull(api, "api"); - this.asyncApi = checkNotNull(asyncApi, "asyncApi"); - this.serverStopped = new RetryablePredicate( - checkNotNull(serverStopped), timeouts.nodeSuspended); - this.serverCreated = new RetryablePredicate( - checkNotNull(serverStopped), timeouts.nodeRunning); - this.systemNormal = new RetryablePredicate( - checkNotNull(systemNormal), timeouts.nodeTerminated); - this.toFirewallId = checkNotNull(toFirewallId, "ResourceIdToFirewallId"); - this.toSystemId = checkNotNull(toSystemId, "ResourceIdToSystemId"); - } + @Inject + public FGCPComputeServiceAdapter(FGCPApi api, FGCPAsyncApi asyncApi, + ServerStopped serverStopped, SystemStatusNormal systemNormal, + Timeouts timeouts, ResourceIdToFirewallId toFirewallId, + ResourceIdToSystemId toSystemId) { + this.api = checkNotNull(api, "api"); + this.asyncApi = checkNotNull(asyncApi, "asyncApi"); + this.serverStopped = new RetryablePredicate( + checkNotNull(serverStopped), timeouts.nodeSuspended); + this.serverCreated = new RetryablePredicate( + checkNotNull(serverStopped), timeouts.nodeRunning); + this.systemNormal = new RetryablePredicate( + checkNotNull(systemNormal), timeouts.nodeTerminated); + this.toFirewallId = checkNotNull(toFirewallId, "ResourceIdToFirewallId"); + this.toSystemId = checkNotNull(toSystemId, "ResourceIdToSystemId"); + } - /** - * {@inheritDoc} - */ - @Override - public NodeAndInitialCredentials createNodeWithGroupEncodedIntoName( - String group, String name, Template template) { - // Find vsys (how? create new? default to first found?) - // Target network DMZ/SECURE1/SECURE2 (how? default to DMZ?) - // Determine remaining params: [vserverType,diskImageId,networkId] - // what if no vsys exists yet? Location.AU(.contractId) creates 3? tier - // skeleton vsys and DMZ is picked? - String id = api.getVirtualSystemApi().createServer(name, - template.getHardware().getName(), template.getImage().getId(), - template.getLocation().getId()); + /** + * {@inheritDoc} + */ + @Override + public NodeAndInitialCredentials createNodeWithGroupEncodedIntoName( + String group, String name, Template template) { + // Find vsys (how? create new? default to first found?) + // Target network DMZ/SECURE1/SECURE2 (how? default to DMZ?) + // Determine remaining params: [vserverType,diskImageId,networkId] + // what if no vsys exists yet? Location.AU(.contractId) creates 3? tier + // skeleton vsys and DMZ is picked? + String id = api.getVirtualSystemApi().createServer(name, + template.getHardware().getName(), template.getImage().getId(), + template.getLocation().getId()); - // wait until fully created (i.e. transitions to stopped status) - serverCreated.apply(id); - resumeNode(id); - VServerMetadata server = getNode(id); + // wait until fully created (i.e. transitions to stopped status) + serverCreated.apply(id); + resumeNode(id); + VServerMetadata server = getNode(id); - //do we need this? - server.setTemplate(template); - String user = template.getImage().getOperatingSystem().getFamily() == OsFamily.WINDOWS ? "Administrator" - : "root"; + //do we need this? + server.setTemplate(template); + String user = template.getImage().getOperatingSystem().getFamily() == OsFamily.WINDOWS ? "Administrator" + : "root"; - return new NodeAndInitialCredentials(server, - id, LoginCredentials.builder().identity(user) - .password(server.getInitialPassword()).build()); - } + return new NodeAndInitialCredentials(server, + id, LoginCredentials.builder().identity(user) + .password(server.getInitialPassword()).build()); + } - /** - * {@inheritDoc} - */ - @Override - public Iterable listHardwareProfiles() { - return api.getVirtualDCApi().listServerTypes(); - } + /** + * {@inheritDoc} + */ + @Override + public Iterable listHardwareProfiles() { + return api.getVirtualDCApi().listServerTypes(); + } - /** - * {@inheritDoc} - */ - @Override - public Iterable listImages() { - return api.getVirtualDCApi().listDiskImages(); - } + /** + * {@inheritDoc} + */ + @Override + public Iterable listImages() { + return api.getVirtualDCApi().listDiskImages(); + } - /** - * {@inheritDoc} - */ - @Override - public DiskImage getImage(String id) { - return api.getDiskImageApi().get(id); - } + /** + * {@inheritDoc} + */ + @Override + public DiskImage getImage(String id) { + return api.getDiskImageApi().get(id); + } - /** - * {@inheritDoc} - */ - @Override - public Iterable listLocations() { - // Not using the adapter to determine locations - // see SystemAndNetworkSegmentToLocationSupplier - return ImmutableSet. of(); - } + /** + * {@inheritDoc} + */ + @Override + public Iterable listLocations() { + // Not using the adapter to determine locations + // see SystemAndNetworkSegmentToLocationSupplier + return ImmutableSet. of(); + } - /** - * {@inheritDoc} - */ - @Override - public VServerMetadata getNode(String id) { - Builder builder = VServerMetadata.builder(); - builder.id(id); + /** + * {@inheritDoc} + */ + @Override + public VServerMetadata getNode(String id) { + Builder builder = VServerMetadata.builder(); + builder.id(id); - List> futures = new ArrayList>(); + List> futures = new ArrayList>(); - futures.add(asyncApi.getVirtualServerApi().getDetails(id)); - futures.add(asyncApi.getVirtualServerApi().getStatus(id)); - futures.add(asyncApi.getVirtualServerApi().getInitialPassword(id)); - // mapped public ips? - String fwId = toFirewallId.apply(id); -// futures.add(asyncApi.getBuiltinServerApi().getConfiguration(fwId, -// BuiltinServerConfiguration.SLB_RULE)); - try { - List results = Futures.successfulAsList(futures).get(); - VServerWithDetails server = (VServerWithDetails) results.get(0); - VServerStatus status = (VServerStatus) results.get(1); - System.out.println("getNode(" + id + ")'s getDetails: " + status +" - " + server); - if (server == null) { - server = api.getVirtualServerApi().getDetails(id); - System.out.println("getNode(" + id + ")'s getDetails(2) returns: " + server); + futures.add(asyncApi.getVirtualServerApi().getDetails(id)); + futures.add(asyncApi.getVirtualServerApi().getStatus(id)); + futures.add(asyncApi.getVirtualServerApi().getInitialPassword(id)); + // mapped public ips? + String fwId = toFirewallId.apply(id); +// futures.add(asyncApi.getBuiltinServerApi().getConfiguration(fwId, +// BuiltinServerConfiguration.SLB_RULE)); + try { + List results = Futures.successfulAsList(futures).get(); + VServerWithDetails server = (VServerWithDetails) results.get(0); + VServerStatus status = (VServerStatus) results.get(1); + System.out.println("getNode(" + id + ")'s getDetails: " + status +" - " + server); + if (server == null) { + server = api.getVirtualServerApi().getDetails(id); + System.out.println("getNode(" + id + ")'s getDetails(2) returns: " + server); + } + builder.serverWithDetails(server); + builder.status(status == null ? VServerStatus.UNRECOGNIZED : status); +// System.out.println("status in adapter#getNode: " +// + (VServerStatus) results.get(1) +// +" for " +// + server.getId()); + builder.initialPassword((String) results.get(2)); +// SLB slb = ((BuiltinServer) results.get(4)).; +// slb. + } catch (InterruptedException e) { + throw Throwables.propagate(e); + } catch (ExecutionException e) { + throw Throwables.propagate(e); + } + return builder.build(); + } + + /** + * {@inheritDoc} + */ + @Override + public Iterable listNodes() { + ImmutableSet.Builder servers = ImmutableSet + . builder(); + + Set systems = api.getVirtualDCApi().listVirtualSystems(); + List> futures = new ArrayList>(); + for (VSystem system : systems) { + + futures.add(asyncApi.getVirtualSystemApi().getDetails( + system.getId())); + } + try { + for (VSystemWithDetails system : Futures.successfulAsList(futures) + .get()) { + + if (system != null) { + + for (VServerWithVNICs server : system.getServers()) { + + // skip FW (S-0001) and SLBs (>0 for SLB) + if (!server.getId().endsWith("-S-0001") && server.getVnics().iterator().next().getNicNo() == 0) { + + servers.add(getNode(server.getId())); +// Builder builder = VServerMetadata.builder(); +// builder.server(server); +// builder.status(VServerStatus.UNRECOGNIZED); +// servers.add(builder.build()); + } + } } - builder.serverWithDetails(server); - builder.status(status == null ? VServerStatus.UNRECOGNIZED : status); -// System.out.println("status in adapter#getNode: " -// + (VServerStatus) results.get(1) -// +" for " -// + server.getId()); - builder.initialPassword((String) results.get(2)); -// SLB slb = ((BuiltinServer) results.get(4)).; -// slb. - } catch (InterruptedException e) { - throw Throwables.propagate(e); - } catch (ExecutionException e) { - throw Throwables.propagate(e); - } - return builder.build(); - } + } + } catch (InterruptedException e) { + throw Throwables.propagate(e); + } catch (ExecutionException e) { + throw Throwables.propagate(e); + } - /** - * {@inheritDoc} - */ - @Override - public Iterable listNodes() { - ImmutableSet.Builder servers = ImmutableSet - . builder(); + return servers.build(); + } - Set systems = api.getVirtualDCApi().listVirtualSystems(); - List> futures = new ArrayList>(); - for (VSystem system : systems) { + /** + * {@inheritDoc} + */ + @Override + public void destroyNode(String id) { + api.getVirtualServerApi().destroy(id); + // wait until fully destroyed + String systemId = toSystemId.apply(id); + systemNormal.apply(systemId); + } - futures.add(asyncApi.getVirtualSystemApi().getDetails( - system.getId())); - } - try { - for (VSystemWithDetails system : Futures.successfulAsList(futures) - .get()) { + /** + * {@inheritDoc} + */ + @Override + public void rebootNode(String id) { + suspendNode(id); + // wait until fully stopped + serverStopped.apply(id); + resumeNode(id); + } - if (system != null) { + /** + * {@inheritDoc} + */ + @Override + public void resumeNode(String id) { + api.getVirtualServerApi().start(id); + } - for (VServerWithVNICs server : system.getServers()) { - - // skip FW (S-0001) and SLBs (>0 for SLB) - if (!server.getId().endsWith("-S-0001") && server.getVnics().iterator().next().getNicNo() == 0) { - - servers.add(getNode(server.getId())); -// Builder builder = VServerMetadata.builder(); -// builder.server(server); -// builder.status(VServerStatus.UNRECOGNIZED); -// servers.add(builder.build()); - } - } - } - } - } catch (InterruptedException e) { - throw Throwables.propagate(e); - } catch (ExecutionException e) { - throw Throwables.propagate(e); - } - - return servers.build(); - } - - /** - * {@inheritDoc} - */ - @Override - public void destroyNode(String id) { - api.getVirtualServerApi().destroy(id); - // wait until fully destroyed - String systemId = toSystemId.apply(id); - systemNormal.apply(systemId); - } - - /** - * {@inheritDoc} - */ - @Override - public void rebootNode(String id) { - suspendNode(id); - // wait until fully stopped - serverStopped.apply(id); - resumeNode(id); - } - - /** - * {@inheritDoc} - */ - @Override - public void resumeNode(String id) { - api.getVirtualServerApi().start(id); - } - - /** - * {@inheritDoc} - */ - @Override - public void suspendNode(String id) { - api.getVirtualServerApi().stop(id); - } + /** + * {@inheritDoc} + */ + @Override + public void suspendNode(String id) { + api.getVirtualServerApi().stop(id); + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/strategy/VServerMetadata.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/strategy/VServerMetadata.java index e9835ac349..d0eb0a1680 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/strategy/VServerMetadata.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/compute/strategy/VServerMetadata.java @@ -39,140 +39,140 @@ import com.google.common.collect.ImmutableSet; */ public class VServerMetadata { - protected VServer server; - protected String id; - protected String name; - protected Template template; - protected String initialPassword; - protected VServerStatus status = VServerStatus.UNRECOGNIZED; - protected Set ips; - protected DiskImage image; + protected VServer server; + protected String id; + protected String name; + protected Template template; + protected String initialPassword; + protected VServerStatus status = VServerStatus.UNRECOGNIZED; + protected Set ips; + protected DiskImage image; - public VServerMetadata(VServer server, String initialPassword, - VServerStatus status, DiskImage image, Set publicIps) { - this.server = checkNotNull(server, "server"); - this.initialPassword = initialPassword; - this.status = status; - this.image = image; - this.ips = publicIps; - id = server.getId(); - name = server.getName(); - } + public VServerMetadata(VServer server, String initialPassword, + VServerStatus status, DiskImage image, Set publicIps) { + this.server = checkNotNull(server, "server"); + this.initialPassword = initialPassword; + this.status = status; + this.image = image; + this.ips = publicIps; + id = server.getId(); + name = server.getName(); + } - public VServerMetadata(String id, String name, Template template, - VServerStatus status) { - this.id = checkNotNull(id, "id"); - this.name = checkNotNull(name, "name"); - this.template = checkNotNull(template, "template"); - this.status = checkNotNull(status, "status"); - } + public VServerMetadata(String id, String name, Template template, + VServerStatus status) { + this.id = checkNotNull(id, "id"); + this.name = checkNotNull(name, "name"); + this.template = checkNotNull(template, "template"); + this.status = checkNotNull(status, "status"); + } - public VServer getServer() { - return server; - } + public VServer getServer() { + return server; + } - public String getId() { - return id; - } + public String getId() { + return id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public Template getTemplate() { - return template; - } + public Template getTemplate() { + return template; + } - public void setTemplate(Template template) { - this.template = template; - } + public void setTemplate(Template template) { + this.template = template; + } - public String getInitialPassword() { - return initialPassword; - } + public String getInitialPassword() { + return initialPassword; + } - public VServerStatus getStatus() { - return status; - } + public VServerStatus getStatus() { + return status; + } - public Set getIps() { - return ips; - } + public Set getIps() { + return ips; + } - public static Builder builder() { - return new Builder(); - } + public static Builder builder() { + return new Builder(); + } - public static class Builder { - private VServer server; - private VServerWithVNICs serverWithDetails; - private String id; - private String name; - private Template template; - private String initialPassword; - private VServerStatus status = VServerStatus.UNRECOGNIZED; - private Set publicIps = ImmutableSet.of(); - private DiskImage image; + public static class Builder { + private VServer server; + private VServerWithVNICs serverWithDetails; + private String id; + private String name; + private Template template; + private String initialPassword; + private VServerStatus status = VServerStatus.UNRECOGNIZED; + private Set publicIps = ImmutableSet.of(); + private DiskImage image; - public Builder id(String id) { - this.id = id; - return this; - } + public Builder id(String id) { + this.id = id; + return this; + } - public Builder name(String name) { - this.name = name; - return this; - } + public Builder name(String name) { + this.name = name; + return this; + } - public Builder template(Template template) { - this.template = template; - return this; - } + public Builder template(Template template) { + this.template = template; + return this; + } -// public Builder server(VServer server) { -// this.server = server; -// return this; -// } +// public Builder server(VServer server) { +// this.server = server; +// return this; +// } - public Builder serverWithDetails(VServerWithVNICs serverWithDetails) { - this.serverWithDetails = serverWithDetails; - return this; - } + public Builder serverWithDetails(VServerWithVNICs serverWithDetails) { + this.serverWithDetails = serverWithDetails; + return this; + } - public Builder initialPassword(String password) { - this.initialPassword = password; - return this; - } + public Builder initialPassword(String password) { + this.initialPassword = password; + return this; + } - public Builder status(VServerStatus status) { - this.status = status; - return this; - } + public Builder status(VServerStatus status) { + this.status = status; + return this; + } - public Builder image(DiskImage image) { - this.image = image; - return this; - } + public Builder image(DiskImage image) { + this.image = image; + return this; + } - public Builder publicIps(Set publicIps) { - this.publicIps = publicIps; - return this; - } + public Builder publicIps(Set publicIps) { + this.publicIps = publicIps; + return this; + } - public VServerMetadata build() { - if (initialPassword == null) initialPassword = ""; - if (server != null) { - return new VServerMetadata(server, initialPassword, status, - image, publicIps); - } else if (serverWithDetails != null) { - return new VServerMetadata(serverWithDetails, initialPassword, - status, image, publicIps); - } else { - // sometimes these fields are null because the server is returning a verify error - if (id == null) id = "dummy-id"; - if (name == null) name = "dummy-name"; - return new VServerMetadata(id, name, template, status); - } - } - } + public VServerMetadata build() { + if (initialPassword == null) initialPassword = ""; + if (server != null) { + return new VServerMetadata(server, initialPassword, status, + image, publicIps); + } else if (serverWithDetails != null) { + return new VServerMetadata(serverWithDetails, initialPassword, + status, image, publicIps); + } else { + // sometimes these fields are null because the server is returning a verify error + if (id == null) id = "dummy-id"; + if (name == null) name = "dummy-name"; + return new VServerMetadata(id, name, template, status); + } + } + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/AddressRange.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/AddressRange.java index 032a718e16..30755a9cc4 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/AddressRange.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/AddressRange.java @@ -28,30 +28,30 @@ import javax.xml.bind.annotation.XmlRootElement; */ @XmlRootElement(name = "addressrange") public class AddressRange { - private String range; + private String range; - private String from; + private String from; - private String to; + private String to; - /** - * @return the range - */ - public String getRange() { - return range; - } + /** + * @return the range + */ + public String getRange() { + return range; + } - /** - * @return the from - */ - public String getFrom() { - return from; - } + /** + * @return the from + */ + public String getFrom() { + return from; + } - /** - * @return the to - */ - public String getTo() { - return to; - } + /** + * @return the to + */ + public String getTo() { + return to; + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/BuiltinServer.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/BuiltinServer.java index 911b05c5f0..cd8325147a 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/BuiltinServer.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/BuiltinServer.java @@ -29,45 +29,45 @@ import javax.xml.bind.annotation.XmlRootElement; */ @XmlRootElement(name = "efm") public class BuiltinServer { - @XmlElement(name = "efmId") - private String id; - @XmlElement(name = "efmType") - private BuiltinServerType builtinServerType; - @XmlElement(name = "efmName") - private String name; - private String creator; - private String slbVip; - private Firewall firewall; - private SLB loadbalancer; + @XmlElement(name = "efmId") + private String id; + @XmlElement(name = "efmType") + private BuiltinServerType builtinServerType; + @XmlElement(name = "efmName") + private String name; + private String creator; + private String slbVip; + private Firewall firewall; + private SLB loadbalancer; - public enum BuiltinServerType {FW, SLB} + public enum BuiltinServerType {FW, SLB} - public String getId() { - return id; - } + public String getId() { + return id; + } - public BuiltinServerType getType() { - return builtinServerType; - } + public BuiltinServerType getType() { + return builtinServerType; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public String getCreator() { - return creator; - } + public String getCreator() { + return creator; + } - public String getSlbVip() { - return slbVip; - } + public String getSlbVip() { + return slbVip; + } - public Firewall getFirewall() { - return firewall; - } + public Firewall getFirewall() { + return firewall; + } - public SLB getLoadbalancer() { - return loadbalancer; - } + public SLB getLoadbalancer() { + return loadbalancer; + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/BuiltinServerBackup.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/BuiltinServerBackup.java index 79374f9356..8548758f12 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/BuiltinServerBackup.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/BuiltinServerBackup.java @@ -31,45 +31,45 @@ import com.google.common.base.Objects; */ @XmlRootElement(name = "backup") public class BuiltinServerBackup { - @XmlElement(name = "backupId") - private String id; - @XmlElement(name = "backupTime") - private String time; + @XmlElement(name = "backupId") + private String id; + @XmlElement(name = "backupTime") + private String time; - /** - * @return the id - */ - public String getId() { - return id; - } + /** + * @return the id + */ + public String getId() { + return id; + } - /** - * @return the time - */ - public String getTime() { - return time; - } + /** + * @return the time + */ + public String getTime() { + return time; + } - @Override - public int hashCode() { - return Objects.hashCode(id); - } + @Override + public int hashCode() { + return Objects.hashCode(id); + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - BuiltinServerBackup that = BuiltinServerBackup.class.cast(obj); - return Objects.equal(this.id, that.id); - } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + BuiltinServerBackup that = BuiltinServerBackup.class.cast(obj); + return Objects.equal(this.id, that.id); + } - @Override - public String toString() { - return Objects.toStringHelper(this).omitNullValues().add("id", id) - .add("time", time).toString(); - } + @Override + public String toString() { + return Objects.toStringHelper(this).omitNullValues().add("id", id) + .add("time", time).toString(); + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/BuiltinServerConfiguration.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/BuiltinServerConfiguration.java index 5f7fa6ac23..1225446560 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/BuiltinServerConfiguration.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/BuiltinServerConfiguration.java @@ -33,36 +33,36 @@ import com.google.common.base.CaseFormat; * @author Dies Koper */ public enum BuiltinServerConfiguration { - FW_NAT_RULE, - FW_DNS, - FW_POLICY, - FW_LOG, - FW_LIMIT_POLICY, - SLB_RULE, - SLB_LOAD_STATISTICS, - SLB_ERROR_STATISTICS, - SLB_CERTIFICATE_LIST, - EFM_UPDATE, - SLB_CONNECTION, - UNRECOGNIZED; + FW_NAT_RULE, + FW_DNS, + FW_POLICY, + FW_LOG, + FW_LIMIT_POLICY, + SLB_RULE, + SLB_LOAD_STATISTICS, + SLB_ERROR_STATISTICS, + SLB_CERTIFICATE_LIST, + EFM_UPDATE, + SLB_CONNECTION, + UNRECOGNIZED; - public String value() { - return (CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name())); - } + public String value() { + return (CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name())); + } - @Override - public String toString() { - return value(); - } + @Override + public String toString() { + return value(); + } - public static BuiltinServerConfiguration fromValue(String configuration) { - try { - return valueOf(CaseFormat.UPPER_CAMEL - .to(CaseFormat.UPPER_UNDERSCORE, - checkNotNull(configuration, "configuration"))); - } catch (IllegalArgumentException e) { - return UNRECOGNIZED; - } - } + public static BuiltinServerConfiguration fromValue(String configuration) { + try { + return valueOf(CaseFormat.UPPER_CAMEL + .to(CaseFormat.UPPER_UNDERSCORE, + checkNotNull(configuration, "configuration"))); + } catch (IllegalArgumentException e) { + return UNRECOGNIZED; + } + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/BuiltinServerStatus.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/BuiltinServerStatus.java index 4ee7ba279d..9df85d32b2 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/BuiltinServerStatus.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/BuiltinServerStatus.java @@ -18,12 +18,12 @@ */ package org.jclouds.fujitsu.fgcp.domain; +import static com.google.common.base.Preconditions.checkNotNull; + import javax.xml.bind.annotation.XmlRootElement; import com.google.common.base.CaseFormat; -import static com.google.common.base.Preconditions.checkNotNull; - /** * Possible statuses of a built-in server, also called extended function module * (EFM), such as a firewall or load balancer (SLB). @@ -36,25 +36,25 @@ import static com.google.common.base.Preconditions.checkNotNull; */ @XmlRootElement(name = "efmStatus") public enum BuiltinServerStatus { - DEPLOYING, RUNNING, STOPPING, STOPPED, STARTING, FAILOVER, UNEXPECTED_STOP, RESTORING, BACKUP_ING, ERROR, EXECUTE_NETWORK_SERVER, START_ERROR, STOP_ERROR, UPDATE, BACKOUT, UNRECOGNIZED; + DEPLOYING, RUNNING, STOPPING, STOPPED, STARTING, FAILOVER, UNEXPECTED_STOP, RESTORING, BACKUP_ING, ERROR, EXECUTE_NETWORK_SERVER, START_ERROR, STOP_ERROR, UPDATE, BACKOUT, UNRECOGNIZED; - public String value() { - return (CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name())); - } + public String value() { + return (CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name())); + } - @Override - public String toString() { - return value(); - } + @Override + public String toString() { + return value(); + } - public static BuiltinServerStatus fromValue(String status) { - try { - return valueOf(CaseFormat.UPPER_CAMEL - .to(CaseFormat.UPPER_UNDERSCORE, - checkNotNull(status, "status"))); - } catch (IllegalArgumentException e) { - return UNRECOGNIZED; - } - } + public static BuiltinServerStatus fromValue(String status) { + try { + return valueOf(CaseFormat.UPPER_CAMEL + .to(CaseFormat.UPPER_UNDERSCORE, + checkNotNull(status, "status"))); + } catch (IllegalArgumentException e) { + return UNRECOGNIZED; + } + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/CPU.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/CPU.java index b49b9e8196..f7fa487569 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/CPU.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/CPU.java @@ -30,48 +30,48 @@ import com.google.common.base.Objects; */ @XmlRootElement(name = "cpu") public class CPU { - @XmlElement(name = "cpuArch") - private String arch; - @XmlElement(name = "cpuPerf") - private double speedPerCore; - @XmlElement(name = "numOfCpu") - private double cores; + @XmlElement(name = "cpuArch") + private String arch; + @XmlElement(name = "cpuPerf") + private double speedPerCore; + @XmlElement(name = "numOfCpu") + private double cores; - public String getArch() { - return arch; - } + public String getArch() { + return arch; + } - public double getSpeedPerCore() { - return speedPerCore; - } + public double getSpeedPerCore() { + return speedPerCore; + } - public double getCores() { - return cores; - } + public double getCores() { + return cores; + } - @Override - public int hashCode() { - return Objects.hashCode(cores, speedPerCore, arch); - } + @Override + public int hashCode() { + return Objects.hashCode(cores, speedPerCore, arch); + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - CPU that = CPU.class.cast(obj); - return Objects.equal(this.cores, that.cores) - && Objects.equal(this.speedPerCore, that.speedPerCore) - && Objects.equal(this.arch, that.arch); - } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + CPU that = CPU.class.cast(obj); + return Objects.equal(this.cores, that.cores) + && Objects.equal(this.speedPerCore, that.speedPerCore) + && Objects.equal(this.arch, that.arch); + } - @Override - public String toString() { - return Objects.toStringHelper(this).omitNullValues() - .add("cores", cores).add("speedPerCore", speedPerCore) - .add("arch", arch).toString(); - } + @Override + public String toString() { + return Objects.toStringHelper(this).omitNullValues() + .add("cores", cores).add("speedPerCore", speedPerCore) + .add("arch", arch).toString(); + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Cause.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Cause.java index c2863db2b5..3e13e10804 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Cause.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Cause.java @@ -25,76 +25,76 @@ package org.jclouds.fujitsu.fgcp.domain; * @author Dies Koper */ public class Cause { - private String cat; + private String cat; - private String status; + private String status; - private String filePath; + private String filePath; - private String current; + private String current; - private String before; + private String before; - private String today; + private String today; - private String yesterday; + private String yesterday; - private String total; + private String total; - /** - * @return category - */ - public String getCat() { - return cat; - } + /** + * @return category + */ + public String getCat() { + return cat; + } - /** - * @return the status - */ - public String getStatus() { - return status; - } + /** + * @return the status + */ + public String getStatus() { + return status; + } - /** - * @return the filePath - */ - public String getFilePath() { - return filePath; - } + /** + * @return the filePath + */ + public String getFilePath() { + return filePath; + } - /** - * @return the current - */ - public String getCurrent() { - return current; - } + /** + * @return the current + */ + public String getCurrent() { + return current; + } - /** - * @return the before - */ - public String getBefore() { - return before; - } + /** + * @return the before + */ + public String getBefore() { + return before; + } - /** - * @return the today - */ - public String getToday() { - return today; - } + /** + * @return the today + */ + public String getToday() { + return today; + } - /** - * @return the yesterday - */ - public String getYesterday() { - return yesterday; - } + /** + * @return the yesterday + */ + public String getYesterday() { + return yesterday; + } - /** - * @return the total - */ - public String getTotal() { - return total; - } + /** + * @return the total + */ + public String getTotal() { + return total; + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Direction.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Direction.java index b332fdcbb1..b76ad1db9f 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Direction.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Direction.java @@ -32,82 +32,82 @@ import com.google.common.collect.ImmutableSet; * @author Dies Koper */ public class Direction { - private String from; - private String to; - private Set policies = new LinkedHashSet(); - private Acceptable acceptable; - private Prefix prefix; - private int maxPolicyNum; + private String from; + private String to; + private Set policies = new LinkedHashSet(); + private Acceptable acceptable; + private Prefix prefix; + private int maxPolicyNum; - enum Acceptable {OK, NG} - enum Prefix {free, src, dst, proto, srcport, dstport, action, rule, tab} + enum Acceptable {OK, NG} + enum Prefix {free, src, dst, proto, srcport, dstport, action, rule, tab} - /** - * @return the from - */ - public String getFrom() { - return from; - } + /** + * @return the from + */ + public String getFrom() { + return from; + } - /** - * @return the to - */ - public String getTo() { - return to; - } + /** + * @return the to + */ + public String getTo() { + return to; + } - /** - * @return the policies - */ - public Set getPolicies() { - return policies == null ? ImmutableSet. of() : ImmutableSet - .copyOf(policies); - } + /** + * @return the policies + */ + public Set getPolicies() { + return policies == null ? ImmutableSet. of() : ImmutableSet + .copyOf(policies); + } - /** - * @return the acceptable - */ - public Acceptable getAcceptable() { - return acceptable; - } + /** + * @return the acceptable + */ + public Acceptable getAcceptable() { + return acceptable; + } - /** - * @return the prefix - */ - public Prefix getPrefix() { - return prefix; - } + /** + * @return the prefix + */ + public Prefix getPrefix() { + return prefix; + } - /** - * @return the maxPolicyNum - */ - public int getMaxPolicyNum() { - return maxPolicyNum; - } + /** + * @return the maxPolicyNum + */ + public int getMaxPolicyNum() { + return maxPolicyNum; + } - @Override - public int hashCode() { - return Objects.hashCode(from, to); - } + @Override + public int hashCode() { + return Objects.hashCode(from, to); + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Direction that = Direction.class.cast(obj); - return Objects.equal(this.from, that.from) - && Objects.equal(this.to, that.to); - } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Direction that = Direction.class.cast(obj); + return Objects.equal(this.from, that.from) + && Objects.equal(this.to, that.to); + } - @Override - public String toString() { - return Objects.toStringHelper(this).omitNullValues().add("from", from) - .add("to", to).add("prefix", prefix).add("policies", policies) - .add("maxPolicyNum", maxPolicyNum) - .add("acceptable", acceptable).toString(); - } + @Override + public String toString() { + return Objects.toStringHelper(this).omitNullValues().add("from", from) + .add("to", to).add("prefix", prefix).add("policies", policies) + .add("maxPolicyNum", maxPolicyNum) + .add("acceptable", acceptable).toString(); + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Disk.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Disk.java index dae088f095..cae3da8ba3 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Disk.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Disk.java @@ -29,57 +29,57 @@ import javax.xml.bind.annotation.XmlRootElement; */ @XmlRootElement public class Disk { - @XmlElement(name = "diskSize") - private String size; + @XmlElement(name = "diskSize") + private String size; - @XmlElement(name = "diskUsage") - private String usage; + @XmlElement(name = "diskUsage") + private String usage; - @XmlElement(name = "diskType") - private String type; + @XmlElement(name = "diskType") + private String type; - public String getSize() { - return size; - } + public String getSize() { + return size; + } - public String getUsage() { - return usage; - } + public String getUsage() { + return usage; + } - public String getType() { - return type; - } + public String getType() { + return type; + } - @Override - public boolean equals(Object o) { - if (this == o) - return true; - if (!(o instanceof Disk)) - return false; + @Override + public boolean equals(Object o) { + if (this == o) + return true; + if (!(o instanceof Disk)) + return false; - Disk disk = (Disk) o; + Disk disk = (Disk) o; - if (size != null ? !size.equals(disk.size) : disk.size != null) - return false; - if (type != null ? !type.equals(disk.type) : disk.type != null) - return false; - if (usage != null ? !usage.equals(disk.usage) : disk.usage != null) - return false; + if (size != null ? !size.equals(disk.size) : disk.size != null) + return false; + if (type != null ? !type.equals(disk.type) : disk.type != null) + return false; + if (usage != null ? !usage.equals(disk.usage) : disk.usage != null) + return false; - return true; - } + return true; + } - @Override - public int hashCode() { - int result = size != null ? size.hashCode() : 0; - result = 31 * result + (usage != null ? usage.hashCode() : 0); - result = 31 * result + (type != null ? type.hashCode() : 0); - return result; - } + @Override + public int hashCode() { + int result = size != null ? size.hashCode() : 0; + result = 31 * result + (usage != null ? usage.hashCode() : 0); + result = 31 * result + (type != null ? type.hashCode() : 0); + return result; + } - @Override - public String toString() { - return "Disk{" + "size='" + size + '\'' + ", usage='" + usage + '\'' - + ", type='" + type + '\'' + '}'; - } + @Override + public String toString() { + return "Disk{" + "size='" + size + '\'' + ", usage='" + usage + '\'' + + ", type='" + type + '\'' + '}'; + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/DiskImage.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/DiskImage.java index 5e2d3e1daf..6540f357ff 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/DiskImage.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/DiskImage.java @@ -37,164 +37,164 @@ import com.google.common.collect.ImmutableSet; */ @XmlRootElement(name = "diskimage") public class DiskImage { - @XmlElement(name = "diskimageId") - private String id; + @XmlElement(name = "diskimageId") + private String id; - @XmlElement(name = "diskimageName") - private String name; + @XmlElement(name = "diskimageName") + private String name; - private int size; + private int size; - private String osName; + private String osName; - private String osType; + private String osType; - private String creatorName; + private String creatorName; - private String registrant; + private String registrant; - private String licenseInfo; + private String licenseInfo; - private String description; + private String description; - @XmlElementWrapper(name = "softwares") - @XmlElement(name = "software") - private Set software = new LinkedHashSet(); + @XmlElementWrapper(name = "softwares") + @XmlElement(name = "software") + private Set software = new LinkedHashSet(); - public String getId() { - return id; - } + public String getId() { + return id; + } - public int getSize() { - return size; - } + public int getSize() { + return size; + } - public String getOsName() { - return osName; - } + public String getOsName() { + return osName; + } - public String getOsType() { - return osType; - } + public String getOsType() { + return osType; + } - public String getCreatorName() { - return creatorName; - } + public String getCreatorName() { + return creatorName; + } - public String getRegistrant() { - return registrant; - } + public String getRegistrant() { + return registrant; + } - public String getLicenseInfo() { - return licenseInfo; - } + public String getLicenseInfo() { + return licenseInfo; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public Set getSoftware() { - return software == null ? ImmutableSet. of() : ImmutableSet - .copyOf(software); - } + public Set getSoftware() { + return software == null ? ImmutableSet. of() : ImmutableSet + .copyOf(software); + } - public static Builder builder() { - return new Builder(); - } + public static Builder builder() { + return new Builder(); + } - public static class Builder { - private String id; - private String name; - private int size; - private String osName; - private String osType; - private String creatorName; - private String registrant; - private String licenseInfo; - private String description; - private Set software; + public static class Builder { + private String id; + private String name; + private int size; + private String osName; + private String osType; + private String creatorName; + private String registrant; + private String licenseInfo; + private String description; + private Set software; - public Builder id(String id) { - this.id = id; - return this; - } + public Builder id(String id) { + this.id = id; + return this; + } - public Builder name(String name) { - this.name = name; - return this; - } + public Builder name(String name) { + this.name = name; + return this; + } - public Builder osName(String osName) { - this.osName = osName; - return this; - } + public Builder osName(String osName) { + this.osName = osName; + return this; + } - public Builder osType(String osType) { - this.osType = osType; - return this; - } + public Builder osType(String osType) { + this.osType = osType; + return this; + } - public Builder creatorName(String creatorName) { - this.creatorName = creatorName; - return this; - } + public Builder creatorName(String creatorName) { + this.creatorName = creatorName; + return this; + } - public Builder registrant(String registrant) { - this.registrant = registrant; - return this; - } + public Builder registrant(String registrant) { + this.registrant = registrant; + return this; + } - public Builder description(String description) { - this.description = description; - return this; - } + public Builder description(String description) { + this.description = description; + return this; + } - public DiskImage build() { - DiskImage image = new DiskImage(); + public DiskImage build() { + DiskImage image = new DiskImage(); - image.id = id; - image.name = name; - image.size = size; - image.osName = osName; - image.osType = osType; - image.creatorName = creatorName; - image.registrant = registrant; - image.licenseInfo = licenseInfo; - image.description = description; - image.software = software; + image.id = id; + image.name = name; + image.size = size; + image.osName = osName; + image.osType = osType; + image.creatorName = creatorName; + image.registrant = registrant; + image.licenseInfo = licenseInfo; + image.description = description; + image.software = software; - return image; - } - } + return image; + } + } - @Override - public int hashCode() { - return Objects.hashCode(id); - } + @Override + public int hashCode() { + return Objects.hashCode(id); + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - DiskImage that = DiskImage.class.cast(obj); - return Objects.equal(this.id, that.id); - } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + DiskImage that = DiskImage.class.cast(obj); + return Objects.equal(this.id, that.id); + } - @Override - public String toString() { - return Objects.toStringHelper(this).omitNullValues().add("id", id) - .add("name", name).add("osName", osName).add("osType", osType) - .add("size", size).add("creatorName", creatorName) - .add("description", description) - .add("licenseInfo", licenseInfo).add("registrant", registrant) - .add("software", software).toString(); - } + @Override + public String toString() { + return Objects.toStringHelper(this).omitNullValues().add("id", id) + .add("name", name).add("osName", osName).add("osType", osType) + .add("size", size).add("creatorName", creatorName) + .add("description", description) + .add("licenseInfo", licenseInfo).add("registrant", registrant) + .add("software", software).toString(); + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/ErrorStatistics.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/ErrorStatistics.java index 28cb1e764a..d5764097af 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/ErrorStatistics.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/ErrorStatistics.java @@ -32,22 +32,22 @@ import com.google.common.collect.ImmutableSet; */ @XmlRootElement(name = "errorstatistics") public class ErrorStatistics { - private Period period; - private Set groups = new LinkedHashSet(); + private Period period; + private Set groups = new LinkedHashSet(); - /** - * @return the period - */ - public Period getPeriod() { - return period; - } + /** + * @return the period + */ + public Period getPeriod() { + return period; + } - /** - * @return the groups - */ - public Set getGroups() { - return groups == null ? ImmutableSet. of() : ImmutableSet - .copyOf(groups); - } + /** + * @return the groups + */ + public Set getGroups() { + return groups == null ? ImmutableSet. of() : ImmutableSet + .copyOf(groups); + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/EventLog.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/EventLog.java index bda7e2303e..f9eef692e5 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/EventLog.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/EventLog.java @@ -29,71 +29,71 @@ import com.google.common.base.Objects; */ @XmlRootElement(name = "errorlog") public class EventLog { - private String title; - private String message; - private String startDate; - private String expiry; - private String entryDate; + private String title; + private String message; + private String startDate; + private String expiry; + private String entryDate; - /** - * @return the title - */ - public String getTitle() { - return title; - } + /** + * @return the title + */ + public String getTitle() { + return title; + } - /** - * @return the message - */ - public String getMessage() { - return message; - } + /** + * @return the message + */ + public String getMessage() { + return message; + } - /** - * @return the startDate - */ - public String getStartDate() { - return startDate; - } + /** + * @return the startDate + */ + public String getStartDate() { + return startDate; + } - /** - * @return the expiry - */ - public String getExpiry() { - return expiry; - } + /** + * @return the expiry + */ + public String getExpiry() { + return expiry; + } - /** - * @return the entryDate - */ - public String getEntryDate() { - return entryDate; - } + /** + * @return the entryDate + */ + public String getEntryDate() { + return entryDate; + } - @Override - public int hashCode() { - return Objects.hashCode(entryDate, message, title); - } + @Override + public int hashCode() { + return Objects.hashCode(entryDate, message, title); + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - EventLog that = EventLog.class.cast(obj); - return Objects.equal(this.entryDate, that.entryDate) - && Objects.equal(this.message, that.message) - && Objects.equal(this.title, that.title); - } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + EventLog that = EventLog.class.cast(obj); + return Objects.equal(this.entryDate, that.entryDate) + && Objects.equal(this.message, that.message) + && Objects.equal(this.title, that.title); + } - @Override - public String toString() { - return Objects.toStringHelper(this).omitNullValues() - .add("entryDate", entryDate).add("title", title) - .add("message", message).add("startDate", startDate) - .add("expiry", expiry).toString(); - } + @Override + public String toString() { + return Objects.toStringHelper(this).omitNullValues() + .add("entryDate", entryDate).add("title", title) + .add("message", message).add("startDate", startDate) + .add("expiry", expiry).toString(); + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Firewall.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Firewall.java index f466c054b1..26f1c7efd0 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Firewall.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Firewall.java @@ -32,102 +32,102 @@ import com.google.common.collect.ImmutableSet; */ @XmlRootElement(name = "fw") public class Firewall { - private NAT nat; - private Set directions = new LinkedHashSet(); - private String log; - private String status; - private String category; - private String latestVersion; - private String comment; - private boolean firmUpdateExist; - private boolean configUpdateExist; - private String backout; - private String updateDate; - private String currentVersion; + private NAT nat; + private Set directions = new LinkedHashSet(); + private String log; + private String status; + private String category; + private String latestVersion; + private String comment; + private boolean firmUpdateExist; + private boolean configUpdateExist; + private String backout; + private String updateDate; + private String currentVersion; - /** - * @return the nat - */ - public NAT getNat() { - return nat; - } + /** + * @return the nat + */ + public NAT getNat() { + return nat; + } - /** - * @return the directions - */ - public Set getDirections() { - return directions == null ? ImmutableSet. of() - : ImmutableSet.copyOf(directions); - } + /** + * @return the directions + */ + public Set getDirections() { + return directions == null ? ImmutableSet. of() + : ImmutableSet.copyOf(directions); + } - /** - * @return the log - */ - public String getLog() { - return log; - } + /** + * @return the log + */ + public String getLog() { + return log; + } - /** - * @return the status - */ - public String getStatus() { - return status; - } + /** + * @return the status + */ + public String getStatus() { + return status; + } - /** - * @return the category - */ - public String getCategory() { - return category; - } + /** + * @return the category + */ + public String getCategory() { + return category; + } - /** - * @return the latestVersion - */ - public String getLatestVersion() { - return latestVersion; - } + /** + * @return the latestVersion + */ + public String getLatestVersion() { + return latestVersion; + } - /** - * @return the comment - */ - public String getComment() { - return comment; - } + /** + * @return the comment + */ + public String getComment() { + return comment; + } - /** - * @return the firmUpdateExist - */ - public boolean getFirmUpdateExist() { - return firmUpdateExist; - } + /** + * @return the firmUpdateExist + */ + public boolean getFirmUpdateExist() { + return firmUpdateExist; + } - /** - * @return the configUpdateExist - */ - public boolean getConfigUpdateExist() { - return configUpdateExist; - } + /** + * @return the configUpdateExist + */ + public boolean getConfigUpdateExist() { + return configUpdateExist; + } - /** - * @return the backout - */ - public String getBackout() { - return backout; - } + /** + * @return the backout + */ + public String getBackout() { + return backout; + } - /** - * @return the updateDate - */ - public String getUpdateDate() { - return updateDate; - } + /** + * @return the updateDate + */ + public String getUpdateDate() { + return updateDate; + } - /** - * @return the currentVersion - */ - public String getCurrentVersion() { - return currentVersion; - } + /** + * @return the currentVersion + */ + public String getCurrentVersion() { + return currentVersion; + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Group.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Group.java index 40c36a4bbe..38392855ac 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Group.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Group.java @@ -32,195 +32,195 @@ import com.google.common.collect.ImmutableSet; * @author Dies Koper */ public class Group { - private int id; + private int id; - private String protocol; + private String protocol; - private int port1; + private int port1; - private int port2; + private int port2; - private String balanceType; + private String balanceType; - private String uniqueType; + private String uniqueType; - private String monitorType; + private String monitorType; - private int maxConnection; + private int maxConnection; - private int uniqueRetention; + private int uniqueRetention; - private int interval; + private int interval; - private int timeout; + private int timeout; - private int retryCount; + private int retryCount; - private int certNum; + private int certNum; - private Set causes; + private Set causes; - private RecoveryAction recoveryAction; + private RecoveryAction recoveryAction; - private Set targets = new LinkedHashSet(); + private Set targets = new LinkedHashSet(); - private String validity; + private String validity; - enum RecoveryAction { - @XmlEnumValue("switch-back") - SWITCH_BACK, @XmlEnumValue("maintenance") - MAINTENANCE - } + enum RecoveryAction { + @XmlEnumValue("switch-back") + SWITCH_BACK, @XmlEnumValue("maintenance") + MAINTENANCE + } - /** - * @return the id - */ - public int getId() { - return id; - } + /** + * @return the id + */ + public int getId() { + return id; + } - /** - * @return the protocol - */ - public String getProtocol() { - return protocol; - } + /** + * @return the protocol + */ + public String getProtocol() { + return protocol; + } - /** - * @return the port1 - */ - public int getPort1() { - return port1; - } + /** + * @return the port1 + */ + public int getPort1() { + return port1; + } - /** - * @return the port2 - */ - public int getPort2() { - return port2; - } + /** + * @return the port2 + */ + public int getPort2() { + return port2; + } - /** - * @return the balanceType - */ - public String getBalanceType() { - return balanceType; - } + /** + * @return the balanceType + */ + public String getBalanceType() { + return balanceType; + } - /** - * @return the uniqueType - */ - public String getUniqueType() { - return uniqueType; - } + /** + * @return the uniqueType + */ + public String getUniqueType() { + return uniqueType; + } - /** - * @return the monitorType - */ - public String getMonitorType() { - return monitorType; - } + /** + * @return the monitorType + */ + public String getMonitorType() { + return monitorType; + } - /** - * @return the maxConnection - */ - public int getMaxConnection() { - return maxConnection; - } + /** + * @return the maxConnection + */ + public int getMaxConnection() { + return maxConnection; + } - /** - * @return the uniqueRetention - */ - public int getUniqueRetention() { - return uniqueRetention; - } + /** + * @return the uniqueRetention + */ + public int getUniqueRetention() { + return uniqueRetention; + } - /** - * @return the interval - */ - public int getInterval() { - return interval; - } + /** + * @return the interval + */ + public int getInterval() { + return interval; + } - /** - * @return the timeout - */ - public int getTimeout() { - return timeout; - } + /** + * @return the timeout + */ + public int getTimeout() { + return timeout; + } - /** - * @return the retryCount - */ - public int getRetryCount() { - return retryCount; - } + /** + * @return the retryCount + */ + public int getRetryCount() { + return retryCount; + } - /** - * @return the certNum - */ - public int getCertNum() { - return certNum; - } + /** + * @return the certNum + */ + public int getCertNum() { + return certNum; + } - /** - * @return the causes - */ - public Set getCauses() { - return causes == null ? ImmutableSet. of() : ImmutableSet - .copyOf(causes); - } + /** + * @return the causes + */ + public Set getCauses() { + return causes == null ? ImmutableSet. of() : ImmutableSet + .copyOf(causes); + } - /** - * @return the recoveryAction - */ - public RecoveryAction getRecoveryAction() { - return recoveryAction; - } + /** + * @return the recoveryAction + */ + public RecoveryAction getRecoveryAction() { + return recoveryAction; + } - /** - * @return the targets - */ - public Set getTargets() { - return targets == null ? ImmutableSet. of() : ImmutableSet - .copyOf(targets); - } + /** + * @return the targets + */ + public Set getTargets() { + return targets == null ? ImmutableSet. of() : ImmutableSet + .copyOf(targets); + } - /** - * @return the validity - */ - public String getValidity() { - return validity; - } + /** + * @return the validity + */ + public String getValidity() { + return validity; + } - @Override - public int hashCode() { - return Objects.hashCode(id); - } + @Override + public int hashCode() { + return Objects.hashCode(id); + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Group that = Group.class.cast(obj); - return Objects.equal(this.id, that.id); - } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Group that = Group.class.cast(obj); + return Objects.equal(this.id, that.id); + } - @Override - public String toString() { - return Objects.toStringHelper(this).omitNullValues().add("id", id) - .add("protocol", protocol).add("port1", port1) - .add("port2", port2).add("balanceType", balanceType) - .add("uniqueType", uniqueType).add("monitorType", monitorType) - .add("maxConnection", maxConnection) - .add("uniqueRetention", uniqueRetention) - .add("interval", interval).add("timeout", timeout) - .add("retryCount", retryCount).add("certNum", certNum) - .add("causes", causes).add("recoveryAction", recoveryAction) - .add("targets", targets).add("validity", validity).toString(); - } + @Override + public String toString() { + return Objects.toStringHelper(this).omitNullValues().add("id", id) + .add("protocol", protocol).add("port1", port1) + .add("port2", port2).add("balanceType", balanceType) + .add("uniqueType", uniqueType).add("monitorType", monitorType) + .add("maxConnection", maxConnection) + .add("uniqueRetention", uniqueRetention) + .add("interval", interval).add("timeout", timeout) + .add("retryCount", retryCount).add("certNum", certNum) + .add("causes", causes).add("recoveryAction", recoveryAction) + .add("targets", targets).add("validity", validity).toString(); + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Image.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Image.java index ed8fbacd31..2d3be5e4a8 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Image.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Image.java @@ -34,81 +34,81 @@ import com.google.common.collect.ImmutableSet; * @author Dies Koper */ public class Image { - private String id; + private String id; - private String serverCategory; + private String serverCategory; - private String serverApplication; + private String serverApplication; - private String cpuBit; + private String cpuBit; - private float sysvolSize; + private float sysvolSize; - private int numOfMaxDisk; + private int numOfMaxDisk; - private int numOfMaxNic; + private int numOfMaxNic; - @XmlElementWrapper(name = "softwares") - @XmlElement(name = "software") - private Set software = new LinkedHashSet(); + @XmlElementWrapper(name = "softwares") + @XmlElement(name = "software") + private Set software = new LinkedHashSet(); - public String getId() { - return id; - } + public String getId() { + return id; + } - public String getServerCategory() { - return serverCategory; - } + public String getServerCategory() { + return serverCategory; + } - public String getServerApplication() { - return serverApplication; - } + public String getServerApplication() { + return serverApplication; + } - public String getCpuBit() { - return cpuBit; - } + public String getCpuBit() { + return cpuBit; + } - public float getSysvolSize() { - return sysvolSize; - } + public float getSysvolSize() { + return sysvolSize; + } - public int getNumOfMaxDisk() { - return numOfMaxDisk; - } + public int getNumOfMaxDisk() { + return numOfMaxDisk; + } - public int getNumOfMaxNic() { - return numOfMaxNic; - } + public int getNumOfMaxNic() { + return numOfMaxNic; + } - public Set getSoftware() { - return software == null ? ImmutableSet. of() : ImmutableSet - .copyOf(software); - } + public Set getSoftware() { + return software == null ? ImmutableSet. of() : ImmutableSet + .copyOf(software); + } - @Override - public int hashCode() { - return Objects.hashCode(id); - } + @Override + public int hashCode() { + return Objects.hashCode(id); + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Image that = Image.class.cast(obj); - return Objects.equal(this.id, that.id); - } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Image that = Image.class.cast(obj); + return Objects.equal(this.id, that.id); + } - @Override - public String toString() { - return Objects.toStringHelper(this).omitNullValues().add("id", id) - .add("serverCategory", serverCategory) - .add("serverApplication", serverApplication) - .add("cpuBit", cpuBit).add("sysvolSize", sysvolSize) - .add("numOfMaxDisk", numOfMaxDisk) - .add("numOfMaxNic", numOfMaxNic).toString(); - } + @Override + public String toString() { + return Objects.toStringHelper(this).omitNullValues().add("id", id) + .add("serverCategory", serverCategory) + .add("serverApplication", serverApplication) + .add("cpuBit", cpuBit).add("sysvolSize", sysvolSize) + .add("numOfMaxDisk", numOfMaxDisk) + .add("numOfMaxNic", numOfMaxNic).toString(); + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Information.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Information.java index a8a822f859..21f292c4e2 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Information.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Information.java @@ -26,80 +26,80 @@ import com.google.common.base.Objects; * @author Dies Koper */ public class Information { - private int seqno; - private String title; - private String message; - private String startDate; - private String expiry; - private String entryDate; + private int seqno; + private String title; + private String message; + private String startDate; + private String expiry; + private String entryDate; - /** - * @return the seqno - */ - public int getSeqno() { - return seqno; - } + /** + * @return the seqno + */ + public int getSeqno() { + return seqno; + } - /** - * @return the title - */ - public String getTitle() { - return title; - } + /** + * @return the title + */ + public String getTitle() { + return title; + } - /** - * @return the message - */ - public String getMessage() { - return message; - } + /** + * @return the message + */ + public String getMessage() { + return message; + } - /** - * @return the startDate - */ - public String getStartDate() { - return startDate; - } + /** + * @return the startDate + */ + public String getStartDate() { + return startDate; + } - /** - * @return the expiry - */ - public String getExpiry() { - return expiry; - } + /** + * @return the expiry + */ + public String getExpiry() { + return expiry; + } - /** - * @return the entryDate - */ - public String getEntryDate() { - return entryDate; - } + /** + * @return the entryDate + */ + public String getEntryDate() { + return entryDate; + } - @Override - public int hashCode() { - return Objects.hashCode(seqno, entryDate, message, title); - } + @Override + public int hashCode() { + return Objects.hashCode(seqno, entryDate, message, title); + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Information that = Information.class.cast(obj); - return Objects.equal(this.seqno, that.seqno) - && Objects.equal(this.entryDate, that.entryDate) - && Objects.equal(this.message, that.message) - && Objects.equal(this.title, that.title); - } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Information that = Information.class.cast(obj); + return Objects.equal(this.seqno, that.seqno) + && Objects.equal(this.entryDate, that.entryDate) + && Objects.equal(this.message, that.message) + && Objects.equal(this.title, that.title); + } - @Override - public String toString() { - return Objects.toStringHelper(this).omitNullValues() - .add("seqno", seqno).add("entryDate", entryDate) - .add("title", title).add("message", message) - .add("startDate", startDate).add("expiry", expiry).toString(); - } + @Override + public String toString() { + return Objects.toStringHelper(this).omitNullValues() + .add("seqno", seqno).add("entryDate", entryDate) + .add("title", title).add("message", message) + .add("startDate", startDate).add("expiry", expiry).toString(); + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/IntermediateCACert.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/IntermediateCACert.java index 7acc3871a0..879171f8f8 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/IntermediateCACert.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/IntermediateCACert.java @@ -29,92 +29,92 @@ import com.google.common.base.Objects; */ @XmlRootElement(name = "ccacert") public class IntermediateCACert implements Comparable { - private int ccacertNum; + private int ccacertNum; - private String description; + private String description; - private String subject; + private String subject; - private String issuer; + private String issuer; - private String validity; + private String validity; - private String detail; + private String detail; - /** - * @return the ccacertNum - */ - public int getCcacertNum() { - return ccacertNum; - } + /** + * @return the ccacertNum + */ + public int getCcacertNum() { + return ccacertNum; + } - /** - * @return the description - */ - public String getDescription() { - return description; - } + /** + * @return the description + */ + public String getDescription() { + return description; + } - /** - * @return the subject - */ - public String getSubject() { - return subject; - } + /** + * @return the subject + */ + public String getSubject() { + return subject; + } - /** - * @return the issuer - */ - public String getIssuer() { - return issuer; - } + /** + * @return the issuer + */ + public String getIssuer() { + return issuer; + } - /** - * @return the validity - */ - public String getValidity() { - return validity; - } + /** + * @return the validity + */ + public String getValidity() { + return validity; + } - /** - * @return the detail - */ - public String getDetail() { - return detail; - } + /** + * @return the detail + */ + public String getDetail() { + return detail; + } - @Override - public int hashCode() { - return Objects.hashCode(ccacertNum, issuer, subject, validity); - } + @Override + public int hashCode() { + return Objects.hashCode(ccacertNum, issuer, subject, validity); + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - IntermediateCACert that = IntermediateCACert.class.cast(obj); - return Objects.equal(this.ccacertNum, that.ccacertNum) - && Objects.equal(this.issuer, that.issuer) - && Objects.equal(this.subject, that.subject) - && Objects.equal(this.validity, that.validity); - } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + IntermediateCACert that = IntermediateCACert.class.cast(obj); + return Objects.equal(this.ccacertNum, that.ccacertNum) + && Objects.equal(this.issuer, that.issuer) + && Objects.equal(this.subject, that.subject) + && Objects.equal(this.validity, that.validity); + } - @Override - public String toString() { - return Objects.toStringHelper(this).omitNullValues() - .add("ccacertNum", ccacertNum).add("issuer", issuer) - .add("subject", subject).add("validity", validity) - .add("description", description).add("detail", detail) - .toString(); - } + @Override + public String toString() { + return Objects.toStringHelper(this).omitNullValues() + .add("ccacertNum", ccacertNum).add("issuer", issuer) + .add("subject", subject).add("validity", validity) + .add("description", description).add("detail", detail) + .toString(); + } - @Override - public int compareTo(IntermediateCACert o) { - return ccacertNum - o.ccacertNum; - } + @Override + public int compareTo(IntermediateCACert o) { + return ccacertNum - o.ccacertNum; + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/LoadStatistics.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/LoadStatistics.java index 654e4fca5c..9e166af3ba 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/LoadStatistics.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/LoadStatistics.java @@ -33,36 +33,36 @@ import com.google.common.collect.ImmutableSet; */ @XmlRootElement(name = "loadstatistics") public class LoadStatistics { - private Set groups = new LinkedHashSet(); + private Set groups = new LinkedHashSet(); - /** - * @return the groups - */ - public Set getGroups() { - return groups == null ? ImmutableSet. of() : ImmutableSet - .copyOf(groups); - } + /** + * @return the groups + */ + public Set getGroups() { + return groups == null ? ImmutableSet. of() : ImmutableSet + .copyOf(groups); + } - @Override - public int hashCode() { - return Objects.hashCode(groups); - } + @Override + public int hashCode() { + return Objects.hashCode(groups); + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - LoadStatistics that = LoadStatistics.class.cast(obj); - return Objects.equal(this.groups, that.groups); - } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + LoadStatistics that = LoadStatistics.class.cast(obj); + return Objects.equal(this.groups, that.groups); + } - @Override - public String toString() { - return Objects.toStringHelper(this).omitNullValues() - .add("groups", groups).toString(); - } + @Override + public String toString() { + return Objects.toStringHelper(this).omitNullValues() + .add("groups", groups).toString(); + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Memory.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Memory.java index af3b0767b6..d4bd9df3aa 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Memory.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Memory.java @@ -28,39 +28,39 @@ import com.google.common.base.Objects; * @author Dies Koper */ public class Memory implements Comparable { - @XmlElement(name = "memorySize") - private double size; + @XmlElement(name = "memorySize") + private double size; - public double getSize() { - return size; - } + public double getSize() { + return size; + } - @Override - public int hashCode() { - return Objects.hashCode(size); - } + @Override + public int hashCode() { + return Objects.hashCode(size); + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Memory that = Memory.class.cast(obj); - return Objects.equal(this.size, that.size); - } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Memory that = Memory.class.cast(obj); + return Objects.equal(this.size, that.size); + } - @Override - public String toString() { - return Objects.toStringHelper(this).omitNullValues().add("size", size) - .toString(); - } + @Override + public String toString() { + return Objects.toStringHelper(this).omitNullValues().add("size", size) + .toString(); + } - @Override - public int compareTo(Memory o) { - return Double.compare(size, o.size); - } + @Override + public int compareTo(Memory o) { + return Double.compare(size, o.size); + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/NAT.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/NAT.java index a753ed8395..d0fcbb2ddd 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/NAT.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/NAT.java @@ -30,36 +30,36 @@ import com.google.common.collect.ImmutableSet; * @author Dies Koper */ public class NAT { - private Set rules = new LinkedHashSet(); + private Set rules = new LinkedHashSet(); - /** - * @return the rules - */ - public Set getRules() { - return rules == null ? ImmutableSet. of() : ImmutableSet - .copyOf(rules); - } + /** + * @return the rules + */ + public Set getRules() { + return rules == null ? ImmutableSet. of() : ImmutableSet + .copyOf(rules); + } - @Override - public int hashCode() { - return Objects.hashCode(rules); - } + @Override + public int hashCode() { + return Objects.hashCode(rules); + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - NAT that = NAT.class.cast(obj); - return Objects.equal(this.rules, that.rules); - } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + NAT that = NAT.class.cast(obj); + return Objects.equal(this.rules, that.rules); + } - @Override - public String toString() { - return Objects.toStringHelper(this).omitNullValues() - .add("rules", rules).toString(); - } + @Override + public String toString() { + return Objects.toStringHelper(this).omitNullValues() + .add("rules", rules).toString(); + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/PerformanceInfo.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/PerformanceInfo.java index e9d9856182..37a8b780ee 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/PerformanceInfo.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/PerformanceInfo.java @@ -29,121 +29,121 @@ import com.google.common.base.Objects; */ @XmlRootElement(name = "performanceinfo") public class PerformanceInfo implements Comparable { - private long recordTime; - private double cpuUtilization; - private long diskReadRequestCount; - private long diskWriteRequestCount; - private long diskReadSector; - private long diskWriteSector; - private long nicInputByte; - private long nicOutputByte; - private long nicInputPacket; - private long nicOutputPacket; + private long recordTime; + private double cpuUtilization; + private long diskReadRequestCount; + private long diskWriteRequestCount; + private long diskReadSector; + private long diskWriteSector; + private long nicInputByte; + private long nicOutputByte; + private long nicInputPacket; + private long nicOutputPacket; - /** - * @return the recordTime - */ - public long getRecordTime() { - return recordTime; - } + /** + * @return the recordTime + */ + public long getRecordTime() { + return recordTime; + } - /** - * @return the cpuUtilization - */ - public double getCpuUtilization() { - return cpuUtilization; - } + /** + * @return the cpuUtilization + */ + public double getCpuUtilization() { + return cpuUtilization; + } - /** - * @return the diskReadRequestCount - */ - public long getDiskReadRequestCount() { - return diskReadRequestCount; - } + /** + * @return the diskReadRequestCount + */ + public long getDiskReadRequestCount() { + return diskReadRequestCount; + } - /** - * @return the diskWriteRequestCount - */ - public long getDiskWriteRequestCount() { - return diskWriteRequestCount; - } + /** + * @return the diskWriteRequestCount + */ + public long getDiskWriteRequestCount() { + return diskWriteRequestCount; + } - /** - * @return the diskReadSector - */ - public long getDiskReadSector() { - return diskReadSector; - } + /** + * @return the diskReadSector + */ + public long getDiskReadSector() { + return diskReadSector; + } - /** - * @return the diskWriteSector - */ - public long getDiskWriteSector() { - return diskWriteSector; - } + /** + * @return the diskWriteSector + */ + public long getDiskWriteSector() { + return diskWriteSector; + } - /** - * @return the nicInputByte - */ - public long getNicInputByte() { - return nicInputByte; - } + /** + * @return the nicInputByte + */ + public long getNicInputByte() { + return nicInputByte; + } - /** - * @return the nicOutputByte - */ - public long getNicOutputByte() { - return nicOutputByte; - } + /** + * @return the nicOutputByte + */ + public long getNicOutputByte() { + return nicOutputByte; + } - /** - * @return the nicInputPacket - */ - public long getNicInputPacket() { - return nicInputPacket; - } + /** + * @return the nicInputPacket + */ + public long getNicInputPacket() { + return nicInputPacket; + } - /** - * @return the nicOutputPacket - */ - public long getNicOutputPacket() { - return nicOutputPacket; - } + /** + * @return the nicOutputPacket + */ + public long getNicOutputPacket() { + return nicOutputPacket; + } - @Override - public int hashCode() { - return Objects.hashCode(recordTime); - } + @Override + public int hashCode() { + return Objects.hashCode(recordTime); + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - PerformanceInfo that = PerformanceInfo.class.cast(obj); - return Objects.equal(this.recordTime, that.recordTime); - } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + PerformanceInfo that = PerformanceInfo.class.cast(obj); + return Objects.equal(this.recordTime, that.recordTime); + } - @Override - public String toString() { - return Objects.toStringHelper(this).omitNullValues() - .add("recordTime", recordTime) - .add("cpuUtilization", cpuUtilization) - .add("diskReadRequestCount", diskReadRequestCount) - .add("diskWriteRequestCount", diskWriteRequestCount) - .add("diskReadSector", diskReadSector) - .add("diskWriteSector", diskWriteSector) - .add("nicInputByte", nicInputByte) - .add("nicOutputByte", nicOutputByte) - .add("nicInputPacket", nicInputPacket) - .add("nicOutputPacket", nicOutputPacket).toString(); - } + @Override + public String toString() { + return Objects.toStringHelper(this).omitNullValues() + .add("recordTime", recordTime) + .add("cpuUtilization", cpuUtilization) + .add("diskReadRequestCount", diskReadRequestCount) + .add("diskWriteRequestCount", diskWriteRequestCount) + .add("diskReadSector", diskReadSector) + .add("diskWriteSector", diskWriteSector) + .add("nicInputByte", nicInputByte) + .add("nicOutputByte", nicOutputByte) + .add("nicInputPacket", nicInputPacket) + .add("nicOutputPacket", nicOutputPacket).toString(); + } - @Override - public int compareTo(PerformanceInfo o) { - return (int) (recordTime - o.recordTime); - } + @Override + public int compareTo(PerformanceInfo o) { + return (int) (recordTime - o.recordTime); + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Period.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Period.java index b75173fe6c..718af01285 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Period.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Period.java @@ -25,37 +25,37 @@ package org.jclouds.fujitsu.fgcp.domain; * @author Dies Koper */ public class Period { - private String current; - private String before; - private String today; - private String yesterday; + private String current; + private String before; + private String today; + private String yesterday; - /** - * @return the current - */ - public String getCurrent() { - return current; - } + /** + * @return the current + */ + public String getCurrent() { + return current; + } - /** - * @return the before - */ - public String getBefore() { - return before; - } + /** + * @return the before + */ + public String getBefore() { + return before; + } - /** - * @return the today - */ - public String getToday() { - return today; - } + /** + * @return the today + */ + public String getToday() { + return today; + } - /** - * @return the yesterday - */ - public String getYesterday() { - return yesterday; - } + /** + * @return the yesterday + */ + public String getYesterday() { + return yesterday; + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Policy.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Policy.java index e030c12793..4c7c1675dc 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Policy.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Policy.java @@ -28,168 +28,168 @@ import com.google.common.base.Objects; * @author Dies Koper */ public class Policy implements Comparable { - private int id; + private int id; - private String src; + private String src; - private PolicyType srcType; + private PolicyType srcType; - private String srcPort; + private String srcPort; - private Service dstService; + private Service dstService; - private String dst; + private String dst; - private PolicyType dstType; + private PolicyType dstType; - private String dstPort; + private String dstPort; - private Protocol protocol; + private Protocol protocol; - private Action action; + private Action action; - private Log log; + private Log log; - enum Service { - NONE, WSUS, DNS, NTP, @XmlEnumValue("yum") - YUM, KMS, @XmlEnumValue("Symantec") - SYMANTEC, RHUI - } + enum Service { + NONE, WSUS, DNS, NTP, @XmlEnumValue("yum") + YUM, KMS, @XmlEnumValue("Symantec") + SYMANTEC, RHUI + } - enum PolicyType {IP, FQDN, FQDNF} + enum PolicyType {IP, FQDN, FQDNF} - enum Protocol { - @XmlEnumValue("tcp") - TCP, @XmlEnumValue("udp") - UDP, @XmlEnumValue("tcp-udp") - TCP_UDP, @XmlEnumValue("icmp") - ICMP - } + enum Protocol { + @XmlEnumValue("tcp") + TCP, @XmlEnumValue("udp") + UDP, @XmlEnumValue("tcp-udp") + TCP_UDP, @XmlEnumValue("icmp") + ICMP + } - enum Action { - @XmlEnumValue("Accept") - ACCEPT, @XmlEnumValue("Deny") - DENY - } + enum Action { + @XmlEnumValue("Accept") + ACCEPT, @XmlEnumValue("Deny") + DENY + } - enum Log { - @XmlEnumValue("On") - ON, @XmlEnumValue("Off") - OFF - } + enum Log { + @XmlEnumValue("On") + ON, @XmlEnumValue("Off") + OFF + } - /** - * @return the id - */ - public int getId() { - return id; - } + /** + * @return the id + */ + public int getId() { + return id; + } - /** - * @return the src - */ - public String getSrc() { - return src; - } + /** + * @return the src + */ + public String getSrc() { + return src; + } - /** - * @return the srcType - */ - public PolicyType getSrcType() { - return srcType; - } + /** + * @return the srcType + */ + public PolicyType getSrcType() { + return srcType; + } - /** - * @return the srcPort - */ - public String getSrcPort() { - return srcPort; - } + /** + * @return the srcPort + */ + public String getSrcPort() { + return srcPort; + } - /** - * @return the dstService - */ - public Service getDstService() { - return dstService; - } + /** + * @return the dstService + */ + public Service getDstService() { + return dstService; + } - /** - * @return the dst - */ - public String getDst() { - return dst; - } + /** + * @return the dst + */ + public String getDst() { + return dst; + } - /** - * @return the dstType - */ - public PolicyType getDstType() { - return dstType; - } + /** + * @return the dstType + */ + public PolicyType getDstType() { + return dstType; + } - /** - * @return the dstPort - */ - public String getDstPort() { - return dstPort; - } + /** + * @return the dstPort + */ + public String getDstPort() { + return dstPort; + } - /** - * @return the protocol - */ - public Protocol getProtocol() { - return protocol; - } + /** + * @return the protocol + */ + public Protocol getProtocol() { + return protocol; + } - /** - * @return the action - */ - public Action getAction() { - return action; - } + /** + * @return the action + */ + public Action getAction() { + return action; + } - /** - * @return the log - */ - public Log getLog() { - return log; - } + /** + * @return the log + */ + public Log getLog() { + return log; + } - @Override - public int hashCode() { - return Objects.hashCode(id); - } + @Override + public int hashCode() { + return Objects.hashCode(id); + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Policy that = Policy.class.cast(obj); - return Objects.equal(this.id, that.id); - } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Policy that = Policy.class.cast(obj); + return Objects.equal(this.id, that.id); + } - @Override - public String toString() { - return Objects.toStringHelper(this).omitNullValues() - .add("id", id) - .add("src", src) - .add("srcType", srcType) - .add("srcPort", srcPort) - .add("dstService", dstService) - .add("dst", dst) - .add("dstType", dstType) - .add("dstPort", dstPort) - .add("protocol", protocol) - .add("action", action) - .add("log", log).toString(); - } + @Override + public String toString() { + return Objects.toStringHelper(this).omitNullValues() + .add("id", id) + .add("src", src) + .add("srcType", srcType) + .add("srcPort", srcPort) + .add("dstService", dstService) + .add("dst", dst) + .add("dstType", dstType) + .add("dstPort", dstPort) + .add("protocol", protocol) + .add("action", action) + .add("log", log).toString(); + } - @Override - public int compareTo(Policy o) { - return id - o.id; - } + @Override + public int compareTo(Policy o) { + return id - o.id; + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Product.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Product.java index 447f81ea04..c1765893c6 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Product.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Product.java @@ -28,57 +28,57 @@ import com.google.common.base.Objects; * @author Dies Koper */ public class Product { - @XmlElement(name = "productName") - private String name; + @XmlElement(name = "productName") + private String name; - private String unitName; + private String unitName; - private String usedPoints; + private String usedPoints; - /** - * @return the name - */ - public String getName() { - return name; - } + /** + * @return the name + */ + public String getName() { + return name; + } - /** - * @return the unitName - */ - public String getUnitName() { - return unitName; - } + /** + * @return the unitName + */ + public String getUnitName() { + return unitName; + } - /** - * @return the usedPoints - */ - public String getUsedPoints() { - return usedPoints; - } + /** + * @return the usedPoints + */ + public String getUsedPoints() { + return usedPoints; + } - @Override - public int hashCode() { - return Objects.hashCode(name, unitName, usedPoints); - } + @Override + public int hashCode() { + return Objects.hashCode(name, unitName, usedPoints); + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Product that = Product.class.cast(obj); - return Objects.equal(this.name, that.name) - && Objects.equal(this.unitName, that.unitName) - && Objects.equal(this.usedPoints, that.usedPoints); - } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Product that = Product.class.cast(obj); + return Objects.equal(this.name, that.name) + && Objects.equal(this.unitName, that.unitName) + && Objects.equal(this.usedPoints, that.usedPoints); + } - @Override - public String toString() { - return Objects.toStringHelper(this).omitNullValues().add("name", name) - .add("unitName", unitName).add("usedPoints", usedPoints) - .toString(); - } + @Override + public String toString() { + return Objects.toStringHelper(this).omitNullValues().add("name", name) + .add("unitName", unitName).add("usedPoints", usedPoints) + .toString(); + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/PublicIP.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/PublicIP.java index 698c462cee..c672815161 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/PublicIP.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/PublicIP.java @@ -36,59 +36,59 @@ import com.google.common.base.Objects; */ public class PublicIP { - public static enum Version { - IPv4, IPv6, UNRECOGNIZED; + public static enum Version { + IPv4, IPv6, UNRECOGNIZED; - @Override - public String toString() { - return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, - name()); - } + @Override + public String toString() { + return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, + name()); + } - public static Version fromValue(String version) { - try { - return valueOf(CaseFormat.UPPER_CAMEL.to( - CaseFormat.UPPER_UNDERSCORE, - checkNotNull(version, "version"))); - } catch (IllegalArgumentException e) { - return UNRECOGNIZED; - } - } + public static Version fromValue(String version) { + try { + return valueOf(CaseFormat.UPPER_CAMEL.to( + CaseFormat.UPPER_UNDERSCORE, + checkNotNull(version, "version"))); + } catch (IllegalArgumentException e) { + return UNRECOGNIZED; + } + } - } + } - protected String address; - @XmlElement(name = "v4v6Flag") - protected Version version; + protected String address; + @XmlElement(name = "v4v6Flag") + protected Version version; - public String getAddress() { - return address; - } + public String getAddress() { + return address; + } - public Version getVersion() { - return version; - } + public Version getVersion() { + return version; + } - @Override - public int hashCode() { - return Objects.hashCode(address); - } + @Override + public int hashCode() { + return Objects.hashCode(address); + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - PublicIP that = PublicIP.class.cast(obj); - return Objects.equal(this.address, that.address); - } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + PublicIP that = PublicIP.class.cast(obj); + return Objects.equal(this.address, that.address); + } - @Override - public String toString() { - return Objects.toStringHelper(this).omitNullValues() - .add("address", address).add("version", version).toString(); - } + @Override + public String toString() { + return Objects.toStringHelper(this).omitNullValues() + .add("address", address).add("version", version).toString(); + } } \ No newline at end of file diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/PublicIPStatus.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/PublicIPStatus.java index 3b10c95e35..aa93809998 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/PublicIPStatus.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/PublicIPStatus.java @@ -18,12 +18,12 @@ */ package org.jclouds.fujitsu.fgcp.domain; +import static com.google.common.base.Preconditions.checkNotNull; + import javax.xml.bind.annotation.XmlRootElement; import com.google.common.base.CaseFormat; -import static com.google.common.base.Preconditions.checkNotNull; - /** * Possible statuses of a public IP address. *

@@ -34,24 +34,24 @@ import static com.google.common.base.Preconditions.checkNotNull; */ @XmlRootElement(name = "publicipStatus") public enum PublicIPStatus { - ATTACHED, ATTACHING, DETACHING, DETACHED, UNRECOGNIZED; + ATTACHED, ATTACHING, DETACHING, DETACHED, UNRECOGNIZED; - public String value() { - return (CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name())); - } + public String value() { + return (CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name())); + } - @Override - public String toString() { - return value(); - } + @Override + public String toString() { + return value(); + } - public static PublicIPStatus fromValue(String status) { - try { - return valueOf(CaseFormat.UPPER_CAMEL - .to(CaseFormat.UPPER_UNDERSCORE, - checkNotNull(status, "status"))); - } catch (IllegalArgumentException e) { - return UNRECOGNIZED; - } - } + public static PublicIPStatus fromValue(String status) { + try { + return valueOf(CaseFormat.UPPER_CAMEL + .to(CaseFormat.UPPER_UNDERSCORE, + checkNotNull(status, "status"))); + } catch (IllegalArgumentException e) { + return UNRECOGNIZED; + } + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Rule.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Rule.java index 6cd979822f..3dc45cad99 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Rule.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Rule.java @@ -31,54 +31,54 @@ import com.google.common.base.Objects; * @author Dies Koper */ public class Rule { - private String publicIp; - private String privateIp; - private boolean snapt; + private String publicIp; + private String privateIp; + private boolean snapt; - /** - * @return the publicIp - */ - public String getPublicIp() { - return publicIp; - } + /** + * @return the publicIp + */ + public String getPublicIp() { + return publicIp; + } - /** - * @return the privateIp - */ - public String getPrivateIp() { - return privateIp; - } + /** + * @return the privateIp + */ + public String getPrivateIp() { + return privateIp; + } - /** - * @return the snapt - */ - public boolean isSnapt() { - return snapt; - } + /** + * @return the snapt + */ + public boolean isSnapt() { + return snapt; + } - @Override - public int hashCode() { - return Objects.hashCode(privateIp, publicIp, snapt); - } + @Override + public int hashCode() { + return Objects.hashCode(privateIp, publicIp, snapt); + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Rule that = Rule.class.cast(obj); - return Objects.equal(this.privateIp, that.privateIp) - && Objects.equal(this.publicIp, that.publicIp) - && Objects.equal(this.snapt, that.snapt); - } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Rule that = Rule.class.cast(obj); + return Objects.equal(this.privateIp, that.privateIp) + && Objects.equal(this.publicIp, that.publicIp) + && Objects.equal(this.snapt, that.snapt); + } - @Override - public String toString() { - return Objects.toStringHelper(this).omitNullValues() - .add("privateIp", privateIp).add("publicIp", publicIp) - .add("snapt", snapt).toString(); - } + @Override + public String toString() { + return Objects.toStringHelper(this).omitNullValues() + .add("privateIp", privateIp).add("publicIp", publicIp) + .add("snapt", snapt).toString(); + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/SLB.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/SLB.java index 274c3b8caa..40a06958c1 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/SLB.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/SLB.java @@ -32,169 +32,169 @@ import com.google.common.collect.ImmutableSet; */ @XmlRootElement(name = "slb") public class SLB extends BuiltinServer { - private String ipAddress; + private String ipAddress; - private Set ccacerts = new LinkedHashSet(); + private Set ccacerts = new LinkedHashSet(); - private Set servercerts = new LinkedHashSet(); + private Set servercerts = new LinkedHashSet(); - private Set groups; + private Set groups; - private String srcType; + private String srcType; - private String srcPort; + private String srcPort; - private String status; + private String status; - private ErrorStatistics errorStatistics; + private ErrorStatistics errorStatistics; - private LoadStatistics loadStatistics; + private LoadStatistics loadStatistics; - private String category; + private String category; - private String latestVersion; + private String latestVersion; - private String comment; + private String comment; - private boolean firmUpdateExist; + private boolean firmUpdateExist; - private boolean configUpdateExist; + private boolean configUpdateExist; - private boolean backout; + private boolean backout; - private String updateDate; + private String updateDate; - private String currentVersion; + private String currentVersion; - private String webAccelerator; + private String webAccelerator; - /** - * @return the ipAddress - */ - public String getIpAddress() { - return ipAddress; - } + /** + * @return the ipAddress + */ + public String getIpAddress() { + return ipAddress; + } - /** - * @return the ccacerts - */ - public Set getCcacerts() { - return ccacerts == null ? ImmutableSet. of() - : ImmutableSet.copyOf(ccacerts); - } + /** + * @return the ccacerts + */ + public Set getCcacerts() { + return ccacerts == null ? ImmutableSet. of() + : ImmutableSet.copyOf(ccacerts); + } - /** - * @return the servercerts - */ - public Set getServercerts() { - return servercerts == null ? ImmutableSet. of() - : ImmutableSet.copyOf(servercerts); - } + /** + * @return the servercerts + */ + public Set getServercerts() { + return servercerts == null ? ImmutableSet. of() + : ImmutableSet.copyOf(servercerts); + } - /** - * @return the groups - */ - public Set getGroups() { - return groups == null ? ImmutableSet. of() : ImmutableSet - .copyOf(groups); - } + /** + * @return the groups + */ + public Set getGroups() { + return groups == null ? ImmutableSet. of() : ImmutableSet + .copyOf(groups); + } - /** - * @return the srcType - */ - public String getSrcType() { - return srcType; - } + /** + * @return the srcType + */ + public String getSrcType() { + return srcType; + } - /** - * @return the srcPort - */ - public String getSrcPort() { - return srcPort; - } + /** + * @return the srcPort + */ + public String getSrcPort() { + return srcPort; + } - /** - * @return the status - */ - public String getStatus() { - return status; - } + /** + * @return the status + */ + public String getStatus() { + return status; + } - /** - * @return the errorStatistics - */ - public ErrorStatistics getErrorStatistics() { - return errorStatistics; - } + /** + * @return the errorStatistics + */ + public ErrorStatistics getErrorStatistics() { + return errorStatistics; + } - /** - * @return the loadStatistics - */ - public LoadStatistics getLoadStatistics() { - return loadStatistics; - } + /** + * @return the loadStatistics + */ + public LoadStatistics getLoadStatistics() { + return loadStatistics; + } - /** - * @return the category - */ - public String getCategory() { - return category; - } + /** + * @return the category + */ + public String getCategory() { + return category; + } - /** - * @return the latestVersion - */ - public String getLatestVersion() { - return latestVersion; - } + /** + * @return the latestVersion + */ + public String getLatestVersion() { + return latestVersion; + } - /** - * @return the comment - */ - public String getComment() { - return comment; - } + /** + * @return the comment + */ + public String getComment() { + return comment; + } - /** - * @return the firmUpdateExist - */ - public boolean getFirmUpdateExist() { - return firmUpdateExist; - } + /** + * @return the firmUpdateExist + */ + public boolean getFirmUpdateExist() { + return firmUpdateExist; + } - /** - * @return the configUpdateExist - */ - public boolean getConfigUpdateExist() { - return configUpdateExist; - } + /** + * @return the configUpdateExist + */ + public boolean getConfigUpdateExist() { + return configUpdateExist; + } - /** - * @return the backout - */ - public boolean getBackout() { - return backout; - } + /** + * @return the backout + */ + public boolean getBackout() { + return backout; + } - /** - * @return the updateDate - */ - public String getUpdateDate() { - return updateDate; - } + /** + * @return the updateDate + */ + public String getUpdateDate() { + return updateDate; + } - /** - * @return the currentVersion - */ - public String getCurrentVersion() { - return currentVersion; - } + /** + * @return the currentVersion + */ + public String getCurrentVersion() { + return currentVersion; + } - /** - * @return the webAccelerator - */ - public String getWebAccelerator() { - return webAccelerator; - } + /** + * @return the webAccelerator + */ + public String getWebAccelerator() { + return webAccelerator; + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/ServerCert.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/ServerCert.java index d1dfc0698f..3df227fd3b 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/ServerCert.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/ServerCert.java @@ -29,93 +29,93 @@ import com.google.common.base.Objects; */ @XmlRootElement(name = "servercert") public class ServerCert implements Comparable { - private int certNum; + private int certNum; - private String subject; + private String subject; - private String issuer; + private String issuer; - private String validity; + private String validity; - private int groupId; + private int groupId; - private String detail; + private String detail; - /** - * @return the certNum - */ - public int getCertNum() { - return certNum; - } + /** + * @return the certNum + */ + public int getCertNum() { + return certNum; + } - /** - * @return the subject - */ - public String getSubject() { - return subject; - } + /** + * @return the subject + */ + public String getSubject() { + return subject; + } - /** - * @return the issuer - */ - public String getIssuer() { - return issuer; - } + /** + * @return the issuer + */ + public String getIssuer() { + return issuer; + } - /** - * @return the validity - */ - public String getValidity() { - return validity; - } + /** + * @return the validity + */ + public String getValidity() { + return validity; + } - /** - * @return the groupId - */ - public int getGroupId() { - return groupId; - } + /** + * @return the groupId + */ + public int getGroupId() { + return groupId; + } - /** - * @return the detail - */ - public String getDetail() { - return detail; - } + /** + * @return the detail + */ + public String getDetail() { + return detail; + } - @Override - public int hashCode() { - return Objects.hashCode(certNum, groupId, issuer, subject, validity); - } + @Override + public int hashCode() { + return Objects.hashCode(certNum, groupId, issuer, subject, validity); + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - ServerCert that = ServerCert.class.cast(obj); - return Objects.equal(this.certNum, that.certNum) - && Objects.equal(this.groupId, that.groupId) - && Objects.equal(this.issuer, that.issuer) - && Objects.equal(this.subject, that.subject) - && Objects.equal(this.validity, that.validity); - } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + ServerCert that = ServerCert.class.cast(obj); + return Objects.equal(this.certNum, that.certNum) + && Objects.equal(this.groupId, that.groupId) + && Objects.equal(this.issuer, that.issuer) + && Objects.equal(this.subject, that.subject) + && Objects.equal(this.validity, that.validity); + } - @Override - public String toString() { - return Objects.toStringHelper(this).omitNullValues() - .add("certNum", certNum).add("issuer", issuer) - .add("subject", subject).add("validity", validity) - .add("groupId", groupId).add("detail", detail).toString(); - } + @Override + public String toString() { + return Objects.toStringHelper(this).omitNullValues() + .add("certNum", certNum).add("issuer", issuer) + .add("subject", subject).add("validity", validity) + .add("groupId", groupId).add("detail", detail).toString(); + } - @Override - public int compareTo(ServerCert o) { - return (certNum - o.certNum) == 0 ? (groupId - o.groupId) - : (certNum - o.certNum); - } + @Override + public int compareTo(ServerCert o) { + return (certNum - o.certNum) == 0 ? (groupId - o.groupId) + : (certNum - o.certNum); + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/ServerType.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/ServerType.java index b4a724809b..c5a8b36c13 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/ServerType.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/ServerType.java @@ -35,111 +35,111 @@ import com.google.common.collect.Sets; */ @XmlRootElement(name = "servertype") public class ServerType implements Comparable { - private String id; + private String id; - private String name; + private String name; - private String label; + private String label; - private String comment; + private String comment; - private String productId; + private String productId; - private String productName; + private String productName; - private String price; + private String price; - private String chargeType; + private String chargeType; - private String expectedUsage; + private String expectedUsage; - private CPU cpu; + private CPU cpu; - private Memory memory; + private Memory memory; - @XmlElementWrapper(name = "disks") - @XmlElement(name = "disk") - private Set disks = Sets.newLinkedHashSet(); + @XmlElementWrapper(name = "disks") + @XmlElement(name = "disk") + private Set disks = Sets.newLinkedHashSet(); - public String getId() { - return id; - } + public String getId() { + return id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public String getLabel() { - return label; - } + public String getLabel() { + return label; + } - public String getComment() { - return comment; - } + public String getComment() { + return comment; + } - public String getProductId() { - return productId; - } + public String getProductId() { + return productId; + } - public String getProductName() { - return productName; - } + public String getProductName() { + return productName; + } - public String getPrice() { - return price; - } + public String getPrice() { + return price; + } - public String getChargeType() { - return chargeType; - } + public String getChargeType() { + return chargeType; + } - public String getExpectedUsage() { - return expectedUsage; - } + public String getExpectedUsage() { + return expectedUsage; + } - public CPU getCpu() { - return cpu; - } + public CPU getCpu() { + return cpu; + } - public Memory getMemory() { - return memory; - } + public Memory getMemory() { + return memory; + } - public Set getDisks() { - return disks == null ? ImmutableSet. of() : ImmutableSet - .copyOf(disks); - } + public Set getDisks() { + return disks == null ? ImmutableSet. of() : ImmutableSet + .copyOf(disks); + } - @Override - public int hashCode() { - return Objects.hashCode(id); - } + @Override + public int hashCode() { + return Objects.hashCode(id); + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - ServerType that = ServerType.class.cast(obj); - return Objects.equal(this.id, that.id); - } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + ServerType that = ServerType.class.cast(obj); + return Objects.equal(this.id, that.id); + } - @Override - public String toString() { - return Objects.toStringHelper(this).omitNullValues().add("id", id) - .add("name", name).add("label", label).add("comment", comment) - .add("productId", productId).add("productName", productName) - .add("price", price).add("chargeType", chargeType) - .add("expectedUsage", expectedUsage).add("cpu", cpu) - .add("memory", memory).add("disks", disks).toString(); - } + @Override + public String toString() { + return Objects.toStringHelper(this).omitNullValues().add("id", id) + .add("name", name).add("label", label).add("comment", comment) + .add("productId", productId).add("productName", productName) + .add("price", price).add("chargeType", chargeType) + .add("expectedUsage", expectedUsage).add("cpu", cpu) + .add("memory", memory).add("disks", disks).toString(); + } - @Override - public int compareTo(ServerType o) { - return memory == null ? -1 : memory.compareTo(o.memory); - } + @Override + public int compareTo(ServerType o) { + return memory == null ? -1 : memory.compareTo(o.memory); + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Software.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Software.java index cfff2a682e..0bf955a57c 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Software.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Software.java @@ -26,78 +26,78 @@ import com.google.common.base.Objects; * @author Dies Koper */ public class Software { - private String name; + private String name; - private String id; + private String id; - private String category; + private String category; - private String version; + private String version; - private String officialVersion; + private String officialVersion; - private String patch; + private String patch; - private String license; + private String license; - private String support; + private String support; - public String getName() { - return name; - } + public String getName() { + return name; + } - public String getId() { - return id; - } + public String getId() { + return id; + } - public String getCategory() { - return category; - } + public String getCategory() { + return category; + } - public String getVersion() { - return version; - } + public String getVersion() { + return version; + } - public String getOfficialVersion() { - return officialVersion; - } + public String getOfficialVersion() { + return officialVersion; + } - public String getPatch() { - return patch; - } + public String getPatch() { + return patch; + } - public String getLicense() { - return license; - } + public String getLicense() { + return license; + } - public String getSupport() { - return support; - } + public String getSupport() { + return support; + } - @Override - public int hashCode() { - return Objects.hashCode(id); - } + @Override + public int hashCode() { + return Objects.hashCode(id); + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Software that = Software.class.cast(obj); - return Objects.equal(this.id, that.id); - } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Software that = Software.class.cast(obj); + return Objects.equal(this.id, that.id); + } - @Override - public String toString() { - return Objects.toStringHelper(this).omitNullValues().add("id", id) - .add("name", name).add("category", category) - .add("version", version) - .add("officialVersion", officialVersion) - .add("support", support).add("patch", patch) - .add("license", license).toString(); - } + @Override + public String toString() { + return Objects.toStringHelper(this).omitNullValues().add("id", id) + .add("name", name).add("category", category) + .add("version", version) + .add("officialVersion", officialVersion) + .add("support", support).add("patch", patch) + .add("license", license).toString(); + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Target.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Target.java index 44cd0fe727..aeb340f772 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Target.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/Target.java @@ -26,101 +26,101 @@ import com.google.common.base.Objects; * @author Dies Koper */ public class Target { - private String serverId; + private String serverId; - private String serverName; + private String serverName; - private String ipAddress; + private String ipAddress; - private String port1; + private String port1; - private String port2; + private String port2; - private String status; + private String status; - private String now; + private String now; - private String peak; + private String peak; - /** - * @return the serverId - */ - public String getServerId() { - return serverId; - } + /** + * @return the serverId + */ + public String getServerId() { + return serverId; + } - /** - * @return the serverName - */ - public String getServerName() { - return serverName; - } + /** + * @return the serverName + */ + public String getServerName() { + return serverName; + } - /** - * @return the ipAddress - */ - public String getIpAddress() { - return ipAddress; - } + /** + * @return the ipAddress + */ + public String getIpAddress() { + return ipAddress; + } - /** - * @return the port1 - */ - public String getPort1() { - return port1; - } + /** + * @return the port1 + */ + public String getPort1() { + return port1; + } - /** - * @return the port2 - */ - public String getPort2() { - return port2; - } + /** + * @return the port2 + */ + public String getPort2() { + return port2; + } - /** - * @return the status - */ - public String getStatus() { - return status; - } + /** + * @return the status + */ + public String getStatus() { + return status; + } - /** - * @return the now - */ - public String getNow() { - return now; - } + /** + * @return the now + */ + public String getNow() { + return now; + } - /** - * @return the peak - */ - public String getPeak() { - return peak; - } + /** + * @return the peak + */ + public String getPeak() { + return peak; + } - @Override - public int hashCode() { - return Objects.hashCode(serverId); - } + @Override + public int hashCode() { + return Objects.hashCode(serverId); + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Target that = Target.class.cast(obj); - return Objects.equal(this.serverId, that.serverId); - } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Target that = Target.class.cast(obj); + return Objects.equal(this.serverId, that.serverId); + } - @Override - public String toString() { - return Objects.toStringHelper(this).omitNullValues() - .add("serverId", serverId).add("serverName", serverName) - .add("ipAddress", ipAddress).add("port1", port1) - .add("port2", port2).add("status", status).add("now", now) - .add("peak", peak).toString(); - } + @Override + public String toString() { + return Objects.toStringHelper(this).omitNullValues() + .add("serverId", serverId).add("serverName", serverName) + .add("ipAddress", ipAddress).add("port1", port1) + .add("port2", port2).add("status", status).add("now", now) + .add("peak", peak).toString(); + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/UsageInfo.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/UsageInfo.java index 48cffa4b05..61c4b368e7 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/UsageInfo.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/UsageInfo.java @@ -35,60 +35,60 @@ import com.google.common.collect.ImmutableSet; */ @XmlRootElement(name = "usageinfo") public class UsageInfo { - @XmlElement(name = "vsysId") - private String systemId; - @XmlElement(name = "vsysName") - private String systemName; + @XmlElement(name = "vsysId") + private String systemId; + @XmlElement(name = "vsysName") + private String systemName; - @XmlElementWrapper(name = "products") - @XmlElement(name = "product") - private Set products = new LinkedHashSet(); + @XmlElementWrapper(name = "products") + @XmlElement(name = "product") + private Set products = new LinkedHashSet(); - /** - * @return the systemId - */ - public String getSystemId() { - return systemId; - } + /** + * @return the systemId + */ + public String getSystemId() { + return systemId; + } - /** - * @return the systemName - */ - public String getSystemName() { - return systemName; - } + /** + * @return the systemName + */ + public String getSystemName() { + return systemName; + } - /** - * @return the products - */ - public Set getProducts() { - return products == null ? ImmutableSet. of() : ImmutableSet - .copyOf(products); - } + /** + * @return the products + */ + public Set getProducts() { + return products == null ? ImmutableSet. of() : ImmutableSet + .copyOf(products); + } - @Override - public int hashCode() { - return Objects.hashCode(systemId, systemName, products); - } + @Override + public int hashCode() { + return Objects.hashCode(systemId, systemName, products); + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - UsageInfo that = UsageInfo.class.cast(obj); - return Objects.equal(this.systemId, that.systemId) - && Objects.equal(this.systemName, that.systemName) - && Objects.equal(this.products, that.products); - } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + UsageInfo that = UsageInfo.class.cast(obj); + return Objects.equal(this.systemId, that.systemId) + && Objects.equal(this.systemName, that.systemName) + && Objects.equal(this.products, that.products); + } - @Override - public String toString() { - return Objects.toStringHelper(this).omitNullValues() - .add("systemId", systemId).add("systemName", systemName) - .add("products", products).toString(); - } + @Override + public String toString() { + return Objects.toStringHelper(this).omitNullValues() + .add("systemId", systemId).add("systemName", systemName) + .add("products", products).toString(); + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/VDisk.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/VDisk.java index e8784c4a98..e90815e3c4 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/VDisk.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/VDisk.java @@ -30,57 +30,57 @@ import com.google.common.base.Objects; */ @XmlRootElement(name = "vdisk") public class VDisk { - @XmlElement(name = "diskId") - private String id; - @XmlElement(name = "diskName") - private String name; - @XmlElement(name = "attachedTo") - private String attachedServer; - private String creator; - private double size; + @XmlElement(name = "diskId") + private String id; + @XmlElement(name = "diskName") + private String name; + @XmlElement(name = "attachedTo") + private String attachedServer; + private String creator; + private double size; - public String getId() { - return id; - } + public String getId() { + return id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public String getAttachedServer() { - return attachedServer; - } + public String getAttachedServer() { + return attachedServer; + } - public String getCreator() { - return creator; - } + public String getCreator() { + return creator; + } - public double getSize() { - return size; - } + public double getSize() { + return size; + } - @Override - public int hashCode() { - return Objects.hashCode(id); - } + @Override + public int hashCode() { + return Objects.hashCode(id); + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - VDisk that = VDisk.class.cast(obj); - return Objects.equal(this.id, that.id); - } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + VDisk that = VDisk.class.cast(obj); + return Objects.equal(this.id, that.id); + } - @Override - public String toString() { - return Objects.toStringHelper(this).omitNullValues().add("id", id) - .add("name", name).add("attachedServer", attachedServer) - .add("creator", creator).add("size", size).toString(); - } + @Override + public String toString() { + return Objects.toStringHelper(this).omitNullValues().add("id", id) + .add("name", name).add("attachedServer", attachedServer) + .add("creator", creator).add("size", size).toString(); + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/VDiskStatus.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/VDiskStatus.java index cc4459426c..c0ad812e05 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/VDiskStatus.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/VDiskStatus.java @@ -18,12 +18,12 @@ */ package org.jclouds.fujitsu.fgcp.domain; +import static com.google.common.base.Preconditions.checkNotNull; + import javax.xml.bind.annotation.XmlRootElement; import com.google.common.base.CaseFormat; -import static com.google.common.base.Preconditions.checkNotNull; - /** * Possible statuses of an attachable virtual disk. * @@ -32,24 +32,24 @@ import static com.google.common.base.Preconditions.checkNotNull; @XmlRootElement(name = "vdiskStatus") public enum VDiskStatus { - NORMAL, BACKUP_ING, DEPLOYING, DETACHING, ATTACHING, RESTORING, ERROR, UNRECOGNIZED; + NORMAL, BACKUP_ING, DEPLOYING, DETACHING, ATTACHING, RESTORING, ERROR, UNRECOGNIZED; - public String value() { - return (CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name())); - } + public String value() { + return (CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name())); + } - @Override - public String toString() { - return value(); - } + @Override + public String toString() { + return value(); + } - public static VDiskStatus fromValue(String status) { - try { - return valueOf(CaseFormat.UPPER_CAMEL - .to(CaseFormat.UPPER_UNDERSCORE, - checkNotNull(status, "status"))); - } catch (IllegalArgumentException e) { - return UNRECOGNIZED; - } - } + public static VDiskStatus fromValue(String status) { + try { + return valueOf(CaseFormat.UPPER_CAMEL + .to(CaseFormat.UPPER_UNDERSCORE, + checkNotNull(status, "status"))); + } catch (IllegalArgumentException e) { + return UNRECOGNIZED; + } + } } \ No newline at end of file diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/VNIC.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/VNIC.java index 6fbf0770c2..9091384fe1 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/VNIC.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/VNIC.java @@ -29,45 +29,45 @@ import com.google.common.base.Objects; */ @XmlRootElement(name = "vnic") public class VNIC { - private String networkId; + private String networkId; - private String privateIp; + private String privateIp; - private int nicNo; + private int nicNo; - public String getNetworkId() { - return networkId; - } + public String getNetworkId() { + return networkId; + } - public String getPrivateIp() { - return privateIp; - } + public String getPrivateIp() { + return privateIp; + } - public int getNicNo() { - return nicNo; - } + public int getNicNo() { + return nicNo; + } - @Override - public int hashCode() { - return Objects.hashCode(networkId); - } + @Override + public int hashCode() { + return Objects.hashCode(networkId); + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - VNIC that = VNIC.class.cast(obj); - return Objects.equal(this.networkId, that.networkId); - } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + VNIC that = VNIC.class.cast(obj); + return Objects.equal(this.networkId, that.networkId); + } - @Override - public String toString() { - return Objects.toStringHelper(this).omitNullValues() - .add("networkId", networkId).add("privateIp", privateIp) - .add("nicNo", nicNo).toString(); - } + @Override + public String toString() { + return Objects.toStringHelper(this).omitNullValues() + .add("networkId", networkId).add("privateIp", privateIp) + .add("nicNo", nicNo).toString(); + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/VNet.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/VNet.java index 77210c146e..99de06cc47 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/VNet.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/VNet.java @@ -30,32 +30,32 @@ import com.google.common.base.Objects; @XmlRootElement(name = "vnet") public class VNet { - private String networkId; + private String networkId; - public String getNetworkId() { - return networkId; - } + public String getNetworkId() { + return networkId; + } - @Override - public int hashCode() { - return Objects.hashCode(networkId); - } + @Override + public int hashCode() { + return Objects.hashCode(networkId); + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - VNet that = VNet.class.cast(obj); - return Objects.equal(this.networkId, that.networkId); - } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + VNet that = VNet.class.cast(obj); + return Objects.equal(this.networkId, that.networkId); + } - @Override - public String toString() { - return Objects.toStringHelper(this).add("networkId", networkId) - .toString(); - } + @Override + public String toString() { + return Objects.toStringHelper(this).add("networkId", networkId) + .toString(); + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/VServer.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/VServer.java index b3db2991cc..9db887a72c 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/VServer.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/VServer.java @@ -28,57 +28,57 @@ import com.google.common.base.Objects; * @author Dies Koper */ public class VServer { - @XmlElement(name = "vserverId") - protected String id; - @XmlElement(name = "vserverName") - protected String name; - @XmlElement(name = "vserverType") - protected String type; - protected String diskimageId; - protected String creator; + @XmlElement(name = "vserverId") + protected String id; + @XmlElement(name = "vserverName") + protected String name; + @XmlElement(name = "vserverType") + protected String type; + protected String diskimageId; + protected String creator; - public String getId() { - return id; - } + public String getId() { + return id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public String getType() { - return type; - } + public String getType() { + return type; + } - public String getDiskimageId() { - return diskimageId; - } + public String getDiskimageId() { + return diskimageId; + } - public String getCreator() { - return creator; - } + public String getCreator() { + return creator; + } - @Override - public int hashCode() { - return Objects.hashCode(id); - } + @Override + public int hashCode() { + return Objects.hashCode(id); + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - VServer that = VServer.class.cast(obj); - return Objects.equal(this.id, that.id); - } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + VServer that = VServer.class.cast(obj); + return Objects.equal(this.id, that.id); + } - @Override - public String toString() { - return Objects.toStringHelper(this).omitNullValues().add("id", id) - .add("name", name).add("type", type).add("creator", creator) - .add("diskimageId", diskimageId).toString(); - } + @Override + public String toString() { + return Objects.toStringHelper(this).omitNullValues().add("id", id) + .add("name", name).add("type", type).add("creator", creator) + .add("diskimageId", diskimageId).toString(); + } } \ No newline at end of file diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/VServerStatus.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/VServerStatus.java index 8576538965..1df5ce0591 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/VServerStatus.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/VServerStatus.java @@ -18,12 +18,12 @@ */ package org.jclouds.fujitsu.fgcp.domain; +import static com.google.common.base.Preconditions.checkNotNull; + import javax.xml.bind.annotation.XmlRootElement; import com.google.common.base.CaseFormat; -import static com.google.common.base.Preconditions.checkNotNull; - /** * Possible statuses of a virtual server. * @@ -31,24 +31,24 @@ import static com.google.common.base.Preconditions.checkNotNull; */ @XmlRootElement(name = "vserverStatus") public enum VServerStatus { - DEPLOYING, RUNNING, STOPPING, STOPPED, STARTING, FAILOVER, UNEXPECTED_STOP, RESTORING, BACKUP_ING, ERROR, START_ERROR, STOP_ERROR, CHANGE_TYPE, REGISTERING, UNRECOGNIZED; + DEPLOYING, RUNNING, STOPPING, STOPPED, STARTING, FAILOVER, UNEXPECTED_STOP, RESTORING, BACKUP_ING, ERROR, START_ERROR, STOP_ERROR, CHANGE_TYPE, REGISTERING, UNRECOGNIZED; - public String value() { - return (CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name())); - } + public String value() { + return (CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name())); + } - @Override - public String toString() { - return value(); - } + @Override + public String toString() { + return value(); + } - public static VServerStatus fromValue(String status) { - try { - return valueOf(CaseFormat.UPPER_CAMEL - .to(CaseFormat.UPPER_UNDERSCORE, - checkNotNull(status, "status"))); - } catch (IllegalArgumentException e) { - return UNRECOGNIZED; - } - } + public static VServerStatus fromValue(String status) { + try { + return valueOf(CaseFormat.UPPER_CAMEL + .to(CaseFormat.UPPER_UNDERSCORE, + checkNotNull(status, "status"))); + } catch (IllegalArgumentException e) { + return UNRECOGNIZED; + } + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/VServerWithDetails.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/VServerWithDetails.java index d9613a41c2..c969953896 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/VServerWithDetails.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/VServerWithDetails.java @@ -35,25 +35,25 @@ import com.google.common.collect.ImmutableSet; */ @XmlRootElement(name = "vserver") public class VServerWithDetails extends VServerWithVNICs { - @XmlElementWrapper(name = "vdisks") - @XmlElement(name = "vdisk") - protected Set vdisks = new LinkedHashSet(); - protected Image image; + @XmlElementWrapper(name = "vdisks") + @XmlElement(name = "vdisk") + protected Set vdisks = new LinkedHashSet(); + protected Image image; - public Set getVdisks() { - return vdisks == null ? ImmutableSet. of() : ImmutableSet - .copyOf(vdisks); - } + public Set getVdisks() { + return vdisks == null ? ImmutableSet. of() : ImmutableSet + .copyOf(vdisks); + } - public Image getImage() { - return image; - } + public Image getImage() { + return image; + } - @Override - public String toString() { - return Objects.toStringHelper(this).omitNullValues().add("id", id) - .add("name", name).add("type", type).add("creator", creator) - .add("diskimageId", diskimageId).add("vdisks", vdisks) - .add("vnics", vnics).add("image", image).toString(); - } + @Override + public String toString() { + return Objects.toStringHelper(this).omitNullValues().add("id", id) + .add("name", name).add("type", type).add("creator", creator) + .add("diskimageId", diskimageId).add("vdisks", vdisks) + .add("vnics", vnics).add("image", image).toString(); + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/VServerWithVNICs.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/VServerWithVNICs.java index 3117241320..8e46a1de6a 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/VServerWithVNICs.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/VServerWithVNICs.java @@ -11,19 +11,19 @@ import com.google.common.collect.ImmutableSet; public class VServerWithVNICs extends VServer { - @XmlElementWrapper(name = "vnics") - @XmlElement(name = "vnic") - protected Set vnics = new LinkedHashSet(); + @XmlElementWrapper(name = "vnics") + @XmlElement(name = "vnic") + protected Set vnics = new LinkedHashSet(); - public Set getVnics() { - return vnics == null ? ImmutableSet. of() : ImmutableSet - .copyOf(vnics); - } + public Set getVnics() { + return vnics == null ? ImmutableSet. of() : ImmutableSet + .copyOf(vnics); + } - @Override - public String toString() { - return Objects.toStringHelper(this).omitNullValues().add("id", id) - .add("name", name).add("type", type).add("creator", creator) - .add("diskimageId", diskimageId).add("vnics", vnics).toString(); - } + @Override + public String toString() { + return Objects.toStringHelper(this).omitNullValues().add("id", id) + .add("name", name).add("type", type).add("creator", creator) + .add("diskimageId", diskimageId).add("vnics", vnics).toString(); + } } \ No newline at end of file diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/VSystem.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/VSystem.java index ae86034ce3..30f51de348 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/VSystem.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/VSystem.java @@ -28,57 +28,57 @@ import com.google.common.base.Objects; * @author Dies Koper */ public class VSystem { - @XmlElement(name = "vsysId") - protected String id; - @XmlElement(name = "vsysName") - protected String name; - protected String creator; - @XmlElement(name = "baseDescriptor") - protected String template; - protected String description; + @XmlElement(name = "vsysId") + protected String id; + @XmlElement(name = "vsysName") + protected String name; + protected String creator; + @XmlElement(name = "baseDescriptor") + protected String template; + protected String description; - public String getId() { - return id; - } + public String getId() { + return id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public String getCreator() { - return creator; - } + public String getCreator() { + return creator; + } - public String getTemplate() { - return template; - } + public String getTemplate() { + return template; + } - public String getDescription() { - return description; - } + public String getDescription() { + return description; + } - @Override - public int hashCode() { - return Objects.hashCode(id); - } + @Override + public int hashCode() { + return Objects.hashCode(id); + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - VSystem that = VSystem.class.cast(obj); - return Objects.equal(this.id, that.id); - } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + VSystem that = VSystem.class.cast(obj); + return Objects.equal(this.id, that.id); + } - @Override - public String toString() { - return Objects.toStringHelper(this).omitNullValues().add("id", id) - .add("name", name).add("creator", creator) - .add("template", template).add("description", description) - .toString(); - } + @Override + public String toString() { + return Objects.toStringHelper(this).omitNullValues().add("id", id) + .add("name", name).add("creator", creator) + .add("template", template).add("description", description) + .toString(); + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/VSystemDescriptor.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/VSystemDescriptor.java index 46f448ab9d..31a7a7e2f2 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/VSystemDescriptor.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/VSystemDescriptor.java @@ -34,71 +34,71 @@ import com.google.common.collect.ImmutableSet; */ @XmlRootElement(name = "vsysdescriptor") public class VSystemDescriptor { - @XmlElement(name = "vsysdescriptorId") - private String id; + @XmlElement(name = "vsysdescriptorId") + private String id; - @XmlElement(name = "vsysdescriptorName") - private String name; + @XmlElement(name = "vsysdescriptorName") + private String name; - private String creatorName; + private String creatorName; - private String registrant; + private String registrant; - private String description; + private String description; - private String keyword; + private String keyword; - @XmlElementWrapper(name = "vservers") - @XmlElement(name = "vserver") - private Set servers = new LinkedHashSet(); + @XmlElementWrapper(name = "vservers") + @XmlElement(name = "vserver") + private Set servers = new LinkedHashSet(); - /** - * @return the id - */ - public String getId() { - return id; - } + /** + * @return the id + */ + public String getId() { + return id; + } - /** - * @return the name - */ - public String getName() { - return name; - } + /** + * @return the name + */ + public String getName() { + return name; + } - /** - * @return the creatorName - */ - public String getCreatorName() { - return creatorName; - } + /** + * @return the creatorName + */ + public String getCreatorName() { + return creatorName; + } - /** - * @return the registrant - */ - public String getRegistrant() { - return registrant; - } + /** + * @return the registrant + */ + public String getRegistrant() { + return registrant; + } - /** - * @return the description - */ - public String getDescription() { - return description; - } + /** + * @return the description + */ + public String getDescription() { + return description; + } - /** - * @return the keyword - */ - public String getKeyword() { - return keyword; - } + /** + * @return the keyword + */ + public String getKeyword() { + return keyword; + } - /** - * @return the servers - */ - public Set getServers() { - return servers == null ? ImmutableSet. of() - : ImmutableSet.copyOf(servers); - } + /** + * @return the servers + */ + public Set getServers() { + return servers == null ? ImmutableSet. of() + : ImmutableSet.copyOf(servers); + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/VSystemStatus.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/VSystemStatus.java index 58e6e7a048..1668b291e3 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/VSystemStatus.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/VSystemStatus.java @@ -18,12 +18,12 @@ */ package org.jclouds.fujitsu.fgcp.domain; +import static com.google.common.base.Preconditions.checkNotNull; + import javax.xml.bind.annotation.XmlRootElement; import com.google.common.base.CaseFormat; -import static com.google.common.base.Preconditions.checkNotNull; - /** * Possible statuses of a virtual system. * @@ -31,24 +31,24 @@ import static com.google.common.base.Preconditions.checkNotNull; */ @XmlRootElement(name = "vsysStatus") public enum VSystemStatus { - NORMAL, RECONFIG_ING, DEPLOYING, ERROR, UNRECOGNIZED; + NORMAL, RECONFIG_ING, DEPLOYING, ERROR, UNRECOGNIZED; - public String value() { - return (CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name())); - } + public String value() { + return (CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, name())); + } - @Override - public String toString() { - return value(); - } + @Override + public String toString() { + return value(); + } - public static VSystemStatus fromValue(String status) { - try { - return valueOf(CaseFormat.UPPER_CAMEL - .to(CaseFormat.UPPER_UNDERSCORE, - checkNotNull(status, "status"))); - } catch (IllegalArgumentException e) { - return UNRECOGNIZED; - } - } + public static VSystemStatus fromValue(String status) { + try { + return valueOf(CaseFormat.UPPER_CAMEL + .to(CaseFormat.UPPER_UNDERSCORE, + checkNotNull(status, "status"))); + } catch (IllegalArgumentException e) { + return UNRECOGNIZED; + } + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/VSystemWithDetails.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/VSystemWithDetails.java index 16839889a7..7ae51fd203 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/VSystemWithDetails.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/VSystemWithDetails.java @@ -36,45 +36,45 @@ import com.google.common.collect.ImmutableSet; */ @XmlRootElement(name = "vsys") public class VSystemWithDetails extends VSystem { - @XmlElementWrapper(name = "vservers") - @XmlElement(name = "vserver") - private Set servers = new LinkedHashSet(); - @XmlElementWrapper(name = "vdisks") - @XmlElement(name = "vdisk") - private Set disks = new LinkedHashSet(); - @XmlElementWrapper(name = "publicips") - @XmlElement(name = "publicip") - private Set publicips = new LinkedHashSet(); - @XmlElementWrapper(name = "vnets") - @XmlElement(name = "vnet") - private Set networks = new LinkedHashSet(); + @XmlElementWrapper(name = "vservers") + @XmlElement(name = "vserver") + private Set servers = new LinkedHashSet(); + @XmlElementWrapper(name = "vdisks") + @XmlElement(name = "vdisk") + private Set disks = new LinkedHashSet(); + @XmlElementWrapper(name = "publicips") + @XmlElement(name = "publicip") + private Set publicips = new LinkedHashSet(); + @XmlElementWrapper(name = "vnets") + @XmlElement(name = "vnet") + private Set networks = new LinkedHashSet(); - public Set getServers() { - return servers == null ? ImmutableSet. of() : ImmutableSet - .copyOf(servers); - } + public Set getServers() { + return servers == null ? ImmutableSet. of() : ImmutableSet + .copyOf(servers); + } - public Set getDisks() { - return disks == null ? ImmutableSet. of() : ImmutableSet - .copyOf(disks); - } + public Set getDisks() { + return disks == null ? ImmutableSet. of() : ImmutableSet + .copyOf(disks); + } - public Set getPublicips() { - return publicips == null ? ImmutableSet. of() : ImmutableSet - .copyOf(publicips); - } + public Set getPublicips() { + return publicips == null ? ImmutableSet. of() : ImmutableSet + .copyOf(publicips); + } - public Set getNetworks() { - return networks == null ? ImmutableSet. of() : ImmutableSet - .copyOf(networks); - } + public Set getNetworks() { + return networks == null ? ImmutableSet. of() : ImmutableSet + .copyOf(networks); + } - @Override - public String toString() { - return Objects.toStringHelper(this).omitNullValues().add("id", id) - .add("name", name).add("creator", creator) - .add("template", template).add("description", description) - .add("disks", disks).add("networks", networks) - .add("publicips", publicips).add("servers", servers).toString(); - } + @Override + public String toString() { + return Objects.toStringHelper(this).omitNullValues().add("id", id) + .add("name", name).add("creator", creator) + .add("template", template).add("description", description) + .add("disks", disks).add("networks", networks) + .add("publicips", publicips).add("servers", servers).toString(); + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/package-info.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/package-info.java index 4f79fc1182..4c2494a2a8 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/package-info.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/domain/package-info.java @@ -20,7 +20,7 @@ @XmlAccessorType(XmlAccessType.FIELD) package org.jclouds.fujitsu.fgcp.domain; -import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlSchema; diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/filters/RequestAuthenticator.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/filters/RequestAuthenticator.java index 9fecf69ca3..c155d67193 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/filters/RequestAuthenticator.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/filters/RequestAuthenticator.java @@ -20,13 +20,13 @@ package org.jclouds.fujitsu.fgcp.filters; import static com.google.common.base.Preconditions.checkNotNull; -import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.Signature; +import java.security.SignatureException; import java.security.UnrecoverableKeyException; import java.util.Calendar; import java.util.Locale; @@ -42,7 +42,6 @@ import javax.ws.rs.core.MediaType; import javax.ws.rs.core.UriBuilder; import org.jclouds.Constants; -import org.jclouds.crypto.CryptoStreams; import org.jclouds.date.TimeStamp; import org.jclouds.encryption.internal.Base64; import org.jclouds.fujitsu.fgcp.reference.RequestParameters; @@ -58,6 +57,7 @@ import org.jclouds.rest.annotations.ApiVersion; import org.jclouds.rest.annotations.Credential; import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Charsets; import com.google.common.collect.Multimap; /** @@ -69,174 +69,168 @@ import com.google.common.collect.Multimap; @Singleton public class RequestAuthenticator implements HttpRequestFilter, RequestSigner { - @Resource - @Named(Constants.LOGGER_SIGNATURE) - private Logger signatureLog = Logger.NULL; + @Resource + @Named(Constants.LOGGER_SIGNATURE) + private Logger signatureLog = Logger.NULL; - final Provider calendarProvider; - final Signature signer; - final Provider builder; - final String apiVersion; + final Provider calendarProvider; + final Signature signer; + final Provider builder; + final String apiVersion; - public String signatureVersion = "1.0"; - public String signatureMethod = "SHA1withRSA"; + public String signatureVersion = "1.0"; + public String signatureMethod = "SHA1withRSA"; - private HttpUtils utils; + private HttpUtils utils; - @Inject - public RequestAuthenticator(@TimeStamp Provider calendarProvider, - Provider keyStoreProvider, - @Credential String keyPassword, Provider builder, - HttpUtils utils, SignatureWire signatureWire, - @ApiVersion String apiVersion) throws NoSuchAlgorithmException, - InvalidKeyException, KeyStoreException, UnrecoverableKeyException { - this.calendarProvider = checkNotNull(calendarProvider); - this.builder = checkNotNull(builder); - this.utils = checkNotNull(utils, "utils"); - this.apiVersion = checkNotNull(apiVersion, "apiVersion"); + @Inject + public RequestAuthenticator(@TimeStamp Provider calendarProvider, + Provider keyStoreProvider, + @Credential String keyPassword, Provider builder, + HttpUtils utils, SignatureWire signatureWire, + @ApiVersion String apiVersion) throws NoSuchAlgorithmException, + InvalidKeyException, KeyStoreException, UnrecoverableKeyException { + this.calendarProvider = checkNotNull(calendarProvider); + this.builder = checkNotNull(builder); + this.utils = checkNotNull(utils, "utils"); + this.apiVersion = checkNotNull(apiVersion, "apiVersion"); - signer = Signature.getInstance(signatureMethod); + signer = Signature.getInstance(signatureMethod); - KeyStore keyStore = checkNotNull(keyStoreProvider).get(); - String alias = keyStore.aliases().nextElement(); // there should be only - // one private key - PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, - keyPassword.toCharArray()); + KeyStore keyStore = checkNotNull(keyStoreProvider).get(); + String alias = keyStore.aliases().nextElement(); // there should be only + // one private key + PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, + keyPassword.toCharArray()); - signer.initSign(privateKey); - } + signer.initSign(privateKey); + } - public HttpRequest filter(HttpRequest request) throws HttpException { - checkNotNull(request, "request must be present"); + public HttpRequest filter(HttpRequest request) throws HttpException { + checkNotNull(request, "request must be present"); - utils.logRequest(signatureLog, request, ">>"); + utils.logRequest(signatureLog, request, ">>"); - // create accesskeyid - String accessKeyId = createStringToSign(request); - String signature = sign(accessKeyId); + // create accesskeyid + String accessKeyId = createStringToSign(request); + String signature = sign(accessKeyId); - // leaving this in for now for reference in case I need it for multipart - // POSTs - // add parameters. Note that in case of a GET, url escaping is required - /* - * Multimap decodedParams = null; if - * (HttpMethod.GET.equals(request.getMethod())) { decodedParams = - * ModifyRequest.parseQueryToMap(request.getEndpoint().getRawQuery()); - * - * } else if (HttpMethod.POST.equals(request.getMethod())) { - * decodedParams = - * ModifyRequest.parseQueryToMap(request.getPayload().getRawContent() - * .toString()); } - * - * checkNotNull(decodedParams, "no query params found"); - * System.out.println("filter: request params before: " + - * decodedParams.toString()); addAuthenticationParams(decodedParams, - * accessKeyId, signature); addLocaleParam(decodedParams); - * System.out.println("filter: request params after : " + - * decodedParams.toString()); if (signatureWire.enabled()) - * signatureWire.output(decodedParams); - * - * - * request = setPayload(request, decodedParams); - */ - // only "en" and "ja" are allowed - String lang = Locale.JAPANESE.getLanguage().equals( - Locale.getDefault().getLanguage()) ? Locale.JAPANESE - .getLanguage() : Locale.ENGLISH.getLanguage(); + // leaving this in for now for reference in case I need it for multipart + // POSTs + // add parameters. Note that in case of a GET, url escaping is required + /* + * Multimap decodedParams = null; if + * (HttpMethod.GET.equals(request.getMethod())) { decodedParams = + * ModifyRequest.parseQueryToMap(request.getEndpoint().getRawQuery()); + * + * } else if (HttpMethod.POST.equals(request.getMethod())) { + * decodedParams = + * ModifyRequest.parseQueryToMap(request.getPayload().getRawContent() + * .toString()); } + * + * checkNotNull(decodedParams, "no query params found"); + * System.out.println("filter: request params before: " + + * decodedParams.toString()); addAuthenticationParams(decodedParams, + * accessKeyId, signature); addLocaleParam(decodedParams); + * System.out.println("filter: request params after : " + + * decodedParams.toString()); if (signatureWire.enabled()) + * signatureWire.output(decodedParams); + * + * + * request = setPayload(request, decodedParams); + */ + // only "en" and "ja" are allowed + String lang = Locale.JAPANESE.getLanguage().equals( + Locale.getDefault().getLanguage()) ? Locale.JAPANESE + .getLanguage() : Locale.ENGLISH.getLanguage(); - if (HttpMethod.GET.equals(request.getMethod())) { - Multimap decodedParams = Queries - .parseQueryToMap(request.getEndpoint().getRawQuery()); + if (HttpMethod.GET.equals(request.getMethod())) { + Multimap decodedParams = Queries + .parseQueryToMap(request.getEndpoint().getRawQuery()); - if (!decodedParams.containsKey(RequestParameters.VERSION)) { - decodedParams.put(RequestParameters.VERSION, apiVersion); - } - decodedParams.put(RequestParameters.LOCALE, lang); - decodedParams.put(RequestParameters.ACCESS_KEY_ID, accessKeyId); - decodedParams.put(RequestParameters.SIGNATURE, signature); - request = request.toBuilder().replaceQueryParams(decodedParams) - .build(); - } else { + if (!decodedParams.containsKey(RequestParameters.VERSION)) { + decodedParams.put(RequestParameters.VERSION, apiVersion); + } + decodedParams.put(RequestParameters.LOCALE, lang); + decodedParams.put(RequestParameters.ACCESS_KEY_ID, accessKeyId); + decodedParams.put(RequestParameters.SIGNATURE, signature); + request = request.toBuilder().replaceQueryParams(decodedParams) + .build(); + } else { - String payload = request.getPayload().getRawContent().toString(); - payload = createXmlElementWithValue(payload, - RequestParameters.VERSION, apiVersion); - payload = createXmlElementWithValue(payload, - RequestParameters.LOCALE, lang); - payload = createXmlElementWithValue(payload, - RequestParameters.ACCESS_KEY_ID, accessKeyId); - payload = createXmlElementWithValue(payload, - RequestParameters.SIGNATURE, signature); + String payload = request.getPayload().getRawContent().toString(); + payload = createXmlElementWithValue(payload, + RequestParameters.VERSION, apiVersion); + payload = createXmlElementWithValue(payload, + RequestParameters.LOCALE, lang); + payload = createXmlElementWithValue(payload, + RequestParameters.ACCESS_KEY_ID, accessKeyId); + payload = createXmlElementWithValue(payload, + RequestParameters.SIGNATURE, signature); - // ensure there are no other query params left - request.setPayload(payload); - request.getPayload().getContentMetadata() - .setContentType(MediaType.TEXT_XML); - } + // ensure there are no other query params left + request.setPayload(payload); + request.getPayload().getContentMetadata() + .setContentType(MediaType.TEXT_XML); + } - // may need to do this elsewhere (see ConvertToGaeRequest) - HttpRequest filteredRequest = request.toBuilder() - .replaceHeader(HttpHeaders.USER_AGENT, "OViSS-API-CLIENT") - .build(); + // may need to do this elsewhere (see ConvertToGaeRequest) + HttpRequest filteredRequest = request.toBuilder() + .replaceHeader(HttpHeaders.USER_AGENT, "OViSS-API-CLIENT") + .build(); - utils.logRequest(signatureLog, filteredRequest, ">>->"); + utils.logRequest(signatureLog, filteredRequest, ">>->"); - return filteredRequest; - } + return filteredRequest; + } - String createXmlElementWithValue(String payload, String tag, String value) { - String startTag = String.format("<%s>", tag); - String endTag = String.format("", tag); + String createXmlElementWithValue(String payload, String tag, String value) { + String startTag = String.format("<%s>", tag); + String endTag = String.format("", tag); - return payload.replace(startTag + endTag, startTag + value + endTag); - } + return payload.replace(startTag + endTag, startTag + value + endTag); + } - /* - * HttpRequest setPayload(HttpRequest request, Multimap - * decodedParams) { - * request.setPayload(ModifyRequest.makeQueryLine(decodedParams, null)); // - * request.getPayload().getContentMetadata().setContentType( - * "application/x-www-form-urlencoded"); return request; } - */ + /* + * HttpRequest setPayload(HttpRequest request, Multimap + * decodedParams) { + * request.setPayload(ModifyRequest.makeQueryLine(decodedParams, null)); // + * request.getPayload().getContentMetadata().setContentType( + * "application/x-www-form-urlencoded"); return request; } + */ - @VisibleForTesting - public String sign(String stringToSign) { - String signed; + @VisibleForTesting + public String sign(String stringToSign) { + String signed; - try { - signer.update(stringToSign.getBytes("UTF-8")); - signed = Base64.encodeBytes(signer.sign()).replace("\n", "\r\n"); -// signed = CryptoStreams.base64(signer.sign()); - } catch (Exception e) { - throw new HttpException("error signing request", e); - } - // if (signatureWire.enabled()) - // signatureWire.input(Strings2.toInputStream(signed)); + try { + signer.update(stringToSign.getBytes(Charsets.UTF_8)); + signed = Base64.encodeBytes(signer.sign()).replace("\n", "\r\n"); +// signed = CryptoStreams.base64(signer.sign()); + } catch (SignatureException e) { + throw new HttpException("error signing request", e); + } + // if (signatureWire.enabled()) + // signatureWire.input(Strings2.toInputStream(signed)); - return signed; - } + return signed; + } - @VisibleForTesting - public String generateAccessKeyId() { - Calendar cal = calendarProvider.get(); - String timezone = cal.getTimeZone().getDisplayName(Locale.ENGLISH); - String expires = String.valueOf(cal.getTime().getTime()); + @VisibleForTesting + public String generateAccessKeyId() { + Calendar cal = calendarProvider.get(); + String timezone = cal.getTimeZone().getDisplayName(Locale.ENGLISH); + String expires = String.valueOf(cal.getTime().getTime()); - String signatureData = String.format("%s&%s&%s&%s", timezone, expires, - signatureVersion, signatureMethod); - try { - String accessKeyId = Base64.encodeBytes(signatureData.getBytes("UTF-8")); - return accessKeyId.replace("\n", "\r\n"); -// return CryptoStreams.base64(signatureData.getBytes("UTF-8")).; - } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e); // should never happen as - // signatureData contains only ASCII - } - } + String signatureData = String.format("%s&%s&%s&%s", timezone, expires, + signatureVersion, signatureMethod); + String accessKeyId = Base64.encodeBytes(signatureData.getBytes(Charsets.UTF_8)); + return accessKeyId.replace("\n", "\r\n"); + } - @Override - public String createStringToSign(HttpRequest input) { - return generateAccessKeyId(); - } + @Override + public String createStringToSign(HttpRequest input) { + return generateAccessKeyId(); + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/handlers/FGCPRetryIfNotProxyAuthenticationFailureHandler.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/handlers/FGCPRetryIfNotProxyAuthenticationFailureHandler.java index 0104aaf61c..9d4c05de9c 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/handlers/FGCPRetryIfNotProxyAuthenticationFailureHandler.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/handlers/FGCPRetryIfNotProxyAuthenticationFailureHandler.java @@ -18,13 +18,14 @@ */ package org.jclouds.fujitsu.fgcp.handlers; -import com.google.inject.Singleton; +import javax.annotation.Resource; + import org.jclouds.http.HttpCommand; import org.jclouds.http.HttpResponse; import org.jclouds.http.HttpRetryHandler; import org.jclouds.logging.Logger; -import javax.annotation.Resource; +import com.google.inject.Singleton; /** * Created by IntelliJ IDEA. @@ -33,15 +34,15 @@ import javax.annotation.Resource; */ @Singleton public class FGCPRetryIfNotProxyAuthenticationFailureHandler implements - HttpRetryHandler { - @Resource - protected Logger logger = Logger.NULL; + HttpRetryHandler { + @Resource + protected Logger logger = Logger.NULL; - @Override - public boolean shouldRetryRequest(HttpCommand command, HttpResponse response) { - int statusCode = response.getStatusCode(); - System.out.println("Response status code: " + statusCode); - logger.error("StatusCode", statusCode); - return true; - } + @Override + public boolean shouldRetryRequest(HttpCommand command, HttpResponse response) { + int statusCode = response.getStatusCode(); + System.out.println("Response status code: " + statusCode); + logger.error("StatusCode", statusCode); + return true; + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/http/SSLContextWithKeysSupplier.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/http/SSLContextWithKeysSupplier.java index c0e20196a5..38974e348f 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/http/SSLContextWithKeysSupplier.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/http/SSLContextWithKeysSupplier.java @@ -45,27 +45,27 @@ import com.google.common.base.Supplier; */ @Singleton public class SSLContextWithKeysSupplier implements Supplier { - private SSLContext sc; + private SSLContext sc; - @Inject - SSLContextWithKeysSupplier(KeyStore keyStore, - @Credential String keyStorePassword, HttpUtils utils, - TrustAllCerts trustAllCerts) throws NoSuchAlgorithmException, - KeyStoreException, UnrecoverableKeyException, - KeyManagementException { + @Inject + SSLContextWithKeysSupplier(KeyStore keyStore, + @Credential String keyStorePassword, HttpUtils utils, + TrustAllCerts trustAllCerts) throws NoSuchAlgorithmException, + KeyStoreException, UnrecoverableKeyException, + KeyManagementException { - TrustManager[] trustManager = null; - if (utils.trustAllCerts()) { - trustManager = new TrustManager[] { trustAllCerts }; - } - KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); - kmf.init(keyStore, keyStorePassword.toCharArray()); - sc = SSLContext.getInstance("TLS"); - sc.init(kmf.getKeyManagers(), trustManager, new SecureRandom()); - } + TrustManager[] trustManager = null; + if (utils.trustAllCerts()) { + trustManager = new TrustManager[] { trustAllCerts }; + } + KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); + kmf.init(keyStore, keyStorePassword.toCharArray()); + sc = SSLContext.getInstance("TLS"); + sc.init(kmf.getKeyManagers(), trustManager, new SecureRandom()); + } - @Override - public SSLContext get() { - return sc; - } + @Override + public SSLContext get() { + return sc; + } } \ No newline at end of file diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/location/SystemAndNetworkSegmentToLocationSupplier.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/location/SystemAndNetworkSegmentToLocationSupplier.java index 569d3aedb8..476db4cd6c 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/location/SystemAndNetworkSegmentToLocationSupplier.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/location/SystemAndNetworkSegmentToLocationSupplier.java @@ -66,55 +66,55 @@ import com.google.common.util.concurrent.ListenableFuture; */ @Singleton public class SystemAndNetworkSegmentToLocationSupplier implements - LocationsSupplier { + LocationsSupplier { - private final RegionToProviderOrJustProvider regionProvider; - private FGCPAsyncApi api; + private final RegionToProviderOrJustProvider regionProvider; + private FGCPAsyncApi api; - @Inject - SystemAndNetworkSegmentToLocationSupplier( - RegionToProviderOrJustProvider regionProvider, FGCPAsyncApi api) { - this.regionProvider = checkNotNull(regionProvider, - "regionToProviderOrJustProvider"); - this.api = checkNotNull(api, "api"); - } + @Inject + SystemAndNetworkSegmentToLocationSupplier( + RegionToProviderOrJustProvider regionProvider, FGCPAsyncApi api) { + this.regionProvider = checkNotNull(regionProvider, + "regionToProviderOrJustProvider"); + this.api = checkNotNull(api, "api"); + } - @Override - public Set get() { - Builder locations = ImmutableSet.builder(); - try { - List> futures = new ArrayList>(); - for (VSystem system : api.getVirtualDCApi().listVirtualSystems() - .get()) { + @Override + public Set get() { + Builder locations = ImmutableSet.builder(); + try { + List> futures = new ArrayList>(); + for (VSystem system : api.getVirtualDCApi().listVirtualSystems() + .get()) { - futures.add(api.getVirtualSystemApi() - .getDetails(system.getId())); + futures.add(api.getVirtualSystemApi() + .getDetails(system.getId())); + } + for (VSystemWithDetails system : Futures.successfulAsList(futures) + .get()) { + + Location systemLocation = new LocationBuilder() + .scope(LocationScope.SYSTEM) + .parent(Iterables.getOnlyElement(regionProvider.get())) + .description(system.getName()).id(system.getId()) + .build(); + + for (VNet net : system.getNetworks()) { + + locations.add(new LocationBuilder() + .scope(LocationScope.NETWORK) + .parent(systemLocation) + .description( + net.getNetworkId().replaceFirst( + ".+(DMZ|SECURE.)", "\\1")) + .id(net.getNetworkId()).build()); } - for (VSystemWithDetails system : Futures.successfulAsList(futures) - .get()) { - - Location systemLocation = new LocationBuilder() - .scope(LocationScope.SYSTEM) - .parent(Iterables.getOnlyElement(regionProvider.get())) - .description(system.getName()).id(system.getId()) - .build(); - - for (VNet net : system.getNetworks()) { - - locations.add(new LocationBuilder() - .scope(LocationScope.NETWORK) - .parent(systemLocation) - .description( - net.getNetworkId().replaceFirst( - ".+(DMZ|SECURE.)", "\\1")) - .id(net.getNetworkId()).build()); - } - } - } catch (InterruptedException e) { - throw Throwables.propagate(e); - } catch (ExecutionException e) { - throw Throwables.propagate(e); - } - return locations.build(); - } + } + } catch (InterruptedException e) { + throw Throwables.propagate(e); + } catch (ExecutionException e) { + throw Throwables.propagate(e); + } + return locations.build(); + } } \ No newline at end of file diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/reference/RequestParameters.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/reference/RequestParameters.java index d4870c540d..784773cb10 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/reference/RequestParameters.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/reference/RequestParameters.java @@ -25,57 +25,57 @@ package org.jclouds.fujitsu.fgcp.reference; */ public interface RequestParameters { - /** - * Indicates the action to perform. Example: ListVSYS - */ - public static final String ACTION = "Action"; + /** + * Indicates the action to perform. Example: ListVSYS + */ + public static final String ACTION = "Action"; - /** - * The API version to use. Example: 2011-01-31 - */ - public static final String VERSION = "Version"; + /** + * The API version to use. Example: 2011-01-31 + */ + public static final String VERSION = "Version"; - /** - * The locale to use. Example: en - */ - public static final String LOCALE = "Locale"; + /** + * The locale to use. Example: en + */ + public static final String LOCALE = "Locale"; - /** - * The Access Key ID for the request sender. This identifies the account - * which will be charged for usage of the service. The account with which - * the Access Key ID is associated must be signed up for FGCP, or requests - * will not be accepted. AKIADQKE4SARGYLE - */ - public static final String ACCESS_KEY_ID = "AccessKeyId"; + /** + * The Access Key ID for the request sender. This identifies the account + * which will be charged for usage of the service. The account with which + * the Access Key ID is associated must be signed up for FGCP, or requests + * will not be accepted. AKIADQKE4SARGYLE + */ + public static final String ACCESS_KEY_ID = "AccessKeyId"; - /** - * The date and time at which the request is signed, in the format - * YYYY-MM-DDThh:mm:ssZ. For more information, go to ISO 8601. Example: - * 2006-07-07T15:04:56Z - */ - public static final String TIMESTAMP = "Timestamp"; + /** + * The date and time at which the request is signed, in the format + * YYYY-MM-DDThh:mm:ssZ. For more information, go to ISO 8601. Example: + * 2006-07-07T15:04:56Z + */ + public static final String TIMESTAMP = "Timestamp"; - /** - * The date and time at which the signer included in the request expires, in - * the format YYYY-MM-DDThh:mm:ssZ. Example: 2006-07-07T15:04:56Z - */ - public static final String EXPIRES = "Expires"; + /** + * The date and time at which the signer included in the request expires, in + * the format YYYY-MM-DDThh:mm:ssZ. Example: 2006-07-07T15:04:56Z + */ + public static final String EXPIRES = "Expires"; - /** - * The request signer. For more information, go to the Amazon Elastic - * Compute Cloud Developer Guide. Example: Qnpl4Qk/7tINHzfXCiT7VbBatDA= - */ - public static final String SIGNATURE = "Signature"; + /** + * The request signer. For more information, go to the Amazon Elastic + * Compute Cloud Developer Guide. Example: Qnpl4Qk/7tINHzfXCiT7VbBatDA= + */ + public static final String SIGNATURE = "Signature"; - /** - * The hash algorithm you use to create the request signer. Valid value: - * SHA1withRSA. - */ - public static final String SIGNATURE_METHOD = "SignatureMethod"; + /** + * The hash algorithm you use to create the request signer. Valid value: + * SHA1withRSA. + */ + public static final String SIGNATURE_METHOD = "SignatureMethod"; - /** - * The signer version you use to sign the request. Set this value to 1.0. - * - */ - public static final String SIGNATURE_VERSION = "SignatureVersion"; + /** + * The signer version you use to sign the request. Set this value to 1.0. + * + */ + public static final String SIGNATURE_VERSION = "SignatureVersion"; } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/AdditionalDiskApi.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/AdditionalDiskApi.java index 2b4cbb658a..ec0e455e54 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/AdditionalDiskApi.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/AdditionalDiskApi.java @@ -18,7 +18,6 @@ */ package org.jclouds.fujitsu.fgcp.services; -import java.util.Set; import java.util.concurrent.TimeUnit; import org.jclouds.concurrent.Timeout; @@ -33,21 +32,21 @@ import org.jclouds.fujitsu.fgcp.domain.VDiskStatus; @Timeout(duration = 60, timeUnit = TimeUnit.SECONDS) public interface AdditionalDiskApi { - VDiskStatus getStatus(String id); + VDiskStatus getStatus(String id); - VDisk get(String id); + VDisk get(String id); - void update(String id, String name, String value); + void update(String id, String name, String value); - void backup(String id); + void backup(String id); - void restore(String systemId, String backupId); + void restore(String systemId, String backupId); - void destroy(String id); + void destroy(String id); - void detach(String diskId, String serverId); + void detach(String diskId, String serverId); - void destroyBackup(String sysId, String backupId); + void destroyBackup(String sysId, String backupId); - // Set<> listBackups(String sysId); + // Set<> listBackups(String sysId); } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/AdditionalDiskAsyncApi.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/AdditionalDiskAsyncApi.java index 440be5baf9..e3774855c4 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/AdditionalDiskAsyncApi.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/AdditionalDiskAsyncApi.java @@ -18,7 +18,6 @@ */ package org.jclouds.fujitsu.fgcp.services; -import java.util.Set; import java.util.concurrent.TimeUnit; import javax.ws.rs.Consumes; @@ -55,58 +54,58 @@ import com.google.common.util.concurrent.ListenableFuture; @Timeout(duration = 60, timeUnit = TimeUnit.SECONDS) public interface AdditionalDiskAsyncApi { - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "GetVDiskStatus") - @Transform(SingleElementResponseToElement.class) - ListenableFuture getStatus( - @BinderParam(BindAlsoToSystemId.class) @QueryParam("vdiskId") String id); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "GetVDiskStatus") + @Transform(SingleElementResponseToElement.class) + ListenableFuture getStatus( + @BinderParam(BindAlsoToSystemId.class) @QueryParam("vdiskId") String id); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "GetVDiskAttributes") - @Transform(SingleElementResponseToElement.class) - ListenableFuture get( - @BinderParam(BindAlsoToSystemId.class) @QueryParam("vdiskId") String id); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "GetVDiskAttributes") + @Transform(SingleElementResponseToElement.class) + ListenableFuture get( + @BinderParam(BindAlsoToSystemId.class) @QueryParam("vdiskId") String id); - @GET - @QueryParams(keys = "Action", values = "UpdateVDiskAttribute") - ListenableFuture update( - @BinderParam(BindAlsoToSystemId.class) @QueryParam("vdiskId") String id, - @QueryParam("attributeName") String name, - @QueryParam("attributeValue") String value); + @GET + @QueryParams(keys = "Action", values = "UpdateVDiskAttribute") + ListenableFuture update( + @BinderParam(BindAlsoToSystemId.class) @QueryParam("vdiskId") String id, + @QueryParam("attributeName") String name, + @QueryParam("attributeValue") String value); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "BackupVDisk") - ListenableFuture backup( - @BinderParam(BindAlsoToSystemId.class) @QueryParam("vdiskId") String id); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "BackupVDisk") + ListenableFuture backup( + @BinderParam(BindAlsoToSystemId.class) @QueryParam("vdiskId") String id); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "RestoreVDisk") - ListenableFuture restore(@QueryParam("vsysId") String systemId, - @QueryParam("backupId") String backupId); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "RestoreVDisk") + ListenableFuture restore(@QueryParam("vsysId") String systemId, + @QueryParam("backupId") String backupId); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "DestroyVDisk") - ListenableFuture destroy( - @BinderParam(BindAlsoToSystemId.class) @QueryParam("vdiskId") String id); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "DestroyVDisk") + ListenableFuture destroy( + @BinderParam(BindAlsoToSystemId.class) @QueryParam("vdiskId") String id); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "DetachVDisk") - ListenableFuture detach( - @BinderParam(BindAlsoToSystemId.class) @QueryParam("vdiskId") String diskId, - @QueryParam("vserverId") String serverId); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "DetachVDisk") + ListenableFuture detach( + @BinderParam(BindAlsoToSystemId.class) @QueryParam("vdiskId") String diskId, + @QueryParam("vserverId") String serverId); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "DestroyVDiskBackup") - ListenableFuture destroyBackup(@QueryParam("vsysId") String sysId, - @QueryParam("backupId") String backupId); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "DestroyVDiskBackup") + ListenableFuture destroyBackup(@QueryParam("vsysId") String sysId, + @QueryParam("backupId") String backupId); - // Set<> listBackups(String sysId); + // Set<> listBackups(String sysId); } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/BuiltinServerApi.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/BuiltinServerApi.java index 274b1fbce3..82bb512cb1 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/BuiltinServerApi.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/BuiltinServerApi.java @@ -36,38 +36,38 @@ import org.jclouds.fujitsu.fgcp.domain.BuiltinServerStatus; @Timeout(duration = 60, timeUnit = TimeUnit.SECONDS) public interface BuiltinServerApi { - void start(String id); + void start(String id); - void stop(String id); + void stop(String id); - void destroy(String id); + void destroy(String id); - void backup(String id); + void backup(String id); - void restore(String id, String backupId); + void restore(String id, String backupId); - Set listBackups(String id); + Set listBackups(String id); - void destroyBackup(String id, String backupId); + void destroyBackup(String id, String backupId); - BuiltinServer get(String id); + BuiltinServer get(String id); - void update(String id, String name, String value); + void update(String id, String name, String value); - BuiltinServerStatus getStatus(String id); + BuiltinServerStatus getStatus(String id); - BuiltinServer getConfiguration(String id, BuiltinServerConfiguration configuration); + BuiltinServer getConfiguration(String id, BuiltinServerConfiguration configuration); - // BuiltinServer getConfiguration(String id, BuiltinServerConfiguration configuration, ConfigurationRequest request); - // void updateConfiguration(String id, xml?); - /* + // BuiltinServer getConfiguration(String id, BuiltinServerConfiguration configuration, ConfigurationRequest request); + // void updateConfiguration(String id, xml?); + /* getDNSConfiguration(String id) getNATConfiguration(String id) getPolicyConfiguration(String id) getLBConfiguration(String id) - * UpdateEFMConfiguration - BuiltinServer getConfiguration(String id, BuiltinServerConfiguration configuration); + * UpdateEFMConfiguration + BuiltinServer getConfiguration(String id, BuiltinServerConfiguration configuration); - */ + */ } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/BuiltinServerAsyncApi.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/BuiltinServerAsyncApi.java index 569577fc4d..b5b3bdcb19 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/BuiltinServerAsyncApi.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/BuiltinServerAsyncApi.java @@ -58,79 +58,79 @@ import com.google.common.util.concurrent.ListenableFuture; @Timeout(duration = 60, timeUnit = TimeUnit.SECONDS) public interface BuiltinServerAsyncApi { - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "StartEFM") - ListenableFuture start( - @BinderParam(BindAlsoToSystemId.class) @QueryParam("efmId") String id); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "StartEFM") + ListenableFuture start( + @BinderParam(BindAlsoToSystemId.class) @QueryParam("efmId") String id); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "StopEFM") - ListenableFuture stop( - @BinderParam(BindAlsoToSystemId.class) @QueryParam("efmId") String id); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "StopEFM") + ListenableFuture stop( + @BinderParam(BindAlsoToSystemId.class) @QueryParam("efmId") String id); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "DestroyEFM") - ListenableFuture destroy( - @BinderParam(BindAlsoToSystemId.class) @QueryParam("efmId") String id); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "DestroyEFM") + ListenableFuture destroy( + @BinderParam(BindAlsoToSystemId.class) @QueryParam("efmId") String id); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "BackupEFM") - ListenableFuture backup( - @BinderParam(BindAlsoToSystemId.class) @QueryParam("efmId") String id); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "BackupEFM") + ListenableFuture backup( + @BinderParam(BindAlsoToSystemId.class) @QueryParam("efmId") String id); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "RestoreEFM") - ListenableFuture restore( - @BinderParam(BindAlsoToSystemId.class) @QueryParam("efmId") String id, - @QueryParam("backupId") String backupId); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "RestoreEFM") + ListenableFuture restore( + @BinderParam(BindAlsoToSystemId.class) @QueryParam("efmId") String id, + @QueryParam("backupId") String backupId); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "ListEFMBackup") - ListenableFuture> listBackups( - @BinderParam(BindAlsoToSystemId.class) @QueryParam("efmId") String id); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "ListEFMBackup") + ListenableFuture> listBackups( + @BinderParam(BindAlsoToSystemId.class) @QueryParam("efmId") String id); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "DestroyEFMBackup") - ListenableFuture destroyBackup( - @BinderParam(BindAlsoToSystemId.class) @QueryParam("efmId") String id, - @QueryParam("backupId") String backupId); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "DestroyEFMBackup") + ListenableFuture destroyBackup( + @BinderParam(BindAlsoToSystemId.class) @QueryParam("efmId") String id, + @QueryParam("backupId") String backupId); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "GetEFMAttributes") - @Transform(SingleElementResponseToElement.class) - ListenableFuture get( - @BinderParam(BindAlsoToSystemId.class) @QueryParam("efmId") String id); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "GetEFMAttributes") + @Transform(SingleElementResponseToElement.class) + ListenableFuture get( + @BinderParam(BindAlsoToSystemId.class) @QueryParam("efmId") String id); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "UpdateEFMAttribute") - ListenableFuture update( - @BinderParam(BindAlsoToSystemId.class) @QueryParam("efmId") String id, - @QueryParam("attributeName") String name, - @QueryParam("attributeValue") String value); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "UpdateEFMAttribute") + ListenableFuture update( + @BinderParam(BindAlsoToSystemId.class) @QueryParam("efmId") String id, + @QueryParam("attributeName") String name, + @QueryParam("attributeValue") String value); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "GetEFMStatus") - @Transform(SingleElementResponseToElement.class) - ListenableFuture getStatus( - @BinderParam(BindAlsoToSystemId.class) @QueryParam("efmId") String id); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "GetEFMStatus") + @Transform(SingleElementResponseToElement.class) + ListenableFuture getStatus( + @BinderParam(BindAlsoToSystemId.class) @QueryParam("efmId") String id); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "GetEFMConfiguration") - @Transform(SingleElementResponseToElement.class) - ListenableFuture getConfiguration( - @BinderParam(BindAlsoToSystemId.class) @QueryParam("efmId") String id, - @QueryParam("configurationName") BuiltinServerConfiguration configuration); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "GetEFMConfiguration") + @Transform(SingleElementResponseToElement.class) + ListenableFuture getConfiguration( + @BinderParam(BindAlsoToSystemId.class) @QueryParam("efmId") String id, + @QueryParam("configurationName") BuiltinServerConfiguration configuration); // @POST // @JAXBResponseParser @@ -138,8 +138,8 @@ public interface BuiltinServerAsyncApi { // @Transform(SingleElementResponseToElement.class) // ListenableFuture> getUpdateDetails(String id); - // ListenableFuture - // updateConfiguration(@BinderParam(BindAlsoToSystemId.class) - // @QueryParam("efmId") String id, xml?); -// EFM_UPDATE, getUpdateStatus(String id); + // ListenableFuture + // updateConfiguration(@BinderParam(BindAlsoToSystemId.class) + // @QueryParam("efmId") String id, xml?); +// EFM_UPDATE, getUpdateStatus(String id); } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/DiskImageApi.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/DiskImageApi.java index 610e61dbeb..294d2827ef 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/DiskImageApi.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/DiskImageApi.java @@ -31,9 +31,9 @@ import org.jclouds.fujitsu.fgcp.domain.DiskImage; @Timeout(duration = 60, timeUnit = TimeUnit.SECONDS) public interface DiskImageApi { - DiskImage get(String id); + DiskImage get(String id); - void update(String diskImageId, String localeId, String name, String value); + void update(String diskImageId, String localeId, String name, String value); - void deregister(String id); + void deregister(String id); } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/DiskImageAsyncApi.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/DiskImageAsyncApi.java index 9b4d613f2f..112a24dd5e 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/DiskImageAsyncApi.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/DiskImageAsyncApi.java @@ -51,23 +51,23 @@ import com.google.common.util.concurrent.ListenableFuture; @Timeout(duration = 60, timeUnit = TimeUnit.SECONDS) public interface DiskImageAsyncApi { - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "GetDiskImageAttributes") - @Transform(SingleElementResponseToElement.class) - ListenableFuture get(@QueryParam("diskImageId") String id); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "GetDiskImageAttributes") + @Transform(SingleElementResponseToElement.class) + ListenableFuture get(@QueryParam("diskImageId") String id); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "UpdateDiskImageAttribute") - ListenableFuture update( - @QueryParam("diskImageId") String diskImageId, - @QueryParam("updateLcId") String localeId, - @QueryParam("attributeName") String name, - @QueryParam("attributeValue") String value); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "UpdateDiskImageAttribute") + ListenableFuture update( + @QueryParam("diskImageId") String diskImageId, + @QueryParam("updateLcId") String localeId, + @QueryParam("attributeName") String name, + @QueryParam("attributeValue") String value); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "UnregisterDiskImage") - ListenableFuture deregister(@QueryParam("diskImageId") String id); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "UnregisterDiskImage") + ListenableFuture deregister(@QueryParam("diskImageId") String id); } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/FirewallApi.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/FirewallApi.java index bfe54e95f7..bbb5067dd0 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/FirewallApi.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/FirewallApi.java @@ -32,6 +32,6 @@ import org.jclouds.fujitsu.fgcp.domain.Rule; @Timeout(duration = 60, timeUnit = TimeUnit.SECONDS) public interface FirewallApi extends BuiltinServerApi { - Set getNATConfiguration(String id); - + Set getNATConfiguration(String id); + } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/FirewallAsyncApi.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/FirewallAsyncApi.java index df06dc9d5f..597e15dd2a 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/FirewallAsyncApi.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/FirewallAsyncApi.java @@ -22,23 +22,15 @@ import java.util.Set; import java.util.concurrent.TimeUnit; import javax.ws.rs.Consumes; -import javax.ws.rs.GET; import javax.ws.rs.POST; -import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import org.jclouds.concurrent.Timeout; import org.jclouds.fujitsu.fgcp.FGCPAsyncApi; -import org.jclouds.fujitsu.fgcp.binders.BindAlsoToSystemId; import org.jclouds.fujitsu.fgcp.compute.functions.SingleElementResponseToElement; -import org.jclouds.fujitsu.fgcp.domain.BuiltinServer; -import org.jclouds.fujitsu.fgcp.domain.BuiltinServerBackup; -import org.jclouds.fujitsu.fgcp.domain.BuiltinServerConfiguration; -import org.jclouds.fujitsu.fgcp.domain.BuiltinServerStatus; import org.jclouds.fujitsu.fgcp.domain.Rule; import org.jclouds.fujitsu.fgcp.filters.RequestAuthenticator; import org.jclouds.fujitsu.fgcp.reference.RequestParameters; -import org.jclouds.rest.annotations.BinderParam; import org.jclouds.rest.annotations.JAXBResponseParser; import org.jclouds.rest.annotations.PayloadParams; import org.jclouds.rest.annotations.QueryParams; @@ -60,20 +52,20 @@ import com.google.common.util.concurrent.ListenableFuture; @Timeout(duration = 60, timeUnit = TimeUnit.SECONDS) public interface FirewallAsyncApi extends BuiltinServerAsyncApi { - @POST - @JAXBResponseParser - @QueryParams(keys = "Action", values = "GetEFMConfiguration") - @Transform(SingleElementResponseToElement.class) - ListenableFuture> getNATConfiguration(String id); + @POST + @JAXBResponseParser + @QueryParams(keys = "Action", values = "GetEFMConfiguration") + @Transform(SingleElementResponseToElement.class) + ListenableFuture> getNATConfiguration(String id); - /* - FW_NAT_RULE, getNATConfiguration(String id) + /* + FW_NAT_RULE, getNATConfiguration(String id) - FW_DNS, getDNSConfiguration(String id) - FW_POLICY, getPolicyConfiguration(String id) + FW_DNS, getDNSConfiguration(String id) + FW_POLICY, getPolicyConfiguration(String id) - FW_LOG, getFirewallLogs(String id); - FW_LIMIT_POLICY, + FW_LOG, getFirewallLogs(String id); + FW_LIMIT_POLICY, - */ + */ } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/LoadBalancerAsyncApi.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/LoadBalancerAsyncApi.java index a7a645201b..49871284bd 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/LoadBalancerAsyncApi.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/LoadBalancerAsyncApi.java @@ -18,32 +18,18 @@ */ package org.jclouds.fujitsu.fgcp.services; -import java.util.Set; import java.util.concurrent.TimeUnit; import javax.ws.rs.Consumes; -import javax.ws.rs.GET; -import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import org.jclouds.concurrent.Timeout; import org.jclouds.fujitsu.fgcp.FGCPAsyncApi; -import org.jclouds.fujitsu.fgcp.binders.BindAlsoToSystemId; -import org.jclouds.fujitsu.fgcp.compute.functions.SingleElementResponseToElement; -import org.jclouds.fujitsu.fgcp.domain.BuiltinServer; -import org.jclouds.fujitsu.fgcp.domain.BuiltinServerBackup; -import org.jclouds.fujitsu.fgcp.domain.BuiltinServerConfiguration; -import org.jclouds.fujitsu.fgcp.domain.BuiltinServerStatus; import org.jclouds.fujitsu.fgcp.filters.RequestAuthenticator; import org.jclouds.fujitsu.fgcp.reference.RequestParameters; -import org.jclouds.rest.annotations.BinderParam; -import org.jclouds.rest.annotations.JAXBResponseParser; import org.jclouds.rest.annotations.PayloadParams; import org.jclouds.rest.annotations.QueryParams; import org.jclouds.rest.annotations.RequestFilters; -import org.jclouds.rest.annotations.Transform; - -import com.google.common.util.concurrent.ListenableFuture; /** * Non-blocking API relating to a built-in server, also called extended function @@ -58,12 +44,12 @@ import com.google.common.util.concurrent.ListenableFuture; @Timeout(duration = 60, timeUnit = TimeUnit.SECONDS) public interface LoadBalancerAsyncApi extends BuiltinServerAsyncApi { - /* - SLB_RULE, getLBConfiguration(String id) - SLB_LOAD_STATISTICS, getLoadBalancerStats(String id) - SLB_ERROR_STATISTICS, getLoadBalancerErrorStats(String id) - SLB_CERTIFICATE_LIST, getLoadBalancerCerts(String id) - SLB_CONNECTION, getLoadBalancerConnection(String id) + /* + SLB_RULE, getLBConfiguration(String id) + SLB_LOAD_STATISTICS, getLoadBalancerStats(String id) + SLB_ERROR_STATISTICS, getLoadBalancerErrorStats(String id) + SLB_CERTIFICATE_LIST, getLoadBalancerCerts(String id) + SLB_CONNECTION, getLoadBalancerConnection(String id) - */ + */ } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/PublicIPAddressApi.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/PublicIPAddressApi.java index 9bb40355ac..21771d74d0 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/PublicIPAddressApi.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/PublicIPAddressApi.java @@ -32,13 +32,13 @@ import org.jclouds.fujitsu.fgcp.domain.PublicIPStatus; @Timeout(duration = 60, timeUnit = TimeUnit.SECONDS) public interface PublicIPAddressApi { - void attach(String systemId, String ip); + void attach(String systemId, String ip); - void detach(String systemId, String ip); + void detach(String systemId, String ip); - void free(String systemId, String ip); + void free(String systemId, String ip); - PublicIPStatus getStatus(String ip); + PublicIPStatus getStatus(String ip); - PublicIP get(String ip); + PublicIP get(String ip); } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/PublicIPAddressAsyncApi.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/PublicIPAddressAsyncApi.java index 0b50dc7fa5..5b26fa1cf0 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/PublicIPAddressAsyncApi.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/PublicIPAddressAsyncApi.java @@ -18,7 +18,6 @@ */ package org.jclouds.fujitsu.fgcp.services; -import java.util.Set; import java.util.concurrent.TimeUnit; import javax.ws.rs.Consumes; @@ -53,35 +52,35 @@ import com.google.common.util.concurrent.ListenableFuture; @Timeout(duration = 60, timeUnit = TimeUnit.SECONDS) public interface PublicIPAddressAsyncApi { - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "AttachPublicIP") - ListenableFuture attach(@QueryParam("vsysId") String systemId, - @QueryParam("publicIp") String ip); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "AttachPublicIP") + ListenableFuture attach(@QueryParam("vsysId") String systemId, + @QueryParam("publicIp") String ip); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "DetachPublicIP") - ListenableFuture detach(@QueryParam("vsysId") String systemId, - @QueryParam("publicIp") String ip); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "DetachPublicIP") + ListenableFuture detach(@QueryParam("vsysId") String systemId, + @QueryParam("publicIp") String ip); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "GetPublicIPStatus") - @Transform(SingleElementResponseToElement.class) - ListenableFuture getStatus( - @QueryParam("publicIp") String ip); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "GetPublicIPStatus") + @Transform(SingleElementResponseToElement.class) + ListenableFuture getStatus( + @QueryParam("publicIp") String ip); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "GetPublicIPAttributes") - @Transform(SingleElementResponseToElement.class) - ListenableFuture get(@QueryParam("publicIp") String ip); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "GetPublicIPAttributes") + @Transform(SingleElementResponseToElement.class) + ListenableFuture get(@QueryParam("publicIp") String ip); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "FreePublicIP") - ListenableFuture free(@QueryParam("vsysId") String systemId, - @QueryParam("publicIp") String ip); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "FreePublicIP") + ListenableFuture free(@QueryParam("vsysId") String systemId, + @QueryParam("publicIp") String ip); } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/SystemTemplateApi.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/SystemTemplateApi.java index e995a72de4..16bfde89d4 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/SystemTemplateApi.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/SystemTemplateApi.java @@ -32,12 +32,12 @@ import org.jclouds.fujitsu.fgcp.domain.VSystemDescriptor; @Timeout(duration = 60, timeUnit = TimeUnit.SECONDS) public interface SystemTemplateApi { - VSystemDescriptor get(String id); + VSystemDescriptor get(String id); - void update(String id, String localeId, String name, String value); + void update(String id, String localeId, String name, String value); - void deregister(String id); + void deregister(String id); - void deregisterPrivateTemplate(String id); + void deregisterPrivateTemplate(String id); } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/SystemTemplateAsyncApi.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/SystemTemplateAsyncApi.java index 74a93b2b3d..0deb371877 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/SystemTemplateAsyncApi.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/SystemTemplateAsyncApi.java @@ -52,30 +52,30 @@ import com.google.common.util.concurrent.ListenableFuture; @Timeout(duration = 60, timeUnit = TimeUnit.SECONDS) public interface SystemTemplateAsyncApi { - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "GetVSYSDescriptorConfiguration") - @Transform(SingleElementResponseToElement.class) - ListenableFuture get( - @QueryParam("vsysDescriptorId") String id); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "GetVSYSDescriptorConfiguration") + @Transform(SingleElementResponseToElement.class) + ListenableFuture get( + @QueryParam("vsysDescriptorId") String id); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "UpdateVSYSDescriptorAttribute") - ListenableFuture update(@QueryParam("vsysDescriptorId") String id, - @QueryParam("updateLcId") String localeId, - @QueryParam("attributeName") String name, - @QueryParam("attributeValue") String value); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "UpdateVSYSDescriptorAttribute") + ListenableFuture update(@QueryParam("vsysDescriptorId") String id, + @QueryParam("updateLcId") String localeId, + @QueryParam("attributeName") String name, + @QueryParam("attributeValue") String value); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "UnregisterVSYSDescriptor") - ListenableFuture deregister( - @QueryParam("vsysDescriptorId") String id); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "UnregisterVSYSDescriptor") + ListenableFuture deregister( + @QueryParam("vsysDescriptorId") String id); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "UnregisterPrivateVSYSDescriptor") - ListenableFuture deregisterPrivateTemplate( - @QueryParam("vsysDescriptorId") String id); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "UnregisterPrivateVSYSDescriptor") + ListenableFuture deregisterPrivateTemplate( + @QueryParam("vsysDescriptorId") String id); } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/VirtualDCApi.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/VirtualDCApi.java index bb3ec3597a..03ec4357cf 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/VirtualDCApi.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/VirtualDCApi.java @@ -18,58 +18,67 @@ */ package org.jclouds.fujitsu.fgcp.services; -import org.jclouds.concurrent.Timeout; -import org.jclouds.fujitsu.fgcp.domain.*; - import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; +import org.jclouds.concurrent.Timeout; +import org.jclouds.fujitsu.fgcp.domain.AddressRange; +import org.jclouds.fujitsu.fgcp.domain.DiskImage; +import org.jclouds.fujitsu.fgcp.domain.EventLog; +import org.jclouds.fujitsu.fgcp.domain.Information; +import org.jclouds.fujitsu.fgcp.domain.PublicIP; +import org.jclouds.fujitsu.fgcp.domain.ServerType; +import org.jclouds.fujitsu.fgcp.domain.UsageInfo; +import org.jclouds.fujitsu.fgcp.domain.VSystem; +import org.jclouds.fujitsu.fgcp.domain.VSystemDescriptor; +import org.jclouds.javax.annotation.Nullable; + /** * API relating to the virtual data center. * + * @see VirtualDCAsyncApi * @author Dies Koper */ @Timeout(duration = 60, timeUnit = TimeUnit.SECONDS) public interface VirtualDCApi { - String createVirtualSystem(String descriptorId, String name); + String createVirtualSystem(String descriptorId, String name); - Set listVirtualSystems(); + Set listVirtualSystems(); - // according to the manual it takes a 'String diskImageId' but value seems - // to be ignored - Set listServerTypes(); + // according to the manual it takes a 'String diskImageId' but value seems + // to be ignored + Set listServerTypes(); - Set listDiskImages(); + Set listDiskImages(); - Set listDiskImages(String serverCategory, - String vsysDescriptorId); + Set listDiskImages(@Nullable String serverCategory, String vsysDescriptorId); - Map listPublicIPs(); + Map listPublicIPs(); - void addAddressRange(String pipFrom, String pipTo); + void addAddressRange(String pipFrom, String pipTo); - void createAddressPool(String pipFrom, String pipTo); + void createAddressPool(String pipFrom, String pipTo); - void deleteAddressRange(String pipFrom, String pipTo); + void deleteAddressRange(String pipFrom, String pipTo); - Set getAddressRange(); + Set getAddressRange(); - Set listVSYSDescriptor(); + Set listVSYSDescriptor(); - Set listVSYSDescriptor(String keyword, int estimateFrom, - int estimateTo); + Set listVSYSDescriptor(String keyword, int estimateFrom, + int estimateTo); - Set getEventLogs(boolean all); + Set getEventLogs(boolean all); - Set getEventLogs(); + Set getEventLogs(); - Set getInformation(boolean all); + Set getInformation(boolean all); - Set getInformation(); + Set getInformation(); - Set getSystemUsage(); + Set getSystemUsage(); - Set getSystemUsage(String systemIds); + Set getSystemUsage(String systemIds); } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/VirtualDCAsyncApi.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/VirtualDCAsyncApi.java index ec4bad9629..7836893678 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/VirtualDCAsyncApi.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/VirtualDCAsyncApi.java @@ -41,6 +41,7 @@ import org.jclouds.fujitsu.fgcp.domain.VSystem; import org.jclouds.fujitsu.fgcp.domain.VSystemDescriptor; import org.jclouds.fujitsu.fgcp.filters.RequestAuthenticator; import org.jclouds.fujitsu.fgcp.reference.RequestParameters; +import org.jclouds.javax.annotation.Nullable; import org.jclouds.rest.annotations.JAXBResponseParser; import org.jclouds.rest.annotations.PayloadParams; import org.jclouds.rest.annotations.QueryParams; @@ -61,129 +62,129 @@ import com.google.common.util.concurrent.ListenableFuture; @Timeout(duration = 60, timeUnit = TimeUnit.SECONDS) public interface VirtualDCAsyncApi { - // @POST - @GET - @JAXBResponseParser - // @XMLResponseParser(VSYSCreateHandler.class) - @QueryParams(keys = "Action", values = "CreateVSYS") - @Transform(SingleElementResponseToElement.class) - // @PayloadParams(keys = "Action", values = "CreateVSYS") - // @Produces(MediaType.TEXT_XML) - // @MapBinder(BindParamsToXmlPayload.class) - // ListenableFuture - // createVirtualSystem(@PayloadParam("vsysDescriptorId") String - // vsysDescriptorId, @PayloadParam("vsysName") String vsysName); - ListenableFuture createVirtualSystem( - @QueryParam("vsysDescriptorId") String descriptorId, - @QueryParam("vsysName") String name); + // @POST + @GET + @JAXBResponseParser + // @XMLResponseParser(VSYSCreateHandler.class) + @QueryParams(keys = "Action", values = "CreateVSYS") + @Transform(SingleElementResponseToElement.class) + // @PayloadParams(keys = "Action", values = "CreateVSYS") + // @Produces(MediaType.TEXT_XML) + // @MapBinder(BindParamsToXmlPayload.class) + // ListenableFuture + // createVirtualSystem(@PayloadParam("vsysDescriptorId") String + // vsysDescriptorId, @PayloadParam("vsysName") String vsysName); + ListenableFuture createVirtualSystem( + @QueryParam("vsysDescriptorId") String descriptorId, + @QueryParam("vsysName") String name); - @GET - @JAXBResponseParser - // @XMLResponseParser(VSYSListHandler.class) - @QueryParams(keys = "Action", values = "ListVSYS") - ListenableFuture> listVirtualSystems(); + @GET + @JAXBResponseParser + // @XMLResponseParser(VSYSListHandler.class) + @QueryParams(keys = "Action", values = "ListVSYS") + ListenableFuture> listVirtualSystems(); - @GET - @JAXBResponseParser - // according to the manual it takes a 'String diskImageId' but value seems - // to be ignored - @QueryParams(keys = { "Action", "diskImageId" }, values = { - "ListServerType", "dummy" }) - // @XmlJavaTypeAdapter(SetOfServerTypesXMLAdapter.class) - // @XmlElement(type = ServerType.class) - ListenableFuture> listServerTypes(); + @GET + @JAXBResponseParser + // according to the manual it takes a 'String diskImageId' but value seems + // to be ignored + @QueryParams(keys = { "Action", "diskImageId" }, values = { + "ListServerType", "dummy" }) + // @XmlJavaTypeAdapter(SetOfServerTypesXMLAdapter.class) + // @XmlElement(type = ServerType.class) + ListenableFuture> listServerTypes(); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "ListDiskImage") - ListenableFuture> listDiskImages(); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "ListDiskImage") + ListenableFuture> listDiskImages(); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "ListDiskImage") - ListenableFuture> listDiskImages( - @QueryParam("serverCategory") String serverCategory, - @QueryParam("vsysDescriptorId") String vsysDescriptorId); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "ListDiskImage") + ListenableFuture> listDiskImages( + @Nullable @QueryParam("serverCategory") String serverCategory, + @QueryParam("vsysDescriptorId") String vsysDescriptorId); - /** - * - * @return - * @see VirtualSystemAsyncApi#listPublicIPs(String) - */ - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "ListPublicIP") - ListenableFuture> listPublicIPs(); + /** + * + * @return + * @see VirtualSystemAsyncApi#listPublicIPs(String) + */ + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "ListPublicIP") + ListenableFuture> listPublicIPs(); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "AddAddressRange") - ListenableFuture addAddressRange( - @QueryParam("pipFrom") String pipFrom, - @QueryParam("pipTo") String pipTo); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "AddAddressRange") + ListenableFuture addAddressRange( + @QueryParam("pipFrom") String pipFrom, + @QueryParam("pipTo") String pipTo); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "CreateAddressPool") - ListenableFuture createAddressPool( - @QueryParam("pipFrom") String pipFrom, - @QueryParam("pipTo") String pipTo); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "CreateAddressPool") + ListenableFuture createAddressPool( + @QueryParam("pipFrom") String pipFrom, + @QueryParam("pipTo") String pipTo); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "DeleteAddressRange") - ListenableFuture deleteAddressRange( - @QueryParam("pipFrom") String pipFrom, - @QueryParam("pipTo") String pipTo); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "DeleteAddressRange") + ListenableFuture deleteAddressRange( + @QueryParam("pipFrom") String pipFrom, + @QueryParam("pipTo") String pipTo); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "GetAddressRange") - ListenableFuture> getAddressRange(); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "GetAddressRange") + ListenableFuture> getAddressRange(); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "ListVSYSDescriptor") - ListenableFuture> listVSYSDescriptor(); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "ListVSYSDescriptor") + ListenableFuture> listVSYSDescriptor(); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "ListVSYSDescriptor") - ListenableFuture> listVSYSDescriptor( - @QueryParam("keyword") String keyword, - @QueryParam("estimateFrom") int estimateFrom, - @QueryParam("estimateTo") int estimateTo); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "ListVSYSDescriptor") + ListenableFuture> listVSYSDescriptor( + @QueryParam("keyword") String keyword, + @QueryParam("estimateFrom") int estimateFrom, + @QueryParam("estimateTo") int estimateTo); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "GetEventLog") - ListenableFuture> getEventLogs(); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "GetEventLog") + ListenableFuture> getEventLogs(); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "GetEventLog") - ListenableFuture> getEventLogs(@QueryParam("all") boolean all); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "GetEventLog") + ListenableFuture> getEventLogs(@QueryParam("all") boolean all); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "GetInformation") - ListenableFuture> getInformation(); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "GetInformation") + ListenableFuture> getInformation(); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "GetInformation") - ListenableFuture> getInformation( - @QueryParam("all") boolean all); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "GetInformation") + ListenableFuture> getInformation( + @QueryParam("all") boolean all); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "GetSystemUsage") - ListenableFuture> getSystemUsage(); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "GetSystemUsage") + ListenableFuture> getSystemUsage(); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "GetSystemUsage") - ListenableFuture> getSystemUsage( - @QueryParam("systemIds") String systemIds); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "GetSystemUsage") + ListenableFuture> getSystemUsage( + @QueryParam("systemIds") String systemIds); } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/VirtualServerApi.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/VirtualServerApi.java index 70be613e2b..e1dabaf021 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/VirtualServerApi.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/VirtualServerApi.java @@ -35,27 +35,27 @@ import org.jclouds.fujitsu.fgcp.domain.VServerWithDetails; @Timeout(duration = 60, timeUnit = TimeUnit.SECONDS) public interface VirtualServerApi { - void start(String id); + void start(String id); - void stop(String id); + void stop(String id); - void stopForcefully(String id); + void stopForcefully(String id); - void destroy(String id); + void destroy(String id); - VServer get(String id); + VServer get(String id); - VServerWithDetails getDetails(String id); + VServerWithDetails getDetails(String id); - void update(String id, String name, String value); + void update(String id, String name, String value); - VServerStatus getStatus(String id); + VServerStatus getStatus(String id); - String getInitialPassword(String id); + String getInitialPassword(String id); - void attachDisk(String serverId, String diskId); + void attachDisk(String serverId, String diskId); - Set getPerformanceInformation(String id, String interval); + Set getPerformanceInformation(String id, String interval); - void registerAsPrivateDiskImage(String xml); + void registerAsPrivateDiskImage(String xml); } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/VirtualServerAsyncApi.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/VirtualServerAsyncApi.java index 5159c3bdce..15d85a2299 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/VirtualServerAsyncApi.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/VirtualServerAsyncApi.java @@ -58,91 +58,91 @@ import com.google.common.util.concurrent.ListenableFuture; @Timeout(duration = 60, timeUnit = TimeUnit.SECONDS) public interface VirtualServerAsyncApi { - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "StartVServer") - ListenableFuture start( - @BinderParam(BindAlsoToSystemId.class) @QueryParam("vserverId") String id); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "StartVServer") + ListenableFuture start( + @BinderParam(BindAlsoToSystemId.class) @QueryParam("vserverId") String id); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "StopVServer") - ListenableFuture stop( - @BinderParam(BindAlsoToSystemId.class) @QueryParam("vserverId") String id); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "StopVServer") + ListenableFuture stop( + @BinderParam(BindAlsoToSystemId.class) @QueryParam("vserverId") String id); - @GET - @JAXBResponseParser - @QueryParams(keys = { "Action", "force" }, values = { "StopVServer", "true" }) - ListenableFuture stopForcefully( - @BinderParam(BindAlsoToSystemId.class) @QueryParam("vserverId") String id); + @GET + @JAXBResponseParser + @QueryParams(keys = { "Action", "force" }, values = { "StopVServer", "true" }) + ListenableFuture stopForcefully( + @BinderParam(BindAlsoToSystemId.class) @QueryParam("vserverId") String id); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "DestroyVServer") - ListenableFuture destroy( - @BinderParam(BindAlsoToSystemId.class) @QueryParam("vserverId") String id); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "DestroyVServer") + ListenableFuture destroy( + @BinderParam(BindAlsoToSystemId.class) @QueryParam("vserverId") String id); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "GetVServerAttributes") - @Transform(SingleElementResponseToElement.class) - ListenableFuture get( - @BinderParam(BindAlsoToSystemId.class) @QueryParam("vserverId") String id); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "GetVServerAttributes") + @Transform(SingleElementResponseToElement.class) + ListenableFuture get( + @BinderParam(BindAlsoToSystemId.class) @QueryParam("vserverId") String id); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "GetVServerConfiguration") - @Transform(SingleElementResponseToElement.class) - ListenableFuture getDetails( - @BinderParam(BindAlsoToSystemId.class) @QueryParam("vserverId") String id); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "GetVServerConfiguration") + @Transform(SingleElementResponseToElement.class) + ListenableFuture getDetails( + @BinderParam(BindAlsoToSystemId.class) @QueryParam("vserverId") String id); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "UpdateVServerAttribute") - ListenableFuture update( - @BinderParam(BindAlsoToSystemId.class) @QueryParam("vserverId") String id, - @QueryParam("attributeName") String name, - @QueryParam("attributeValue") String value); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "UpdateVServerAttribute") + ListenableFuture update( + @BinderParam(BindAlsoToSystemId.class) @QueryParam("vserverId") String id, + @QueryParam("attributeName") String name, + @QueryParam("attributeValue") String value); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "GetVServerStatus") - // @Transform(StringToVServerStatus.class) - @Transform(SingleElementResponseToElement.class) - ListenableFuture getStatus( - @BinderParam(BindAlsoToSystemId.class) @QueryParam("vserverId") String id); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "GetVServerStatus") + // @Transform(StringToVServerStatus.class) + @Transform(SingleElementResponseToElement.class) + ListenableFuture getStatus( + @BinderParam(BindAlsoToSystemId.class) @QueryParam("vserverId") String id); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "GetVServerInitialPassword") - @Transform(SingleElementResponseToElement.class) - ListenableFuture getInitialPassword( - @BinderParam(BindAlsoToSystemId.class) @QueryParam("vserverId") String id); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "GetVServerInitialPassword") + @Transform(SingleElementResponseToElement.class) + ListenableFuture getInitialPassword( + @BinderParam(BindAlsoToSystemId.class) @QueryParam("vserverId") String id); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "AttachVDisk") - ListenableFuture attachDisk( - @BinderParam(BindAlsoToSystemId.class) @QueryParam("vserverId") String serverId, - @QueryParam("vdiskId") String diskId); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "AttachVDisk") + ListenableFuture attachDisk( + @BinderParam(BindAlsoToSystemId.class) @QueryParam("vserverId") String serverId, + @QueryParam("vdiskId") String diskId); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "GetPerformanceInformation") - ListenableFuture> getPerformanceInformation( - @BinderParam(BindAlsoToSystemId.class) @QueryParam("serverId") String id, - @QueryParam("interval") String interval); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "GetPerformanceInformation") + ListenableFuture> getPerformanceInformation( + @BinderParam(BindAlsoToSystemId.class) @QueryParam("serverId") String id, + @QueryParam("interval") String interval); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "GetPerformanceInformation") - ListenableFuture> getPerformanceInformation( - @BinderParam(BindAlsoToSystemId.class) @QueryParam("serverId") String id, - @QueryParam("dataType") String dataType, - @QueryParam("interval") String interval); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "GetPerformanceInformation") + ListenableFuture> getPerformanceInformation( + @BinderParam(BindAlsoToSystemId.class) @QueryParam("serverId") String id, + @QueryParam("dataType") String dataType, + @QueryParam("interval") String interval); - @POST - @JAXBResponseParser - @QueryParams(keys = "Action", values = "RegisterPrivateDiskImage") - ListenableFuture registerAsPrivateDiskImage(String xml); + @POST + @JAXBResponseParser + @QueryParams(keys = "Action", values = "RegisterPrivateDiskImage") + ListenableFuture registerAsPrivateDiskImage(String xml); } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/VirtualSystemApi.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/VirtualSystemApi.java index 5ec70204ff..3bc12cda1b 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/VirtualSystemApi.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/VirtualSystemApi.java @@ -38,37 +38,37 @@ import org.jclouds.fujitsu.fgcp.domain.VSystemWithDetails; @Timeout(duration = 60, timeUnit = TimeUnit.SECONDS) public interface VirtualSystemApi { - void destroy(String id); + void destroy(String id); - VSystemStatus getStatus(String id); + VSystemStatus getStatus(String id); - VSystem get(String id); + VSystem get(String id); - VSystemWithDetails getDetails(String id); + VSystemWithDetails getDetails(String id); - void update(String id, String name, String value); + void update(String id, String name, String value); - void updateConfiguration(String id, String name, String value); + void updateConfiguration(String id, String name, String value); - String createServer(String name, String type, String diskImageId, - String networkId); + String createServer(String name, String type, String diskImageId, + String networkId); - Set listServers(String id); + Set listServers(String id); - String createBuiltinServer(String name, String networkId); + String createBuiltinServer(String name, String networkId); - Set listBuiltinServers(String id, String type); + Set listBuiltinServers(String id, String type); - String createDisk(String id, String name, int size); + String createDisk(String id, String name, int size); - Set listDisks(String id); + Set listDisks(String id); - void allocatePublicIP(String id); + void allocatePublicIP(String id); - Set listPublicIPs(String id); + Set listPublicIPs(String id); - String standByConsole(String id, String networkId); + String standByConsole(String id, String networkId); - void registerAsPrivateVSYSDescriptor(String id, - String vsysDescriptorXMLFilePath); + void registerAsPrivateVSYSDescriptor(String id, + String vsysDescriptorXMLFilePath); } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/VirtualSystemAsyncApi.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/VirtualSystemAsyncApi.java index c9d4d20b71..12a02753b5 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/VirtualSystemAsyncApi.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/services/VirtualSystemAsyncApi.java @@ -60,115 +60,115 @@ import com.google.common.util.concurrent.ListenableFuture; @Timeout(duration = 60, timeUnit = TimeUnit.SECONDS) public interface VirtualSystemAsyncApi { - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "DestroyVSYS") - ListenableFuture destroy(@QueryParam("vsysId") String id); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "DestroyVSYS") + ListenableFuture destroy(@QueryParam("vsysId") String id); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "GetVSYSStatus") - @Transform(SingleElementResponseToElement.class) - ListenableFuture getStatus(@QueryParam("vsysId") String id); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "GetVSYSStatus") + @Transform(SingleElementResponseToElement.class) + ListenableFuture getStatus(@QueryParam("vsysId") String id); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "GetVSYSAttributes") - @Transform(SingleElementResponseToElement.class) - ListenableFuture get(@QueryParam("vsysId") String id); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "GetVSYSAttributes") + @Transform(SingleElementResponseToElement.class) + ListenableFuture get(@QueryParam("vsysId") String id); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "GetVSYSConfiguration") - @Transform(SingleElementResponseToElement.class) - ListenableFuture getDetails( - @QueryParam("vsysId") String id); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "GetVSYSConfiguration") + @Transform(SingleElementResponseToElement.class) + ListenableFuture getDetails( + @QueryParam("vsysId") String id); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "UpdateVSYSAttribute") - ListenableFuture update(@QueryParam("vsysId") String id, - @QueryParam("attributeName") String name, - @QueryParam("attributeValue") String value); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "UpdateVSYSAttribute") + ListenableFuture update(@QueryParam("vsysId") String id, + @QueryParam("attributeName") String name, + @QueryParam("attributeValue") String value); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "UpdateVSYSConfiguration") - ListenableFuture updateConfiguration(@QueryParam("vsysId") String id, - @QueryParam("configurationName") String name, - @QueryParam("configurationValue") String value); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "UpdateVSYSConfiguration") + ListenableFuture updateConfiguration(@QueryParam("vsysId") String id, + @QueryParam("configurationName") String name, + @QueryParam("configurationValue") String value); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "CreateVServer") - @Transform(SingleElementResponseToElement.class) - ListenableFuture createServer( - @QueryParam("vserverName") String name, - @QueryParam("vserverType") String type, - @QueryParam("diskImageId") String diskImageId, - @BinderParam(BindAlsoToSystemId.class) @QueryParam("networkId") String networkId); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "CreateVServer") + @Transform(SingleElementResponseToElement.class) + ListenableFuture createServer( + @QueryParam("vserverName") String name, + @QueryParam("vserverType") String type, + @QueryParam("diskImageId") String diskImageId, + @BinderParam(BindAlsoToSystemId.class) @QueryParam("networkId") String networkId); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "ListVServer") - ListenableFuture> listServers(@QueryParam("vsysId") String id); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "ListVServer") + ListenableFuture> listServers(@QueryParam("vsysId") String id); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "CreateVDisk") - @Transform(SingleElementResponseToElement.class) - ListenableFuture createDisk(@QueryParam("vsysId") String id, - @QueryParam("vdiskName") String name, @QueryParam("size") int size); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "CreateVDisk") + @Transform(SingleElementResponseToElement.class) + ListenableFuture createDisk(@QueryParam("vsysId") String id, + @QueryParam("vdiskName") String name, @QueryParam("size") int size); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "ListVDisk") - ListenableFuture> listDisks(@QueryParam("vsysId") String id); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "ListVDisk") + ListenableFuture> listDisks(@QueryParam("vsysId") String id); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "AllocatePublicIP") - ListenableFuture allocatePublicIP(@QueryParam("vsysId") String id); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "AllocatePublicIP") + ListenableFuture allocatePublicIP(@QueryParam("vsysId") String id); - /** - * - * @return - * @see VirtualDCAsyncApi#listPublicIPs() - */ - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "ListPublicIP") - @Transform(SingleElementResponseToElement.class) - ListenableFuture> listPublicIPs( - @QueryParam("vsysId") String id); + /** + * + * @return + * @see VirtualDCAsyncApi#listPublicIPs() + */ + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "ListPublicIP") + @Transform(SingleElementResponseToElement.class) + ListenableFuture> listPublicIPs( + @QueryParam("vsysId") String id); - @GET - @JAXBResponseParser - // SLB is the only built-in server that can currently be created so - // hard-code it - @QueryParams(keys = { "Action", "efmType" }, values = { "CreateEFM", "SLB" }) - @Transform(SingleElementResponseToElement.class) - ListenableFuture createBuiltinServer( - @QueryParam("efmName") String name, - @BinderParam(BindAlsoToSystemId.class) @QueryParam("networkId") String networkId); + @GET + @JAXBResponseParser + // SLB is the only built-in server that can currently be created so + // hard-code it + @QueryParams(keys = { "Action", "efmType" }, values = { "CreateEFM", "SLB" }) + @Transform(SingleElementResponseToElement.class) + ListenableFuture createBuiltinServer( + @QueryParam("efmName") String name, + @BinderParam(BindAlsoToSystemId.class) @QueryParam("networkId") String networkId); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "ListEFM") - ListenableFuture> listBuiltinServers( - @QueryParam("vsysId") String id, @QueryParam("efmType") String type); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "ListEFM") + ListenableFuture> listBuiltinServers( + @QueryParam("vsysId") String id, @QueryParam("efmType") String type); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "StandByConsole") - @Transform(SingleElementResponseToElement.class) - ListenableFuture standByConsole(@QueryParam("vsysId") String id, - @QueryParam("networkId") String networkId); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "StandByConsole") + @Transform(SingleElementResponseToElement.class) + ListenableFuture standByConsole(@QueryParam("vsysId") String id, + @QueryParam("networkId") String networkId); - @GET - @JAXBResponseParser - @QueryParams(keys = "Action", values = "RegisterPrivateVSYSDescriptor") - ListenableFuture registerAsPrivateVSYSDescriptor( - @QueryParam("vsysId") String id, - @QueryParam("vsysDescriptorXMLFilePath") String vsysDescriptorXMLFilePath); + @GET + @JAXBResponseParser + @QueryParams(keys = "Action", values = "RegisterPrivateVSYSDescriptor") + ListenableFuture registerAsPrivateVSYSDescriptor( + @QueryParam("vsysId") String id, + @QueryParam("vsysDescriptorXMLFilePath") String vsysDescriptorXMLFilePath); } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/BindParamsToXmlPayload.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/BindParamsToXmlPayload.java index 0783787bd0..153207338d 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/BindParamsToXmlPayload.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/BindParamsToXmlPayload.java @@ -18,18 +18,20 @@ */ package org.jclouds.fujitsu.fgcp.xml; -import com.google.common.base.Strings; +import static com.google.common.base.Preconditions.checkNotNull; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Map; + +import javax.ws.rs.core.MediaType; + import org.jclouds.fujitsu.fgcp.reference.RequestParameters; import org.jclouds.http.HttpRequest; import org.jclouds.rest.MapBinder; import org.jclouds.rest.binders.BindToStringPayload; -import javax.ws.rs.core.MediaType; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Map; - -import static com.google.common.base.Preconditions.checkNotNull; +import com.google.common.base.Strings; /** * Not currently used but leaving for reference when implementing multipart POST @@ -38,59 +40,60 @@ import static com.google.common.base.Preconditions.checkNotNull; * @author Dies Koper */ public class BindParamsToXmlPayload extends BindToStringPayload implements - MapBinder { + MapBinder { - @Override - public R bindToRequest(R request, - Map mapParams) { - String action = checkNotNull( - mapParams.remove(RequestParameters.ACTION), - RequestParameters.ACTION).toString(); - String version = Strings.nullToEmpty((String) mapParams - .remove(RequestParameters.VERSION)); + @SuppressWarnings("unchecked") + @Override + public R bindToRequest(R request, + Map mapParams) { + String action = checkNotNull( + mapParams.remove(RequestParameters.ACTION), + RequestParameters.ACTION).toString(); + String version = Strings.nullToEmpty((String) mapParams + .remove(RequestParameters.VERSION)); - StringBuilder xml = new StringBuilder(); - xml.append("\r\n"); - xml.append("\r\n"); - xml.append(" " + action + "\r\n"); + StringBuilder xml = new StringBuilder(); + xml.append("\r\n"); + xml.append("\r\n"); + xml.append(" " + action + "\r\n"); - for (Map.Entry entry : mapParams.entrySet()) { - String key = entry.getKey(); - xml.append(" <" + key + ">" + checkNotNull(mapParams.get(key)) - + "\r\n"); - } + for (Map.Entry entry : mapParams.entrySet()) { + String key = entry.getKey(); + xml.append(" <" + key + ">" + checkNotNull(mapParams.get(key)) + + "\r\n"); + } - xml.append(" " + version + "\r\n"); - xml.append(" \r\n"); // value inserted in - // RequestAuthenticator#filter - xml.append(" \r\n"); // value inserted in - // RequestAuthenticator#filter - xml.append(" \r\n"); // value inserted in - // RequestAuthenticator#filter - xml.append(""); + xml.append(" " + version + "\r\n"); + xml.append(" \r\n"); // value inserted in + // RequestAuthenticator#filter + xml.append(" \r\n"); // value inserted in + // RequestAuthenticator#filter + xml.append(" \r\n"); // value inserted in + // RequestAuthenticator#filter + xml.append(""); - request = super.bindToRequest(request, xml); - request.getPayload().getContentMetadata() - .setContentType(MediaType.TEXT_XML); + request = super.bindToRequest(request, xml); + request.getPayload().getContentMetadata() + .setContentType(MediaType.TEXT_XML); - // remove version query param if set as it was moved to the xml body - URI uri = request.getEndpoint(); - URI uriWithoutQueryParams; - try { - uriWithoutQueryParams = new URI(uri.getScheme(), uri.getUserInfo(), - uri.getHost(), uri.getPort(), uri.getPath(), null, - uri.getFragment()); - } catch (URISyntaxException e) { - // should never happen as we're copying the components from a URI - uriWithoutQueryParams = uri; - } + // remove version query param if set as it was moved to the xml body + URI uri = request.getEndpoint(); + URI uriWithoutQueryParams; + try { + uriWithoutQueryParams = new URI(uri.getScheme(), uri.getUserInfo(), + uri.getHost(), uri.getPort(), uri.getPath(), null, + uri.getFragment()); + } catch (URISyntaxException e) { + // should never happen as we're copying the components from a URI + uriWithoutQueryParams = uri; + } - return (R) request.toBuilder().endpoint(uriWithoutQueryParams).build(); - } + return (R) request.toBuilder().endpoint(uriWithoutQueryParams).build(); + } - @Override - public R bindToRequest(R request, Object toBind) { - throw new IllegalArgumentException( - "BindParamsToXmlPayload needs bind parameters"); - } + @Override + public R bindToRequest(R request, Object toBind) { + throw new IllegalArgumentException( + "BindParamsToXmlPayload needs bind parameters"); + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/FGCPJAXBParser.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/FGCPJAXBParser.java index b5349ab859..7e8dfff2f7 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/FGCPJAXBParser.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/FGCPJAXBParser.java @@ -40,49 +40,49 @@ import org.jclouds.xml.XMLParser; */ @Singleton public class FGCPJAXBParser implements XMLParser { - JAXBContext context; + JAXBContext context; - public FGCPJAXBParser() throws JAXBException { - context = JAXBContext.newInstance(VServerWithDetails.class.getPackage() - .getName() - + ":" - + ListServerTypeResponse.class.getPackage().getName(), - VServerWithDetails.class.getClassLoader()); - } + public FGCPJAXBParser() throws JAXBException { + context = JAXBContext.newInstance(VServerWithDetails.class.getPackage() + .getName() + + ":" + + ListServerTypeResponse.class.getPackage().getName(), + VServerWithDetails.class.getClassLoader()); + } - @Override - public String toXML(final Object src) throws IOException { - return toXML(src, src.getClass()); - } + @Override + public String toXML(final Object src) throws IOException { + return toXML(src, src.getClass()); + } - @Override - public String toXML(final Object src, final Class type) - throws IOException { - throw new UnsupportedOperationException( - "only marshaling from XML is implemented"); - } + @Override + public String toXML(final Object src, final Class type) + throws IOException { + throw new UnsupportedOperationException( + "only marshaling from XML is implemented"); + } - @SuppressWarnings("unchecked") - @Override - public T fromXML(final String xml, final Class type) - throws IOException { - T response = null; - try { - StringReader reader = new StringReader(xml); + @SuppressWarnings("unchecked") + @Override + public T fromXML(final String xml, final Class type) + throws IOException { + T response = null; + try { + StringReader reader = new StringReader(xml); - Unmarshaller unmarshaller = context.createUnmarshaller(); + Unmarshaller unmarshaller = context.createUnmarshaller(); - response = (T) unmarshaller.unmarshal(reader); - } catch (Exception ex) { - throw new IOException("Could not unmarshal document", ex); - } + response = (T) unmarshaller.unmarshal(reader); + } catch (Exception ex) { + throw new IOException("Could not unmarshal document", ex); + } - if (((StatusQuerable) response).isError()) { - throw new HttpException( - ((StatusQuerable) response).getResponseMessage()); - } + if (((StatusQuerable) response).isError()) { + throw new HttpException( + ((StatusQuerable) response).getResponseMessage()); + } - return response; - } + return response; + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/CreateEFMResponse.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/CreateEFMResponse.java index 237fde513f..8c3fdb9757 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/CreateEFMResponse.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/CreateEFMResponse.java @@ -28,17 +28,17 @@ import javax.xml.bind.annotation.XmlRootElement; */ @XmlRootElement(name = "CreateEFMResponse") public class CreateEFMResponse extends StatusResponse implements - SingleElementResponse { - @XmlElement(required = true) - private String efmId; + SingleElementResponse { + @XmlElement(required = true) + private String efmId; - @Override - public String toString() { - return getElement(); - } + @Override + public String toString() { + return getElement(); + } - @Override - public String getElement() { - return efmId; - } + @Override + public String getElement() { + return efmId; + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/CreateVDiskResponse.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/CreateVDiskResponse.java index b31a637f9d..6bf1a1f555 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/CreateVDiskResponse.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/CreateVDiskResponse.java @@ -28,17 +28,17 @@ import javax.xml.bind.annotation.XmlRootElement; */ @XmlRootElement(name = "CreateVDiskResponse") public class CreateVDiskResponse extends StatusResponse implements - SingleElementResponse { - @XmlElement(required = true) - private String vdiskId; + SingleElementResponse { + @XmlElement(required = true) + private String vdiskId; - @Override - public String toString() { - return getElement(); - } + @Override + public String toString() { + return getElement(); + } - @Override - public String getElement() { - return vdiskId; - } + @Override + public String getElement() { + return vdiskId; + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/CreateVSYSResponse.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/CreateVSYSResponse.java index a18a3fada7..61dd417633 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/CreateVSYSResponse.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/CreateVSYSResponse.java @@ -28,17 +28,17 @@ import javax.xml.bind.annotation.XmlRootElement; */ @XmlRootElement(name = "CreateVSYSResponse") public class CreateVSYSResponse extends StatusResponse implements - SingleElementResponse { - @XmlElement(required = true) - private String vsysId; + SingleElementResponse { + @XmlElement(required = true) + private String vsysId; - @Override - public String toString() { - return getElement(); - } + @Override + public String toString() { + return getElement(); + } - @Override - public String getElement() { - return vsysId; - } + @Override + public String getElement() { + return vsysId; + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/CreateVServerResponse.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/CreateVServerResponse.java index 6170ee407a..7d7ddcd88b 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/CreateVServerResponse.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/CreateVServerResponse.java @@ -28,17 +28,17 @@ import javax.xml.bind.annotation.XmlRootElement; */ @XmlRootElement(name = "CreateVServerResponse") public class CreateVServerResponse extends StatusResponse implements - SingleElementResponse { - @XmlElement(required = true) - private String vserverId; + SingleElementResponse { + @XmlElement(required = true) + private String vserverId; - @Override - public String toString() { - return getElement(); - } + @Override + public String toString() { + return getElement(); + } - @Override - public String getElement() { - return vserverId; - } + @Override + public String getElement() { + return vserverId; + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetAddressRangeResponse.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetAddressRangeResponse.java index 9ea55713ac..799b3df445 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetAddressRangeResponse.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetAddressRangeResponse.java @@ -37,14 +37,14 @@ import com.google.common.collect.ImmutableSet; */ @XmlRootElement(name = "GetAddressRangeResponse") public class GetAddressRangeResponse extends - SetWithStatusResponse { - @XmlElementWrapper(name = "addressranges") - @XmlElement(name = "addressrange") - private Set ranges = new LinkedHashSet(); + SetWithStatusResponse { + @XmlElementWrapper(name = "addressranges") + @XmlElement(name = "addressrange") + private Set ranges = new LinkedHashSet(); - @Override - protected Set delegate() { - return ranges == null ? ImmutableSet. of() : Collections - .unmodifiableSet(ranges); - } + @Override + protected Set delegate() { + return ranges == null ? ImmutableSet. of() : Collections + .unmodifiableSet(ranges); + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetDiskImageAttributesResponse.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetDiskImageAttributesResponse.java index ccef26f210..a6c59cfecf 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetDiskImageAttributesResponse.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetDiskImageAttributesResponse.java @@ -18,11 +18,11 @@ */ package org.jclouds.fujitsu.fgcp.xml.internal; -import org.jclouds.fujitsu.fgcp.domain.DiskImage; - import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; +import org.jclouds.fujitsu.fgcp.domain.DiskImage; + /** * Wrapper for GetDiskImageAttributesResponse. * @@ -30,17 +30,17 @@ import javax.xml.bind.annotation.XmlRootElement; */ @XmlRootElement(name = "GetDiskImageAttributesResponse") public class GetDiskImageAttributesResponse extends StatusResponse implements - SingleElementResponse { - @XmlElement(name = "diskimage") - private DiskImage diskImage; + SingleElementResponse { + @XmlElement(name = "diskimage") + private DiskImage diskImage; - @Override - public String toString() { - return getElement().toString(); - } + @Override + public String toString() { + return getElement().toString(); + } - @Override - public DiskImage getElement() { - return diskImage; - } + @Override + public DiskImage getElement() { + return diskImage; + } } \ No newline at end of file diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetEFMAttributesResponse.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetEFMAttributesResponse.java index 9764a9e516..939d63e4a0 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetEFMAttributesResponse.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetEFMAttributesResponse.java @@ -30,17 +30,17 @@ import org.jclouds.fujitsu.fgcp.domain.BuiltinServer; */ @XmlRootElement(name = "GetEFMAttributesResponse") public class GetEFMAttributesResponse extends StatusResponse implements - SingleElementResponse { - @XmlElement(required = true) - private BuiltinServer efm; + SingleElementResponse { + @XmlElement(required = true) + private BuiltinServer efm; - @Override - public String toString() { - return getElement().toString(); - } + @Override + public String toString() { + return getElement().toString(); + } - @Override - public Object getElement() { - return efm; - } + @Override + public Object getElement() { + return efm; + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetEFMStatusResponse.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetEFMStatusResponse.java index 34fa4c6204..a243c80459 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetEFMStatusResponse.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetEFMStatusResponse.java @@ -30,17 +30,17 @@ import org.jclouds.fujitsu.fgcp.domain.BuiltinServerStatus; */ @XmlRootElement(name = "GetEFMStatusResponse") public class GetEFMStatusResponse extends StatusResponse implements - SingleElementResponse { - @XmlElement(required = true) - private BuiltinServerStatus efmStatus; + SingleElementResponse { + @XmlElement(required = true) + private BuiltinServerStatus efmStatus; - @Override - public String toString() { - return getElement().toString(); - } + @Override + public String toString() { + return getElement().toString(); + } - @Override - public Object getElement() { - return efmStatus; - } + @Override + public Object getElement() { + return efmStatus; + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetEventLogResponse.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetEventLogResponse.java index c9f35d25e9..988d79dc63 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetEventLogResponse.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetEventLogResponse.java @@ -37,13 +37,13 @@ import com.google.common.collect.ImmutableSet; */ @XmlRootElement(name = "GetEventLogResponse") public class GetEventLogResponse extends SetWithStatusResponse { - @XmlElementWrapper(name = "eventlogs") - @XmlElement(name = "eventlog") - private Set logs = new LinkedHashSet(); + @XmlElementWrapper(name = "eventlogs") + @XmlElement(name = "eventlog") + private Set logs = new LinkedHashSet(); - @Override - protected Set delegate() { - return logs == null ? ImmutableSet. of() : Collections - .unmodifiableSet(logs); - } + @Override + protected Set delegate() { + return logs == null ? ImmutableSet. of() : Collections + .unmodifiableSet(logs); + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetPerformanceInformationResponse.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetPerformanceInformationResponse.java index e8c92909d1..2c3b5f5b09 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetPerformanceInformationResponse.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetPerformanceInformationResponse.java @@ -37,14 +37,14 @@ import com.google.common.collect.ImmutableSet; */ @XmlRootElement(name = "GetPerformanceInformationResponse") public class GetPerformanceInformationResponse extends - SetWithStatusResponse { - @XmlElementWrapper(name = "performanceinfos") - @XmlElement(name = "performanceinfo") - private Set stats = new LinkedHashSet(); + SetWithStatusResponse { + @XmlElementWrapper(name = "performanceinfos") + @XmlElement(name = "performanceinfo") + private Set stats = new LinkedHashSet(); - @Override - protected Set delegate() { - return stats == null ? ImmutableSet. of() - : Collections.unmodifiableSet(stats); - } + @Override + protected Set delegate() { + return stats == null ? ImmutableSet. of() + : Collections.unmodifiableSet(stats); + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetPublicIPAttributesResponse.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetPublicIPAttributesResponse.java index d0a0488819..cb4f958b62 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetPublicIPAttributesResponse.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetPublicIPAttributesResponse.java @@ -26,7 +26,6 @@ import javax.xml.bind.annotation.XmlRootElement; import org.jclouds.fujitsu.fgcp.domain.PublicIP; - import com.google.common.collect.Iterables; /** @@ -36,18 +35,18 @@ import com.google.common.collect.Iterables; */ @XmlRootElement(name = "GetPublicIPAttributesResponse") public class GetPublicIPAttributesResponse extends StatusResponse implements - SingleElementResponse { - @XmlElementWrapper(name = "publicips") - @XmlElement(name = "publicip") - private Set publicIPs; + SingleElementResponse { + @XmlElementWrapper(name = "publicips") + @XmlElement(name = "publicip") + private Set publicIPs; - @Override - public String toString() { - return getElement().toString(); - } + @Override + public String toString() { + return getElement().toString(); + } - @Override - public Object getElement() { - return Iterables.getOnlyElement(publicIPs); - } + @Override + public Object getElement() { + return Iterables.getOnlyElement(publicIPs); + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetPublicIPStatusResponse.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetPublicIPStatusResponse.java index 29e5ce91f3..69b4fc26db 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetPublicIPStatusResponse.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetPublicIPStatusResponse.java @@ -30,17 +30,17 @@ import org.jclouds.fujitsu.fgcp.domain.PublicIPStatus; */ @XmlRootElement(name = "GetPublicIPStatusResponse") public class GetPublicIPStatusResponse extends StatusResponse implements - SingleElementResponse { - @XmlElement(required = true) - private PublicIPStatus publicipStatus; + SingleElementResponse { + @XmlElement(required = true) + private PublicIPStatus publicipStatus; - @Override - public String toString() { - return publicipStatus.toString(); - } + @Override + public String toString() { + return publicipStatus.toString(); + } - @Override - public Object getElement() { - return publicipStatus; - } + @Override + public Object getElement() { + return publicipStatus; + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetVDiskAttributesResponse.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetVDiskAttributesResponse.java index 0634f00c22..cc486d1213 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetVDiskAttributesResponse.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetVDiskAttributesResponse.java @@ -30,17 +30,17 @@ import org.jclouds.fujitsu.fgcp.domain.VDisk; */ @XmlRootElement(name = "GetVDiskAttributesResponse") public class GetVDiskAttributesResponse extends StatusResponse implements - SingleElementResponse { - @XmlElement(required = true) - private VDisk vdisk; + SingleElementResponse { + @XmlElement(required = true) + private VDisk vdisk; - @Override - public String toString() { - return getElement().toString(); - } + @Override + public String toString() { + return getElement().toString(); + } - @Override - public Object getElement() { - return vdisk; - } + @Override + public Object getElement() { + return vdisk; + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetVSYSAttributesResponse.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetVSYSAttributesResponse.java index 0833a4df0e..bd2ff354ac 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetVSYSAttributesResponse.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetVSYSAttributesResponse.java @@ -30,17 +30,17 @@ import org.jclouds.fujitsu.fgcp.domain.VSystem; */ @XmlRootElement(name = "GetVSYSAttributesResponse") public class GetVSYSAttributesResponse extends StatusResponse implements - SingleElementResponse { - @XmlElement(name = "vsys") - private VSystem system; + SingleElementResponse { + @XmlElement(name = "vsys") + private VSystem system; - @Override - public String toString() { - return getElement().toString(); - } + @Override + public String toString() { + return getElement().toString(); + } - @Override - public Object getElement() { - return system; - } + @Override + public Object getElement() { + return system; + } } \ No newline at end of file diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetVSYSConfigurationResponse.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetVSYSConfigurationResponse.java index c593a3bb4b..977a177ae8 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetVSYSConfigurationResponse.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetVSYSConfigurationResponse.java @@ -30,17 +30,17 @@ import org.jclouds.fujitsu.fgcp.domain.VSystemWithDetails; */ @XmlRootElement(name = "GetVSYSConfigurationResponse") public class GetVSYSConfigurationResponse extends StatusResponse implements - SingleElementResponse { - @XmlElement(name = "vsys") - private VSystemWithDetails system; + SingleElementResponse { + @XmlElement(name = "vsys") + private VSystemWithDetails system; - @Override - public String toString() { - return getElement().toString(); - } + @Override + public String toString() { + return getElement().toString(); + } - @Override - public Object getElement() { - return system; - } + @Override + public Object getElement() { + return system; + } } \ No newline at end of file diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetVSYSDescriptorConfigurationResponse.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetVSYSDescriptorConfigurationResponse.java index af21f20658..75e7a5ea36 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetVSYSDescriptorConfigurationResponse.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetVSYSDescriptorConfigurationResponse.java @@ -30,17 +30,17 @@ import org.jclouds.fujitsu.fgcp.domain.VSystemDescriptor; */ @XmlRootElement(name = "GetVSYSDescriptorConfigurationResponse") public class GetVSYSDescriptorConfigurationResponse extends StatusResponse - implements SingleElementResponse { - @XmlElement - private VSystemDescriptor vsysdescriptor; + implements SingleElementResponse { + @XmlElement + private VSystemDescriptor vsysdescriptor; - @Override - public String toString() { - return getElement().toString(); - } + @Override + public String toString() { + return getElement().toString(); + } - @Override - public Object getElement() { - return vsysdescriptor; - } + @Override + public Object getElement() { + return vsysdescriptor; + } } \ No newline at end of file diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetVSYSStatusResponse.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetVSYSStatusResponse.java index 08d1dc97d1..074ea0bab6 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetVSYSStatusResponse.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetVSYSStatusResponse.java @@ -30,17 +30,17 @@ import org.jclouds.fujitsu.fgcp.domain.VSystemStatus; */ @XmlRootElement(name = "GetVSYSStatusResponse") public class GetVSYSStatusResponse extends StatusResponse implements - SingleElementResponse { - @XmlElement(required = true) - private VSystemStatus vsysStatus; + SingleElementResponse { + @XmlElement(required = true) + private VSystemStatus vsysStatus; - @Override - public String toString() { - return getElement().toString(); - } + @Override + public String toString() { + return getElement().toString(); + } - @Override - public Object getElement() { - return vsysStatus; - } + @Override + public Object getElement() { + return vsysStatus; + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetVServerAttributesResponse.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetVServerAttributesResponse.java index 404cceca87..5f9637c98b 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetVServerAttributesResponse.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetVServerAttributesResponse.java @@ -30,17 +30,17 @@ import org.jclouds.fujitsu.fgcp.domain.VServer; */ @XmlRootElement(name = "GetVServerAttributesResponse") public class GetVServerAttributesResponse extends StatusResponse implements - SingleElementResponse { - @XmlElement(required = true) - private VServer vserver; + SingleElementResponse { + @XmlElement(required = true) + private VServer vserver; - @Override - public String toString() { - return vserver.toString(); - } + @Override + public String toString() { + return vserver.toString(); + } - @Override - public Object getElement() { - return vserver; - } + @Override + public Object getElement() { + return vserver; + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetVServerConfigurationResponse.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetVServerConfigurationResponse.java index f69daa5f12..cebe6ceda1 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetVServerConfigurationResponse.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetVServerConfigurationResponse.java @@ -30,17 +30,17 @@ import org.jclouds.fujitsu.fgcp.domain.VServerWithDetails; */ @XmlRootElement(name = "GetVServerConfigurationResponse") public class GetVServerConfigurationResponse extends StatusResponse implements - SingleElementResponse { - @XmlElement(required = true) - private VServerWithDetails vserver; + SingleElementResponse { + @XmlElement(required = true) + private VServerWithDetails vserver; - @Override - public String toString() { - return vserver.toString(); - } + @Override + public String toString() { + return vserver.toString(); + } - @Override - public Object getElement() { - return vserver; - } + @Override + public Object getElement() { + return vserver; + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetVServerInitialPasswordResponse.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetVServerInitialPasswordResponse.java index f5a1a162f5..39f6ee3797 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetVServerInitialPasswordResponse.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetVServerInitialPasswordResponse.java @@ -28,12 +28,12 @@ import javax.xml.bind.annotation.XmlRootElement; */ @XmlRootElement(name = "GetVServerInitialPasswordResponse") public class GetVServerInitialPasswordResponse extends StatusResponse implements - SingleElementResponse { - @XmlElement(required = true) - private String initialPassword; + SingleElementResponse { + @XmlElement(required = true) + private String initialPassword; - @Override - public Object getElement() { - return initialPassword; - } + @Override + public Object getElement() { + return initialPassword; + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetVServerStatusResponse.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetVServerStatusResponse.java index ea22965525..657c5b6e8f 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetVServerStatusResponse.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/GetVServerStatusResponse.java @@ -30,17 +30,17 @@ import org.jclouds.fujitsu.fgcp.domain.VServerStatus; */ @XmlRootElement(name = "GetVServerStatusResponse") public class GetVServerStatusResponse extends StatusResponse implements - SingleElementResponse { - @XmlElement(required = true) - private VServerStatus vserverStatus; + SingleElementResponse { + @XmlElement(required = true) + private VServerStatus vserverStatus; - @Override - public String toString() { - return getElement().toString(); - } + @Override + public String toString() { + return getElement().toString(); + } - @Override - public Object getElement() { - return vserverStatus; - } + @Override + public Object getElement() { + return vserverStatus; + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/ListDiskImageResponse.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/ListDiskImageResponse.java index 5e19ad697b..339b472b9d 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/ListDiskImageResponse.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/ListDiskImageResponse.java @@ -37,13 +37,13 @@ import com.google.common.collect.ImmutableSet; */ @XmlRootElement(name = "ListDiskImageResponse") public class ListDiskImageResponse extends SetWithStatusResponse { - @XmlElementWrapper(name = "diskimages") - @XmlElement(name = "diskimage") - private Set diskImages = new LinkedHashSet(); + @XmlElementWrapper(name = "diskimages") + @XmlElement(name = "diskimage") + private Set diskImages = new LinkedHashSet(); - @Override - protected Set delegate() { - return diskImages == null ? ImmutableSet. of() : Collections - .unmodifiableSet(diskImages); - } + @Override + protected Set delegate() { + return diskImages == null ? ImmutableSet. of() : Collections + .unmodifiableSet(diskImages); + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/ListEFMBackupResponse.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/ListEFMBackupResponse.java index a9026252a3..2acbfd4141 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/ListEFMBackupResponse.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/ListEFMBackupResponse.java @@ -37,14 +37,14 @@ import com.google.common.collect.ImmutableSet; */ @XmlRootElement(name = "ListEFMBackupResponse") public class ListEFMBackupResponse extends - SetWithStatusResponse { - @XmlElementWrapper(name = "backups") - @XmlElement(name = "backup") - private Set backup = new LinkedHashSet(); + SetWithStatusResponse { + @XmlElementWrapper(name = "backups") + @XmlElement(name = "backup") + private Set backup = new LinkedHashSet(); - @Override - protected Set delegate() { - return backup == null ? ImmutableSet. of() - : Collections.unmodifiableSet(backup); - } + @Override + protected Set delegate() { + return backup == null ? ImmutableSet. of() + : Collections.unmodifiableSet(backup); + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/ListEFMResponse.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/ListEFMResponse.java index 9ebbb1a613..cffa13f681 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/ListEFMResponse.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/ListEFMResponse.java @@ -37,13 +37,13 @@ import com.google.common.collect.ImmutableSet; */ @XmlRootElement(name = "ListEFMResponse") public class ListEFMResponse extends SetWithStatusResponse { - @XmlElementWrapper(name = "efms") - @XmlElement(name = "efm") - private Set efm = new LinkedHashSet(); + @XmlElementWrapper(name = "efms") + @XmlElement(name = "efm") + private Set efm = new LinkedHashSet(); - @Override - protected Set delegate() { - return efm == null ? ImmutableSet. of() : Collections - .unmodifiableSet(efm); - } + @Override + protected Set delegate() { + return efm == null ? ImmutableSet. of() : Collections + .unmodifiableSet(efm); + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/ListPublicIPResponse.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/ListPublicIPResponse.java index 2b6c1a1bf5..6ddfa79126 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/ListPublicIPResponse.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/ListPublicIPResponse.java @@ -39,32 +39,32 @@ import com.google.common.collect.ImmutableSet; */ @XmlRootElement(name = "ListPublicIPResponse") public class ListPublicIPResponse extends - MapWithStatusResponse implements - SingleElementResponse { - @XmlElementWrapper(name = "publicips") - @XmlElement(name = "publicip") - private Set ips; + MapWithStatusResponse implements + SingleElementResponse { + @XmlElementWrapper(name = "publicips") + @XmlElement(name = "publicip") + private Set ips; - @Override - public String toString() { - return getElement().toString(); - } + @Override + public String toString() { + return getElement().toString(); + } - @Override - protected Map delegate() { - Builder returnVal = ImmutableMap.builder(); - if (ips != null) { + @Override + protected Map delegate() { + Builder returnVal = ImmutableMap.builder(); + if (ips != null) { - for (PublicIPWithSystemId ip : ips) { - returnVal.put(ip, ip.getVsysId()); - } - } - return returnVal.build(); - } + for (PublicIPWithSystemId ip : ips) { + returnVal.put(ip, ip.getVsysId()); + } + } + return returnVal.build(); + } - @Override - public Set getElement() { - return ips == null ? ImmutableSet. of() : Collections - .unmodifiableSet(ips); - } + @Override + public Set getElement() { + return ips == null ? ImmutableSet. of() : Collections + .unmodifiableSet(ips); + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/ListServerTypeResponse.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/ListServerTypeResponse.java index 6d1e49e2ee..c10b0c8120 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/ListServerTypeResponse.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/ListServerTypeResponse.java @@ -36,13 +36,13 @@ import com.google.common.collect.ImmutableSet; */ @XmlRootElement(name = "ListServerTypeResponse") public class ListServerTypeResponse extends SetWithStatusResponse { - @XmlElementWrapper(name = "servertypes") - @XmlElement(name = "servertype") - private Set serverTypes; + @XmlElementWrapper(name = "servertypes") + @XmlElement(name = "servertype") + private Set serverTypes; - @Override - protected Set delegate() { - return serverTypes == null ? ImmutableSet. of() - : Collections.unmodifiableSet(serverTypes); - } + @Override + protected Set delegate() { + return serverTypes == null ? ImmutableSet. of() + : Collections.unmodifiableSet(serverTypes); + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/ListVDiskResponse.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/ListVDiskResponse.java index 0489a93042..3be8d5d6ea 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/ListVDiskResponse.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/ListVDiskResponse.java @@ -37,13 +37,13 @@ import com.google.common.collect.ImmutableSet; */ @XmlRootElement(name = "ListVDiskResponse") public class ListVDiskResponse extends SetWithStatusResponse { - @XmlElementWrapper(name = "vdisks") - @XmlElement(name = "vdisk") - private Set disks = new LinkedHashSet(); + @XmlElementWrapper(name = "vdisks") + @XmlElement(name = "vdisk") + private Set disks = new LinkedHashSet(); - @Override - protected Set delegate() { - return disks == null ? ImmutableSet. of() : Collections - .unmodifiableSet(disks); - } + @Override + protected Set delegate() { + return disks == null ? ImmutableSet. of() : Collections + .unmodifiableSet(disks); + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/ListVSYSResponse.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/ListVSYSResponse.java index 90826f63da..0cce1b252e 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/ListVSYSResponse.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/ListVSYSResponse.java @@ -37,13 +37,13 @@ import com.google.common.collect.ImmutableSet; */ @XmlRootElement(name = "ListVSYSResponse") public class ListVSYSResponse extends SetWithStatusResponse { - @XmlElementWrapper(name = "vsyss") - @XmlElement(name = "vsys") - private Set systems = new LinkedHashSet(); + @XmlElementWrapper(name = "vsyss") + @XmlElement(name = "vsys") + private Set systems = new LinkedHashSet(); - @Override - protected Set delegate() { - return systems == null ? ImmutableSet. of() : Collections - .unmodifiableSet(systems); - } + @Override + protected Set delegate() { + return systems == null ? ImmutableSet. of() : Collections + .unmodifiableSet(systems); + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/ListVServerResponse.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/ListVServerResponse.java index 802a779ba1..2d8dc4e161 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/ListVServerResponse.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/ListVServerResponse.java @@ -37,13 +37,13 @@ import com.google.common.collect.ImmutableSet; */ @XmlRootElement(name = "ListVServerResponse") public class ListVServerResponse extends SetWithStatusResponse { - @XmlElementWrapper(name = "vservers") - @XmlElement(name = "vserver") - private Set servers = new LinkedHashSet(); + @XmlElementWrapper(name = "vservers") + @XmlElement(name = "vserver") + private Set servers = new LinkedHashSet(); - @Override - protected Set delegate() { - return servers == null ? ImmutableSet. of() : Collections - .unmodifiableSet(servers); - } + @Override + protected Set delegate() { + return servers == null ? ImmutableSet. of() : Collections + .unmodifiableSet(servers); + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/MapWithStatusResponse.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/MapWithStatusResponse.java index ffc54303a4..e0f841ae87 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/MapWithStatusResponse.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/MapWithStatusResponse.java @@ -18,10 +18,10 @@ */ package org.jclouds.fujitsu.fgcp.xml.internal; -import com.google.common.collect.ForwardingMap; - import javax.xml.bind.annotation.XmlElement; +import com.google.common.collect.ForwardingMap; + /** * Special base class extending (forwardable) Map with fields for the elements * that FGCP XML responses specify. @@ -32,27 +32,27 @@ import javax.xml.bind.annotation.XmlElement; * @author Dies Koper */ public abstract class MapWithStatusResponse extends ForwardingMap - implements StatusQuerable { - @XmlElement(required = true) - private String responseMessage; - @XmlElement(required = true) - private String responseStatus; + implements StatusQuerable { + @XmlElement(required = true) + private String responseMessage; + @XmlElement(required = true) + private String responseStatus; - public String getResponseMessage() { - return responseMessage; - } + public String getResponseMessage() { + return responseMessage; + } - public String getResponseStatus() { - return responseStatus; - } + public String getResponseStatus() { + return responseStatus; + } - public boolean isError() { - return !"SUCCESS".equals(responseStatus); - } + public boolean isError() { + return !"SUCCESS".equals(responseStatus); + } - @Override - public String toString() { - return "StatusResponse{" + "responseMessage='" + responseMessage + '\'' - + ", responseStatus='" + responseStatus + '\'' + '}'; - } + @Override + public String toString() { + return "StatusResponse{" + "responseMessage='" + responseMessage + '\'' + + ", responseStatus='" + responseStatus + '\'' + '}'; + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/PublicIPWithSystemId.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/PublicIPWithSystemId.java index fd9f18cb30..6995541d50 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/PublicIPWithSystemId.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/PublicIPWithSystemId.java @@ -29,15 +29,15 @@ import org.jclouds.fujitsu.fgcp.domain.PublicIP; */ @XmlRootElement(name = "publicip") public class PublicIPWithSystemId extends PublicIP { - private String vsysId; + private String vsysId; - public String getVsysId() { - return vsysId; - } + public String getVsysId() { + return vsysId; + } - @Override - public String toString() { - return "PublicIP{" + "address='" + address + '\'' + ", IP version='" - + version + '\'' + ", vsysId='" + vsysId + '\'' + '}'; - } + @Override + public String toString() { + return "PublicIP{" + "address='" + address + '\'' + ", IP version='" + + version + '\'' + ", vsysId='" + vsysId + '\'' + '}'; + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/SetWithStatusResponse.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/SetWithStatusResponse.java index bb7158f10b..6ee4e7c8f0 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/SetWithStatusResponse.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/SetWithStatusResponse.java @@ -18,10 +18,10 @@ */ package org.jclouds.fujitsu.fgcp.xml.internal; -import com.google.common.collect.ForwardingSet; - import javax.xml.bind.annotation.XmlElement; +import com.google.common.collect.ForwardingSet; + /** * Special base class extending (forwardable) Set with fields for the elements * that FGCP XML responses specify. @@ -32,27 +32,27 @@ import javax.xml.bind.annotation.XmlElement; * @author Dies Koper */ public abstract class SetWithStatusResponse extends ForwardingSet - implements StatusQuerable { - @XmlElement(required = true) - private String responseMessage; - @XmlElement(required = true) - private String responseStatus; + implements StatusQuerable { + @XmlElement(required = true) + private String responseMessage; + @XmlElement(required = true) + private String responseStatus; - public String getResponseMessage() { - return responseMessage; - } + public String getResponseMessage() { + return responseMessage; + } - public String getResponseStatus() { - return responseStatus; - } + public String getResponseStatus() { + return responseStatus; + } - public boolean isError() { - return !"SUCCESS".equals(responseStatus); - } + public boolean isError() { + return !"SUCCESS".equals(responseStatus); + } - @Override - public String toString() { - return delegate().toString(); - } + @Override + public String toString() { + return delegate().toString(); + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/SingleElementResponse.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/SingleElementResponse.java index 759586fe98..4ced6da144 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/SingleElementResponse.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/SingleElementResponse.java @@ -25,5 +25,5 @@ package org.jclouds.fujitsu.fgcp.xml.internal; */ public interface SingleElementResponse { - Object getElement(); + Object getElement(); } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/StatusQuerable.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/StatusQuerable.java index 9046c68720..5a83701844 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/StatusQuerable.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/StatusQuerable.java @@ -24,9 +24,9 @@ package org.jclouds.fujitsu.fgcp.xml.internal; * @author Dies Koper */ public interface StatusQuerable { - public String getResponseMessage(); + public String getResponseMessage(); - public String getResponseStatus(); + public String getResponseStatus(); - public boolean isError(); + public boolean isError(); } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/StatusResponse.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/StatusResponse.java index 7ea3361de3..d9d7f06126 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/StatusResponse.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/StatusResponse.java @@ -19,7 +19,6 @@ package org.jclouds.fujitsu.fgcp.xml.internal; import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; /** * Base class with fields for the elements that FGCP XML responses specify. @@ -27,34 +26,34 @@ import javax.xml.bind.annotation.XmlRootElement; * @author Dies Koper */ public abstract class StatusResponse implements StatusQuerable { - @XmlElement(required = true) - private String responseMessage; - @XmlElement(required = true) - private String responseStatus; + @XmlElement(required = true) + private String responseMessage; + @XmlElement(required = true) + private String responseStatus; - public String getResponseMessage() { - return responseMessage; - } + public String getResponseMessage() { + return responseMessage; + } - public void setResponseMessage(String responseMessage) { - this.responseMessage = responseMessage; - } + public void setResponseMessage(String responseMessage) { + this.responseMessage = responseMessage; + } - public String getResponseStatus() { - return responseStatus; - } + public String getResponseStatus() { + return responseStatus; + } - public void setResponseStatus(String responseStatus) { - this.responseStatus = responseStatus; - } + public void setResponseStatus(String responseStatus) { + this.responseStatus = responseStatus; + } - public boolean isError() { - return !"SUCCESS".equals(responseStatus); - } + public boolean isError() { + return !"SUCCESS".equals(responseStatus); + } - @Override - public String toString() { - return "StatusResponse{" + "responseMessage='" + responseMessage + '\'' - + ", responseStatus='" + responseStatus + '\'' + '}'; - } + @Override + public String toString() { + return "StatusResponse{" + "responseMessage='" + responseMessage + '\'' + + ", responseStatus='" + responseStatus + '\'' + '}'; + } } diff --git a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/package-info.java b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/package-info.java index 12b705bccc..1347685ce9 100644 --- a/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/package-info.java +++ b/labs/fgcp/src/main/java/org/jclouds/fujitsu/fgcp/xml/internal/package-info.java @@ -22,7 +22,7 @@ @XmlAccessorType(XmlAccessType.FIELD) package org.jclouds.fujitsu.fgcp.xml.internal; -import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlSchema; diff --git a/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/compute/FGCPBaseTemplateBuilderLiveTest.java b/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/compute/FGCPBaseTemplateBuilderLiveTest.java index 54388cdaf3..66da95ebd1 100644 --- a/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/compute/FGCPBaseTemplateBuilderLiveTest.java +++ b/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/compute/FGCPBaseTemplateBuilderLiveTest.java @@ -16,69 +16,69 @@ import com.google.common.base.Predicate; import com.google.common.base.Predicates; public abstract class FGCPBaseTemplateBuilderLiveTest extends - BaseTemplateBuilderLiveTest { + BaseTemplateBuilderLiveTest { - @Override - protected Properties setupProperties() { - Properties overrides = super.setupProperties(); + @Override + protected Properties setupProperties() { + Properties overrides = super.setupProperties(); - String proxy = System.getenv("http_proxy"); - if (proxy != null) { + String proxy = System.getenv("http_proxy"); + if (proxy != null) { - String[] parts = proxy.split("http://|:|@"); + String[] parts = proxy.split("http://|:|@"); - overrides.setProperty(Constants.PROPERTY_PROXY_HOST, - parts[parts.length - 2]); - overrides.setProperty(Constants.PROPERTY_PROXY_PORT, - parts[parts.length - 1]); + overrides.setProperty(Constants.PROPERTY_PROXY_HOST, + parts[parts.length - 2]); + overrides.setProperty(Constants.PROPERTY_PROXY_PORT, + parts[parts.length - 1]); - if (parts.length >= 4) { - overrides.setProperty(Constants.PROPERTY_PROXY_USER, - parts[parts.length - 4]); - overrides.setProperty(Constants.PROPERTY_PROXY_PASSWORD, - parts[parts.length - 3]); + if (parts.length >= 4) { + overrides.setProperty(Constants.PROPERTY_PROXY_USER, + parts[parts.length - 4]); + overrides.setProperty(Constants.PROPERTY_PROXY_PASSWORD, + parts[parts.length - 3]); + } + } + + // enables peer verification using the CAs bundled with the JRE (or + // value of javax.net.ssl.trustStore if set) + overrides.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, "false"); + + return overrides; + } + + @Override + protected Predicate defineUnsupportedOperatingSystems() { + return Predicates.not(new Predicate() { + + @Override + public boolean apply(OsFamilyVersion64Bit input) { + switch (input.family) { + case CENTOS: + return input.version.matches("5.[46]") + || input.version.equals("6.[2]"); + case WINDOWS: + return (input.version.equals("2008 R2 SE") || input.version + .equals("2008 R2 EE")) && input.is64Bit; + default: + return false; } - } + } - // enables peer verification using the CAs bundled with the JRE (or - // value of javax.net.ssl.trustStore if set) - overrides.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, "false"); + }); + } - return overrides; - } - - @Override - protected Predicate defineUnsupportedOperatingSystems() { - return Predicates.not(new Predicate() { - - @Override - public boolean apply(OsFamilyVersion64Bit input) { - switch (input.family) { - case CENTOS: - return input.version.matches("5.[46]") - || input.version.equals("6.[2]"); - case WINDOWS: - return (input.version.equals("2008 R2 SE") || input.version - .equals("2008 R2 EE")) && input.is64Bit; - default: - return false; - } - } - - }); - } - - public void testDefaultTemplateBuilder() throws IOException { - Template defaultTemplate = view.getComputeService().templateBuilder() - .build(); - assert defaultTemplate.getImage().getOperatingSystem().getVersion() - .matches("6.2") : defaultTemplate.getImage() - .getOperatingSystem().getVersion(); - assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), - true); - assertEquals(defaultTemplate.getImage().getOperatingSystem() - .getFamily(), OsFamily.CENTOS); - assertEquals(getCores(defaultTemplate.getHardware()), 1.0d); - } + public void testDefaultTemplateBuilder() throws IOException { + Template defaultTemplate = view.getComputeService().templateBuilder() + .build(); + assert defaultTemplate.getImage().getOperatingSystem().getVersion() + .matches("6.2") : defaultTemplate.getImage() + .getOperatingSystem().getVersion(); + assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), + true); + assertEquals(defaultTemplate.getImage().getOperatingSystem() + .getFamily(), OsFamily.CENTOS); + assertEquals(getCores(defaultTemplate.getHardware()), 1.0d); + } } \ No newline at end of file diff --git a/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/compute/FGCPRestClientModuleTest.java b/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/compute/FGCPRestClientModuleTest.java index 9c1c8804ce..2706e97ca4 100644 --- a/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/compute/FGCPRestClientModuleTest.java +++ b/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/compute/FGCPRestClientModuleTest.java @@ -18,15 +18,8 @@ */ package org.jclouds.fujitsu.fgcp.compute; -import com.google.inject.Guice; -import com.google.inject.Injector; -import org.jclouds.crypto.Crypto; -import org.jclouds.fujitsu.fgcp.FGCPApiMetadata; +import static org.testng.Assert.assertNotNull; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.Test; - -import java.io.File; import java.io.IOException; import java.net.URL; import java.security.KeyStore; @@ -34,9 +27,13 @@ import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.spec.InvalidKeySpecException; -import java.util.Scanner; -import static org.testng.Assert.*; +import org.jclouds.crypto.Crypto; +import org.testng.annotations.BeforeTest; +import org.testng.annotations.Test; + +import com.google.inject.Guice; +import com.google.inject.Injector; /** * @author Dies Koper @@ -44,55 +41,55 @@ import static org.testng.Assert.*; @Test(groups = "unit", testName = "FGCPRestClientModuleTest") public class FGCPRestClientModuleTest { - protected FGCPRestClientModule module; - protected Crypto crypto; + protected FGCPRestClientModule module; + protected Crypto crypto; - @BeforeTest - protected void createCrypto() { - Injector i = Guice.createInjector(); - crypto = i.getInstance(Crypto.class); - } + @BeforeTest + protected void createCrypto() { + Injector i = Guice.createInjector(); + crypto = i.getInstance(Crypto.class); + } - @BeforeTest - protected void createRestClientModule() { - Injector i = Guice.createInjector(); - module = i.getInstance(FGCPRestClientModule.class); - } + @BeforeTest + protected void createRestClientModule() { + Injector i = Guice.createInjector(); + module = i.getInstance(FGCPRestClientModule.class); + } - public void testKeyStoreAsPkcs12() throws IOException, InvalidKeySpecException, NoSuchAlgorithmException, KeyStoreException, CertificateException { - assertNotNull(crypto); - assertNotNull(module); + public void testKeyStoreAsPkcs12() throws IOException, InvalidKeySpecException, NoSuchAlgorithmException, KeyStoreException, CertificateException { + assertNotNull(crypto); + assertNotNull(module); - // self-signed dummy cert: - // keytool -genkey -alias test-fgcp -keyalg RSA -keysize 1024 -validity 5475 -dname "CN=localhost" -keystore jclouds-test-fgcp.p12 -storepass jcloudsjclouds -storetype pkcs12 - String cert = "/certs/jclouds-test-fgcp.p12"; - String keyPassword = "jcloudsjclouds"; + // self-signed dummy cert: + // keytool -genkey -alias test-fgcp -keyalg RSA -keysize 1024 -validity 5475 -dname "CN=localhost" -keystore jclouds-test-fgcp.p12 -storepass jcloudsjclouds -storetype pkcs12 + String cert = "/certs/jclouds-test-fgcp.p12"; + String keyPassword = "jcloudsjclouds"; - URL url = this.getClass().getResource(cert); - String certPath = url.getFile(); + URL url = this.getClass().getResource(cert); + String certPath = url.getFile(); - KeyStore ks = module.provideKeyStore(crypto, certPath, keyPassword); + KeyStore ks = module.provideKeyStore(crypto, certPath, keyPassword); - assertNotNull(ks.getCertificate("test-fgcp"), "cert with alias"); - } + assertNotNull(ks.getCertificate("test-fgcp"), "cert with alias"); + } -/* public void testKeyStoreAsPEM() throws IOException, InvalidKeySpecException, NoSuchAlgorithmException, KeyStoreException, CertificateException { - assertNotNull(crypto); - assertNotNull(module); +/* public void testKeyStoreAsPEM() throws IOException, InvalidKeySpecException, NoSuchAlgorithmException, KeyStoreException, CertificateException { + assertNotNull(crypto); + assertNotNull(module); - //openssl pkcs12 -nodes -in jclouds-test-fgcp.p12 -out jclouds-test-fgcp.pem -// String privKeyFilename = "D:\\UserCert.pem.pkcs12-nodes";//_nobags"; - String cert = "/certs/jclouds-test-fgcp.pem"; - String keyPassword = "jcloudsjclouds"; + //openssl pkcs12 -nodes -in jclouds-test-fgcp.p12 -out jclouds-test-fgcp.pem +// String privKeyFilename = "D:\\UserCert.pem.pkcs12-nodes";//_nobags"; + String cert = "/certs/jclouds-test-fgcp.pem"; + String keyPassword = "jcloudsjclouds"; - URL url = this.getClass().getResource(cert); - String certPath = url.getFile(); - Scanner scanner = new Scanner(new File(certPath)); - String content = scanner.useDelimiter("\\A").next(); + URL url = this.getClass().getResource(cert); + String certPath = url.getFile(); + Scanner scanner = new Scanner(new File(certPath)); + String content = scanner.useDelimiter("\\A").next(); - KeyStore ks = module.provideKeyStore(crypto, content, keyPassword); + KeyStore ks = module.provideKeyStore(crypto, content, keyPassword); - assertNotNull(ks.getCertificate("test-fgcp"), "cert with alias"); - } + assertNotNull(ks.getCertificate("test-fgcp"), "cert with alias"); + } */ } diff --git a/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/compute/config/FGCPBaseComputeServiceLiveTest.java b/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/compute/config/FGCPBaseComputeServiceLiveTest.java index 996965b12c..c51c2dcd6f 100644 --- a/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/compute/config/FGCPBaseComputeServiceLiveTest.java +++ b/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/compute/config/FGCPBaseComputeServiceLiveTest.java @@ -15,173 +15,173 @@ import com.google.common.collect.ImmutableSet; import com.google.inject.Module; public abstract class FGCPBaseComputeServiceLiveTest extends - BaseComputeServiceLiveTest { + BaseComputeServiceLiveTest { - @Override - protected Properties setupProperties() { - Properties overrides = super.setupProperties(); - - String proxy = System.getenv("http_proxy"); - if (proxy != null) { - - String[] parts = proxy.split("http://|:|@"); - - overrides.setProperty(Constants.PROPERTY_PROXY_HOST, parts[parts.length - 2]); - overrides.setProperty(Constants.PROPERTY_PROXY_PORT, parts[parts.length - 1]); - - if (parts.length >= 4) { - overrides.setProperty(Constants.PROPERTY_PROXY_USER, parts[parts.length - 4]); - overrides.setProperty(Constants.PROPERTY_PROXY_PASSWORD, parts[parts.length - 3]); - } - } - - // enables peer verification using the CAs bundled with the JRE (or - // value of javax.net.ssl.trustStore if set) - overrides.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, "false"); - - return overrides; + @Override + protected Properties setupProperties() { + Properties overrides = super.setupProperties(); + + String proxy = System.getenv("http_proxy"); + if (proxy != null) { + + String[] parts = proxy.split("http://|:|@"); + + overrides.setProperty(Constants.PROPERTY_PROXY_HOST, parts[parts.length - 2]); + overrides.setProperty(Constants.PROPERTY_PROXY_PORT, parts[parts.length - 1]); + + if (parts.length >= 4) { + overrides.setProperty(Constants.PROPERTY_PROXY_USER, parts[parts.length - 4]); + overrides.setProperty(Constants.PROPERTY_PROXY_PASSWORD, parts[parts.length - 3]); + } + } + + // enables peer verification using the CAs bundled with the JRE (or + // value of javax.net.ssl.trustStore if set) + overrides.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, "false"); + + return overrides; + } + + @Override + protected Module getSshModule() { + return new SshjSshClientModule(); + } + + @Override + @Test(enabled = false, expectedExceptions = AuthorizationException.class) + public void testCorrectAuthException() throws Exception { + // http://code.google.com/p/jclouds/issues/detail?id=1060 + } + + // fgcp does not support metadata + @Override + protected void checkUserMetadataInNodeEquals(NodeMetadata node, ImmutableMap userMetadata) { + assert node.getUserMetadata().isEmpty() : String.format( + "node userMetadata not empty: %s %s", node, + node.getUserMetadata()); } - @Override - protected Module getSshModule() { - return new SshjSshClientModule(); - } + // node name can't be retrieved through the API and is therefore null + protected void checkResponseEqualsHostname(ExecResponse execResponse, + NodeMetadata node) { + assert node.getHostname() == null : node + " with hostname: " + + node.getHostname(); + } - @Override - @Test(enabled = false, expectedExceptions = AuthorizationException.class) - public void testCorrectAuthException() throws Exception { - // http://code.google.com/p/jclouds/issues/detail?id=1060 - } + // tags are not (yet) supported for fgcp + protected void checkTagsInNodeEquals(NodeMetadata node, + ImmutableSet tags) { + assert node.getTags().isEmpty() : String.format( + "node tags found %s (%s) in node %s", node.getTags(), tags, node); + } - // fgcp does not support metadata - @Override - protected void checkUserMetadataInNodeEquals(NodeMetadata node, ImmutableMap userMetadata) { - assert node.getUserMetadata().isEmpty() : String.format( - "node userMetadata not empty: %s %s", node, - node.getUserMetadata()); - } + /* + * public void testCreateAndRunAService() throws Exception { + * super.testCreateAndRunAService(); } + */ - // node name can't be retrieved through the API and is therefore null - protected void checkResponseEqualsHostname(ExecResponse execResponse, - NodeMetadata node) { - assert node.getHostname() == null : node + " with hostname: " - + node.getHostname(); - } + // this test requires network access to the VM it creates: + // before running it, start an SSL/VPN connection to the last updated vsys' + // DMZ. + // may also need to configure SNAT and FW rules to allow the VM to + // communicate out (53 for DNS, 80 for yum). + public void testAScriptExecutionAfterBootWithBasicTemplate() + throws Exception { + super.testAScriptExecutionAfterBootWithBasicTemplate(); + } - // tags are not (yet) supported for fgcp - protected void checkTagsInNodeEquals(NodeMetadata node, - ImmutableSet tags) { - assert node.getTags().isEmpty() : String.format( - "node tags found %s (%s) in node %s", node.getTags(), tags, node); - } + @Override + @Test(enabled = false) + public void testOptionToNotBlock() throws Exception { + // start call returns before node reaches running state, but + // test may be failing due to the system being in a 're-configuring' + // state while destroying nodes of a previous test. + // http://code.google.com/p/jclouds/issues/detail?id=1066 + /* + org.jclouds.compute.RunNodesException: error running 1 node group(fgcp-aublock) location(UZXC0GRT-IZKDVGIL5-N-SECURE1) image(IMG_3c9820_71OW9NZC268) size(islanda-cbrm_140) options({inboundPorts=[], blockUntilRunning=false}) + Execution failures: + + 1) ExecutionException on fgcp-aublock-787: + java.util.concurrent.ExecutionException: java.lang.IllegalStateException: The status of Instance[UZXC0GRT-IZKDVGIL5] is [RECONFIG_ING]. + at com.google.common.util.concurrent.AbstractFuture$Sync.getValue(AbstractFuture.java:289) + at com.google.common.util.concurrent.AbstractFuture$Sync.get(AbstractFuture.java:276) + at com.google.common.util.concurrent.AbstractFuture.get(AbstractFuture.java:111) + at org.jclouds.concurrent.FutureIterables$1.run(FutureIterables.java:134) + at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source) + at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) + at java.lang.Thread.run(Unknown Source) + Caused by: java.lang.IllegalStateException: The status of Instance[UZXC0GRT-IZKDVGIL5] is [RECONFIG_ING]. + at org.jclouds.fujitsu.fgcp.xml.FGCPJAXBParser.fromXML(FGCPJAXBParser.java:75) + at org.jclouds.http.functions.ParseXMLWithJAXB.apply(ParseXMLWithJAXB.java:91) + at org.jclouds.http.functions.ParseXMLWithJAXB.apply(ParseXMLWithJAXB.java:86) + at org.jclouds.http.functions.ParseXMLWithJAXB.apply(ParseXMLWithJAXB.java:73) + at org.jclouds.http.functions.ParseXMLWithJAXB.apply(ParseXMLWithJAXB.java:54) + at com.google.common.base.Functions$FunctionComposition.apply(Functions.java:209) + at com.google.common.util.concurrent.Futures$3.apply(Futures.java:380) + at com.google.common.util.concurrent.Futures$ChainingListenableFuture.run(Futures.java:522) + at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source) + at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) + at java.lang.Thread.run(Unknown Source) + at org.jclouds.concurrent.config.DescribingExecutorService.submit(DescribingExecutorService.java:89) + at org.jclouds.compute.strategy.impl.CreateNodesWithGroupEncodedIntoNameThenAddToSet.createNodeInGroupWithNameAndTemplate(CreateNodesWithGroupEncodedIntoNameThenAddToSet.java:170) + at org.jclouds.compute.strategy.impl.CreateNodesWithGroupEncodedIntoNameThenAddToSet.execute(CreateNodesWithGroupEncodedIntoNameThenAddToSet.java:125) + at org.jclouds.compute.internal.BaseComputeService.createNodesInGroup(BaseComputeService.java:213) + at org.jclouds.compute.internal.BaseComputeService.createNodesInGroup(BaseComputeService.java:229) + at org.jclouds.compute.internal.BaseComputeServiceLiveTest.testOptionToNotBlock(BaseComputeServiceLiveTest.java:803) + */ + } - /* - * public void testCreateAndRunAService() throws Exception { - * super.testCreateAndRunAService(); } - */ +/* @Override + @Test(enabled = false) + public void testCreateTwoNodesWithRunScript() { + } - // this test requires network access to the VM it creates: - // before running it, start an SSL/VPN connection to the last updated vsys' - // DMZ. - // may also need to configure SNAT and FW rules to allow the VM to - // communicate out (53 for DNS, 80 for yum). - public void testAScriptExecutionAfterBootWithBasicTemplate() - throws Exception { - super.testAScriptExecutionAfterBootWithBasicTemplate(); - } + @Override + @Test(enabled = false) + public void testCreateAnotherNodeWithANewContextToEnsureSharedMemIsntRequired() { + } - @Override - @Test(enabled = false) - public void testOptionToNotBlock() throws Exception { - // start call returns before node reaches running state, but - // test may be failing due to the system being in a 're-configuring' - // state while destroying nodes of a previous test. - // http://code.google.com/p/jclouds/issues/detail?id=1066 - /* - org.jclouds.compute.RunNodesException: error running 1 node group(fgcp-aublock) location(UZXC0GRT-IZKDVGIL5-N-SECURE1) image(IMG_3c9820_71OW9NZC268) size(islanda-cbrm_140) options({inboundPorts=[], blockUntilRunning=false}) - Execution failures: - - 1) ExecutionException on fgcp-aublock-787: - java.util.concurrent.ExecutionException: java.lang.IllegalStateException: The status of Instance[UZXC0GRT-IZKDVGIL5] is [RECONFIG_ING]. - at com.google.common.util.concurrent.AbstractFuture$Sync.getValue(AbstractFuture.java:289) - at com.google.common.util.concurrent.AbstractFuture$Sync.get(AbstractFuture.java:276) - at com.google.common.util.concurrent.AbstractFuture.get(AbstractFuture.java:111) - at org.jclouds.concurrent.FutureIterables$1.run(FutureIterables.java:134) - at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) - at java.lang.Thread.run(Unknown Source) - Caused by: java.lang.IllegalStateException: The status of Instance[UZXC0GRT-IZKDVGIL5] is [RECONFIG_ING]. - at org.jclouds.fujitsu.fgcp.xml.FGCPJAXBParser.fromXML(FGCPJAXBParser.java:75) - at org.jclouds.http.functions.ParseXMLWithJAXB.apply(ParseXMLWithJAXB.java:91) - at org.jclouds.http.functions.ParseXMLWithJAXB.apply(ParseXMLWithJAXB.java:86) - at org.jclouds.http.functions.ParseXMLWithJAXB.apply(ParseXMLWithJAXB.java:73) - at org.jclouds.http.functions.ParseXMLWithJAXB.apply(ParseXMLWithJAXB.java:54) - at com.google.common.base.Functions$FunctionComposition.apply(Functions.java:209) - at com.google.common.util.concurrent.Futures$3.apply(Futures.java:380) - at com.google.common.util.concurrent.Futures$ChainingListenableFuture.run(Futures.java:522) - at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) - at java.lang.Thread.run(Unknown Source) - at org.jclouds.concurrent.config.DescribingExecutorService.submit(DescribingExecutorService.java:89) - at org.jclouds.compute.strategy.impl.CreateNodesWithGroupEncodedIntoNameThenAddToSet.createNodeInGroupWithNameAndTemplate(CreateNodesWithGroupEncodedIntoNameThenAddToSet.java:170) - at org.jclouds.compute.strategy.impl.CreateNodesWithGroupEncodedIntoNameThenAddToSet.execute(CreateNodesWithGroupEncodedIntoNameThenAddToSet.java:125) - at org.jclouds.compute.internal.BaseComputeService.createNodesInGroup(BaseComputeService.java:213) - at org.jclouds.compute.internal.BaseComputeService.createNodesInGroup(BaseComputeService.java:229) - at org.jclouds.compute.internal.BaseComputeServiceLiveTest.testOptionToNotBlock(BaseComputeServiceLiveTest.java:803) - */ - } - -/* @Override - @Test(enabled = false) - public void testCreateTwoNodesWithRunScript() { - } - - @Override - @Test(enabled = false) - public void testCreateAnotherNodeWithANewContextToEnsureSharedMemIsntRequired() { - } - - @Override - @Test(enabled = false) - public void testGet() { - } + @Override + @Test(enabled = false) + public void testGet() { + } */ -// @Override -// @Test(enabled = false) -// public void testConcurrentUseOfComputeServiceToCreateNodes() throws Exception { - // http://code.google.com/p/jclouds/issues/detail?id=1066 - /* - 1) ExecutionException on twin0-f6a: - java.util.concurrent.ExecutionException: org.jclouds.http.HttpResponseException: Error parsing input - {statusCode=200, message=OK, headers={Date=[Sun, 26 Aug 2012 01:22:50 GMT], Transfer-Encoding=[chunked], Set-Cookie=[JSESSIONID=8A07404DF0405E46B3A748C3763B0D9F; Path=/ovisspxy; Secure], Connection=[close]}, payload=[content=true, contentMetadata=[contentDisposition=null, contentEncoding=null, contentLanguage=null, contentLength=null, contentMD5=null, contentType=text/xml;charset=UTF-8, expires=null], written=false]} - at com.google.common.util.concurrent.AbstractFuture$Sync.getValue(AbstractFuture.java:289) - at com.google.common.util.concurrent.AbstractFuture$Sync.get(AbstractFuture.java:276) - at com.google.common.util.concurrent.AbstractFuture.get(AbstractFuture.java:111) - at org.jclouds.concurrent.FutureIterables$1.run(FutureIterables.java:134) - at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) - at java.lang.Thread.run(Unknown Source) - Caused by: org.jclouds.http.HttpResponseException: Error parsing input - {statusCode=200, message=OK, headers={Date=[Sun, 26 Aug 2012 01:22:50 GMT], Transfer-Encoding=[chunked], Set-Cookie=[JSESSIONID=8A07404DF0405E46B3A748C3763B0D9F; Path=/ovisspxy; Secure], Connection=[close]}, payload=[content=true, contentMetadata=[contentDisposition=null, contentEncoding=null, contentLanguage=null, contentLength=null, contentMD5=null, contentType=text/xml;charset=UTF-8, expires=null], written=false]} - at org.jclouds.http.functions.ParseXMLWithJAXB.apply(ParseXMLWithJAXB.java:78) - at org.jclouds.http.functions.ParseXMLWithJAXB.apply(ParseXMLWithJAXB.java:1) - at com.google.common.base.Functions$FunctionComposition.apply(Functions.java:209) - at com.google.common.util.concurrent.Futures$3.apply(Futures.java:380) - at com.google.common.util.concurrent.Futures$ChainingListenableFuture.run(Futures.java:522) - at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source) - at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) - at java.lang.Thread.run(Unknown Source) - at org.jclouds.concurrent.config.DescribingExecutorService.submit(DescribingExecutorService.java:89) - at org.jclouds.compute.strategy.impl.CreateNodesWithGroupEncodedIntoNameThenAddToSet.createNodeInGroupWithNameAndTemplate(CreateNodesWithGroupEncodedIntoNameThenAddToSet.java:170) - at org.jclouds.compute.strategy.impl.CreateNodesWithGroupEncodedIntoNameThenAddToSet.execute(CreateNodesWithGroupEncodedIntoNameThenAddToSet.java:125) - at org.jclouds.compute.internal.BaseComputeService.createNodesInGroup(BaseComputeService.java:213) - at org.jclouds.compute.internal.BaseComputeService.createNodesInGroup(BaseComputeService.java:229) - at org.jclouds.compute.internal.BaseComputeServiceLiveTest$1.call(BaseComputeServiceLiveTest.java:442) - at org.jclouds.compute.internal.BaseComputeServiceLiveTest$1.call(BaseComputeServiceLiveTest.java:1) - ... 3 more - Caused by: org.jclouds.http.HttpException: The status of Instance[UZXC0GRT-9Q988189J] is [RECONFIG_ING]. - at org.jclouds.fujitsu.fgcp.xml.FGCPJAXBParser.fromXML(FGCPJAXBParser.java:81) - at org.jclouds.http.functions.ParseXMLWithJAXB.apply(ParseXMLWithJAXB.java:91) -*/ -// } +// @Override +// @Test(enabled = false) +// public void testConcurrentUseOfComputeServiceToCreateNodes() throws Exception { + // http://code.google.com/p/jclouds/issues/detail?id=1066 + /* + 1) ExecutionException on twin0-f6a: + java.util.concurrent.ExecutionException: org.jclouds.http.HttpResponseException: Error parsing input + {statusCode=200, message=OK, headers={Date=[Sun, 26 Aug 2012 01:22:50 GMT], Transfer-Encoding=[chunked], Set-Cookie=[JSESSIONID=8A07404DF0405E46B3A748C3763B0D9F; Path=/ovisspxy; Secure], Connection=[close]}, payload=[content=true, contentMetadata=[contentDisposition=null, contentEncoding=null, contentLanguage=null, contentLength=null, contentMD5=null, contentType=text/xml;charset=UTF-8, expires=null], written=false]} + at com.google.common.util.concurrent.AbstractFuture$Sync.getValue(AbstractFuture.java:289) + at com.google.common.util.concurrent.AbstractFuture$Sync.get(AbstractFuture.java:276) + at com.google.common.util.concurrent.AbstractFuture.get(AbstractFuture.java:111) + at org.jclouds.concurrent.FutureIterables$1.run(FutureIterables.java:134) + at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source) + at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) + at java.lang.Thread.run(Unknown Source) + Caused by: org.jclouds.http.HttpResponseException: Error parsing input + {statusCode=200, message=OK, headers={Date=[Sun, 26 Aug 2012 01:22:50 GMT], Transfer-Encoding=[chunked], Set-Cookie=[JSESSIONID=8A07404DF0405E46B3A748C3763B0D9F; Path=/ovisspxy; Secure], Connection=[close]}, payload=[content=true, contentMetadata=[contentDisposition=null, contentEncoding=null, contentLanguage=null, contentLength=null, contentMD5=null, contentType=text/xml;charset=UTF-8, expires=null], written=false]} + at org.jclouds.http.functions.ParseXMLWithJAXB.apply(ParseXMLWithJAXB.java:78) + at org.jclouds.http.functions.ParseXMLWithJAXB.apply(ParseXMLWithJAXB.java:1) + at com.google.common.base.Functions$FunctionComposition.apply(Functions.java:209) + at com.google.common.util.concurrent.Futures$3.apply(Futures.java:380) + at com.google.common.util.concurrent.Futures$ChainingListenableFuture.run(Futures.java:522) + at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source) + at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) + at java.lang.Thread.run(Unknown Source) + at org.jclouds.concurrent.config.DescribingExecutorService.submit(DescribingExecutorService.java:89) + at org.jclouds.compute.strategy.impl.CreateNodesWithGroupEncodedIntoNameThenAddToSet.createNodeInGroupWithNameAndTemplate(CreateNodesWithGroupEncodedIntoNameThenAddToSet.java:170) + at org.jclouds.compute.strategy.impl.CreateNodesWithGroupEncodedIntoNameThenAddToSet.execute(CreateNodesWithGroupEncodedIntoNameThenAddToSet.java:125) + at org.jclouds.compute.internal.BaseComputeService.createNodesInGroup(BaseComputeService.java:213) + at org.jclouds.compute.internal.BaseComputeService.createNodesInGroup(BaseComputeService.java:229) + at org.jclouds.compute.internal.BaseComputeServiceLiveTest$1.call(BaseComputeServiceLiveTest.java:442) + at org.jclouds.compute.internal.BaseComputeServiceLiveTest$1.call(BaseComputeServiceLiveTest.java:1) + ... 3 more + Caused by: org.jclouds.http.HttpException: The status of Instance[UZXC0GRT-9Q988189J] is [RECONFIG_ING]. + at org.jclouds.fujitsu.fgcp.xml.FGCPJAXBParser.fromXML(FGCPJAXBParser.java:81) + at org.jclouds.http.functions.ParseXMLWithJAXB.apply(ParseXMLWithJAXB.java:91) +*/ +// } } \ No newline at end of file diff --git a/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/compute/functions/DiskImageToOperatingSystemTest.java b/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/compute/functions/DiskImageToOperatingSystemTest.java index 966ea07569..2c947e569b 100644 --- a/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/compute/functions/DiskImageToOperatingSystemTest.java +++ b/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/compute/functions/DiskImageToOperatingSystemTest.java @@ -11,7 +11,6 @@ import java.util.List; import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.compute.domain.OsFamily; -import org.jclouds.fujitsu.fgcp.compute.functions.DiskImageToOperatingSystem; import org.jclouds.fujitsu.fgcp.domain.DiskImage; import org.jclouds.fujitsu.fgcp.domain.DiskImage.Builder; import org.testng.annotations.Test; @@ -21,143 +20,143 @@ import org.testng.annotations.Test; */ @Test(groups = "unit", testName = "DiskImageToOperatingSystemTest") public class DiskImageToOperatingSystemTest { - // Operating Systems available JAN 2012 (taken from osName) - private static final List operatingSystems = Arrays.asList( - // JP - "CentOS 5.6 32bit (English)", - "CentOS 5.6 64bit (English)", - "Red Hat Enterprise Linux 5.5 32bit (Japanese)", - "Red Hat Enterprise Linux 5.5 64bit (Japanese)", - "Windows Server 2003 R2 EE 32bit SP2 (日本語版) サポート付", - "Windows Server 2003 R2 EE 32bit SP2 (日本語版)", - "Windows Server 2008 R2 EE 64bit (日本語版) サポート付", - "Windows Server 2008 R2 EE 64bit (日本語版)", - "Windows Server 2008 R2 SE 64bit (日本語版) サポート付", - "Windows Server 2008 R2 SE 64bit (日本語版)", - "Windows Server 2008 SE 32bit SP2 (日本語版) サポート付", - "Windows Server 2008 SE 32bit SP2 (日本語版)", - // AU - "CentOS 5.4 64bit (English)", "CentOS 5.4 32bit (English)", - "Windows Server 2008 R2 SE 64bit (English)", - "Windows Server 2008 R2 EE 64bit (English)"); + // Operating Systems available JAN 2012 (taken from osName) + private static final List operatingSystems = Arrays.asList( + // JP + "CentOS 5.6 32bit (English)", + "CentOS 5.6 64bit (English)", + "Red Hat Enterprise Linux 5.5 32bit (Japanese)", + "Red Hat Enterprise Linux 5.5 64bit (Japanese)", + "Windows Server 2003 R2 EE 32bit SP2 (日本語版) サポート付", + "Windows Server 2003 R2 EE 32bit SP2 (日本語版)", + "Windows Server 2008 R2 EE 64bit (日本語版) サポート付", + "Windows Server 2008 R2 EE 64bit (日本語版)", + "Windows Server 2008 R2 SE 64bit (日本語版) サポート付", + "Windows Server 2008 R2 SE 64bit (日本語版)", + "Windows Server 2008 SE 32bit SP2 (日本語版) サポート付", + "Windows Server 2008 SE 32bit SP2 (日本語版)", + // AU + "CentOS 5.4 64bit (English)", "CentOS 5.4 32bit (English)", + "Windows Server 2008 R2 SE 64bit (English)", + "Windows Server 2008 R2 EE 64bit (English)"); - @Test - public void testConversion() { - for (String description : operatingSystems) { - Builder builder = DiskImage.builder(); - builder.osName(description); - builder.osType("hvm"); - builder.creatorName("creator"); - builder.registrant("registrant"); - builder.description("description"); - builder.id("ABCDEFGH"); - DiskImage image = builder.build(); + @Test + public void testConversion() { + for (String description : operatingSystems) { + Builder builder = DiskImage.builder(); + builder.osName(description); + builder.osType("hvm"); + builder.creatorName("creator"); + builder.registrant("registrant"); + builder.description("description"); + builder.id("ABCDEFGH"); + DiskImage image = builder.build(); - OperatingSystem os = new DiskImageToOperatingSystem().apply(image); + OperatingSystem os = new DiskImageToOperatingSystem().apply(image); - assertNotNull(os, description); - assertNotNull(os.getFamily(), description); - assertFalse(os.getFamily().equals(OsFamily.UNRECOGNIZED), - "OsFamily not recognised: " + description); - assertNotNull(os.getVersion(), "Version not recognised: " - + description); - assertEquals(os.getName(), description); - assertEquals(os.getDescription(), description); - assertNotNull(os.getArch(), description); - } - } + assertNotNull(os, description); + assertNotNull(os.getFamily(), description); + assertFalse(os.getFamily().equals(OsFamily.UNRECOGNIZED), + "OsFamily not recognised: " + description); + assertNotNull(os.getVersion(), "Version not recognised: " + + description); + assertEquals(os.getName(), description); + assertEquals(os.getDescription(), description); + assertNotNull(os.getArch(), description); + } + } - @Test - public void testOsFamilyUnrecognized() { - DiskImage image = DiskImage.builder() - .osName("not a known operating system").build(); + @Test + public void testOsFamilyUnrecognized() { + DiskImage image = DiskImage.builder() + .osName("not a known operating system").build(); - OperatingSystem os = new DiskImageToOperatingSystem().apply(image); + OperatingSystem os = new DiskImageToOperatingSystem().apply(image); - assertNotNull(os); - assertEquals(os.getFamily(), OsFamily.UNRECOGNIZED); - } + assertNotNull(os); + assertEquals(os.getFamily(), OsFamily.UNRECOGNIZED); + } - @Test - public void test64BitsWithSpace() { - DiskImage image = DiskImage.builder().osName("a (64 bit) os").build(); + @Test + public void test64BitsWithSpace() { + DiskImage image = DiskImage.builder().osName("a (64 bit) os").build(); - OperatingSystem os = new DiskImageToOperatingSystem().apply(image); + OperatingSystem os = new DiskImageToOperatingSystem().apply(image); - assertNotNull(os); - assertTrue(os.is64Bit()); - } + assertNotNull(os); + assertTrue(os.is64Bit()); + } - @Test - public void test64BitsNoSpace() { - DiskImage image = DiskImage.builder().osName("a (64bit) os").build(); + @Test + public void test64BitsNoSpace() { + DiskImage image = DiskImage.builder().osName("a (64bit) os").build(); - OperatingSystem os = new DiskImageToOperatingSystem().apply(image); + OperatingSystem os = new DiskImageToOperatingSystem().apply(image); - assertNotNull(os); - assertTrue(os.is64Bit()); - } + assertNotNull(os); + assertTrue(os.is64Bit()); + } - @Test - public void test32BitsNoSpace() { - DiskImage image = DiskImage.builder().osName("a (32bit) os").build(); + @Test + public void test32BitsNoSpace() { + DiskImage image = DiskImage.builder().osName("a (32bit) os").build(); - OperatingSystem os = new DiskImageToOperatingSystem().apply(image); + OperatingSystem os = new DiskImageToOperatingSystem().apply(image); - assertNotNull(os); - assertFalse(os.is64Bit()); - } + assertNotNull(os); + assertFalse(os.is64Bit()); + } - @Test - public void testx64NoSpace() { - DiskImage image = DiskImage.builder().osName("a (x64) os").build(); + @Test + public void testx64NoSpace() { + DiskImage image = DiskImage.builder().osName("a (x64) os").build(); - OperatingSystem os = new DiskImageToOperatingSystem().apply(image); + OperatingSystem os = new DiskImageToOperatingSystem().apply(image); - assertNotNull(os); - assertTrue(os.is64Bit()); - } + assertNotNull(os); + assertTrue(os.is64Bit()); + } - @Test - public void testWindowsVersion() { - DiskImage image = DiskImage.builder() - .osName("Windows Server 2008 R2 SE 64 bit").build(); + @Test + public void testWindowsVersion() { + DiskImage image = DiskImage.builder() + .osName("Windows Server 2008 R2 SE 64 bit").build(); - OperatingSystem os = new DiskImageToOperatingSystem().apply(image); + OperatingSystem os = new DiskImageToOperatingSystem().apply(image); - assertNotNull(os); - assertEquals(os.getVersion(), "2008 R2 SE"); - } + assertNotNull(os); + assertEquals(os.getVersion(), "2008 R2 SE"); + } - @Test - public void testCentOSVersion() { - DiskImage image = DiskImage.builder() - .osName("CentOS 6.2 64bit (English)").build(); + @Test + public void testCentOSVersion() { + DiskImage image = DiskImage.builder() + .osName("CentOS 6.2 64bit (English)").build(); - OperatingSystem os = new DiskImageToOperatingSystem().apply(image); + OperatingSystem os = new DiskImageToOperatingSystem().apply(image); - assertNotNull(os); - assertEquals(os.getVersion(), "6.2"); - } + assertNotNull(os); + assertEquals(os.getVersion(), "6.2"); + } - @Test - public void testUnrecognizedOsVersion() { - DiskImage image = DiskImage.builder() - .osName("Windows Server 2099 (256 bit)").build(); + @Test + public void testUnrecognizedOsVersion() { + DiskImage image = DiskImage.builder() + .osName("Windows Server 2099 (256 bit)").build(); - OperatingSystem os = new DiskImageToOperatingSystem().apply(image); + OperatingSystem os = new DiskImageToOperatingSystem().apply(image); - assertNotNull(os); - assertNull(os.getVersion()); - } + assertNotNull(os); + assertNull(os.getVersion()); + } - @Test - public void testOsVersionMissing() { - DiskImage image = DiskImage.builder().osName("asd Server").build(); + @Test + public void testOsVersionMissing() { + DiskImage image = DiskImage.builder().osName("asd Server").build(); - OperatingSystem os = new DiskImageToOperatingSystem().apply(image); - assertNotNull(os); - assertNull(os.getVersion(), "os.getVersion(): \'" + os.getVersion() - + "\'"); - } + OperatingSystem os = new DiskImageToOperatingSystem().apply(image); + assertNotNull(os); + assertNull(os.getVersion(), "os.getVersion(): \'" + os.getVersion() + + "\'"); + } } diff --git a/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/services/AdditionalDiskApiExpectTest.java b/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/services/AdditionalDiskApiExpectTest.java index 953fceb870..b2a0fd2bd5 100644 --- a/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/services/AdditionalDiskApiExpectTest.java +++ b/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/services/AdditionalDiskApiExpectTest.java @@ -30,128 +30,128 @@ import org.testng.annotations.Test; @Test(groups = "unit", testName = "AdditionalDiskApiExpectTest", singleThreaded = true) public class AdditionalDiskApiExpectTest extends BaseFGCPRestApiExpectTest { - public void testGet() { - HttpRequest request = buildGETWithQuery("Action=GetVDiskAttributes" - + "&vdiskId=CONTRACT-VSYS00001-D-0001" - + "&vsysId=CONTRACT-VSYS00001"); - HttpResponse response = HttpResponse - .builder() - .statusCode(200) - .payload( - payloadFromResource("/GetVDiskAttributes-response.xml")) - .build(); + public void testGet() { + HttpRequest request = buildGETWithQuery("Action=GetVDiskAttributes" + + "&vdiskId=CONTRACT-VSYS00001-D-0001" + + "&vsysId=CONTRACT-VSYS00001"); + HttpResponse response = HttpResponse + .builder() + .statusCode(200) + .payload( + payloadFromResource("/GetVDiskAttributes-response.xml")) + .build(); - AdditionalDiskApi api = requestSendsResponse(request, response) - .getAdditionalDiskApi(); + AdditionalDiskApi api = requestSendsResponse(request, response) + .getAdditionalDiskApi(); - assertEquals(api.get("CONTRACT-VSYS00001-D-0001").getSize(), 10.0); - } + assertEquals(api.get("CONTRACT-VSYS00001-D-0001").getSize(), 10.0); + } - public void testGetStatus() { - HttpRequest request = buildGETWithQuery("Action=GetVDiskStatus" - + "&vdiskId=CONTRACT-VSYS00001-S-0001" - + "&vsysId=CONTRACT-VSYS00001"); - HttpResponse response = HttpResponse - .builder() - .statusCode(200) - .payload( - payloadFromResource("/GetVDiskStatus-response.xml")) - .build(); + public void testGetStatus() { + HttpRequest request = buildGETWithQuery("Action=GetVDiskStatus" + + "&vdiskId=CONTRACT-VSYS00001-S-0001" + + "&vsysId=CONTRACT-VSYS00001"); + HttpResponse response = HttpResponse + .builder() + .statusCode(200) + .payload( + payloadFromResource("/GetVDiskStatus-response.xml")) + .build(); - AdditionalDiskApi api = requestSendsResponse(request, response) - .getAdditionalDiskApi(); + AdditionalDiskApi api = requestSendsResponse(request, response) + .getAdditionalDiskApi(); - // api is returning STOPPED which is not a documented status. Documentation error? -// assertEquals(api.getStatus("CONTRACT-VSYS00001-S-0001"), VDiskStatus.STOPPED); - } + // api is returning STOPPED which is not a documented status. Documentation error? +// assertEquals(api.getStatus("CONTRACT-VSYS00001-S-0001"), VDiskStatus.STOPPED); + } - public void testUpdate() { - HttpRequest request = buildGETWithQuery("Action=UpdateVDiskAttribute" - + "&vdiskId=CONTRACT-VSYS00001-D-0001" - + "&attributeValue=new-name" + "&attributeName=updateName" - + "&vsysId=CONTRACT-VSYS00001"); - HttpResponse response = HttpResponse - .builder() - .statusCode(200) - .payload( - payloadFromResource("/UpdateVDiskAttribute-response.xml")) - .build(); + public void testUpdate() { + HttpRequest request = buildGETWithQuery("Action=UpdateVDiskAttribute" + + "&vdiskId=CONTRACT-VSYS00001-D-0001" + + "&attributeValue=new-name" + "&attributeName=updateName" + + "&vsysId=CONTRACT-VSYS00001"); + HttpResponse response = HttpResponse + .builder() + .statusCode(200) + .payload( + payloadFromResource("/UpdateVDiskAttribute-response.xml")) + .build(); - AdditionalDiskApi api = requestSendsResponse(request, response) - .getAdditionalDiskApi(); + AdditionalDiskApi api = requestSendsResponse(request, response) + .getAdditionalDiskApi(); - api.update("CONTRACT-VSYS00001-D-0001", "updateName", "new-name"); - } + api.update("CONTRACT-VSYS00001-D-0001", "updateName", "new-name"); + } - public void testDestroy() { - HttpRequest request = buildGETWithQuery("Action=DestroyVDisk" - + "&vdiskId=CONTRACT-VSYS00001-D-0001" - + "&vsysId=CONTRACT-VSYS00001"); - HttpResponse response = HttpResponse.builder().statusCode(200) - .payload(payloadFromResource("/DestroyVDisk-response.xml")) - .build(); + public void testDestroy() { + HttpRequest request = buildGETWithQuery("Action=DestroyVDisk" + + "&vdiskId=CONTRACT-VSYS00001-D-0001" + + "&vsysId=CONTRACT-VSYS00001"); + HttpResponse response = HttpResponse.builder().statusCode(200) + .payload(payloadFromResource("/DestroyVDisk-response.xml")) + .build(); - AdditionalDiskApi api = requestSendsResponse(request, response) - .getAdditionalDiskApi(); + AdditionalDiskApi api = requestSendsResponse(request, response) + .getAdditionalDiskApi(); - api.destroy("CONTRACT-VSYS00001-D-0001"); - } + api.destroy("CONTRACT-VSYS00001-D-0001"); + } - public void testBackup() { - HttpRequest request = buildGETWithQuery("Action=BackupVDisk" - + "&vdiskId=CONTRACT-VSYS00001-D-0001" - + "&vsysId=CONTRACT-VSYS00001"); - HttpResponse response = HttpResponse.builder().statusCode(200) - .payload(payloadFromResource("/BackupVDisk-response.xml")) - .build(); + public void testBackup() { + HttpRequest request = buildGETWithQuery("Action=BackupVDisk" + + "&vdiskId=CONTRACT-VSYS00001-D-0001" + + "&vsysId=CONTRACT-VSYS00001"); + HttpResponse response = HttpResponse.builder().statusCode(200) + .payload(payloadFromResource("/BackupVDisk-response.xml")) + .build(); - AdditionalDiskApi api = requestSendsResponse(request, response) - .getAdditionalDiskApi(); + AdditionalDiskApi api = requestSendsResponse(request, response) + .getAdditionalDiskApi(); - api.backup("CONTRACT-VSYS00001-D-0001"); - } + api.backup("CONTRACT-VSYS00001-D-0001"); + } - public void testRestore() { - HttpRequest request = buildGETWithQuery("Action=RestoreVDisk" - + "&vsysId=CONTRACT-VSYS00001" - + "&backupId=003"); - HttpResponse response = HttpResponse.builder().statusCode(200) - .payload(payloadFromResource("/RestoreVDisk-response.xml")) - .build(); + public void testRestore() { + HttpRequest request = buildGETWithQuery("Action=RestoreVDisk" + + "&vsysId=CONTRACT-VSYS00001" + + "&backupId=003"); + HttpResponse response = HttpResponse.builder().statusCode(200) + .payload(payloadFromResource("/RestoreVDisk-response.xml")) + .build(); - AdditionalDiskApi api = requestSendsResponse(request, response) - .getAdditionalDiskApi(); + AdditionalDiskApi api = requestSendsResponse(request, response) + .getAdditionalDiskApi(); - api.restore("CONTRACT-VSYS00001", "003"); - } + api.restore("CONTRACT-VSYS00001", "003"); + } - public void testDetach() { - HttpRequest request = buildGETWithQuery("Action=DetachVDisk" - + "&vdiskId=CONTRACT-VSYS00001-D-0001" - + "&vserverId=CONTRACT-VSYS00001-S-0006" - + "&vsysId=CONTRACT-VSYS00001"); - HttpResponse response = HttpResponse.builder().statusCode(200) - .payload(payloadFromResource("/DetachVDisk-response.xml")) - .build(); + public void testDetach() { + HttpRequest request = buildGETWithQuery("Action=DetachVDisk" + + "&vdiskId=CONTRACT-VSYS00001-D-0001" + + "&vserverId=CONTRACT-VSYS00001-S-0006" + + "&vsysId=CONTRACT-VSYS00001"); + HttpResponse response = HttpResponse.builder().statusCode(200) + .payload(payloadFromResource("/DetachVDisk-response.xml")) + .build(); - AdditionalDiskApi api = requestSendsResponse(request, response) - .getAdditionalDiskApi(); + AdditionalDiskApi api = requestSendsResponse(request, response) + .getAdditionalDiskApi(); - api.detach("CONTRACT-VSYS00001-D-0001", "CONTRACT-VSYS00001-S-0006"); - } + api.detach("CONTRACT-VSYS00001-D-0001", "CONTRACT-VSYS00001-S-0006"); + } - public void testDestroyBackup() { - HttpRequest request = buildGETWithQuery("Action=DestroyVDiskBackup" - + "&vsysId=CONTRACT-VSYS00001" - + "&backupId=003"); - HttpResponse response = HttpResponse.builder().statusCode(200) - .payload(payloadFromResource("/DestroyVDiskBackup-response.xml")) - .build(); + public void testDestroyBackup() { + HttpRequest request = buildGETWithQuery("Action=DestroyVDiskBackup" + + "&vsysId=CONTRACT-VSYS00001" + + "&backupId=003"); + HttpResponse response = HttpResponse.builder().statusCode(200) + .payload(payloadFromResource("/DestroyVDiskBackup-response.xml")) + .build(); - AdditionalDiskApi api = requestSendsResponse(request, response) - .getAdditionalDiskApi(); + AdditionalDiskApi api = requestSendsResponse(request, response) + .getAdditionalDiskApi(); - api.destroyBackup("CONTRACT-VSYS00001", "003"); - } + api.destroyBackup("CONTRACT-VSYS00001", "003"); + } } diff --git a/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/services/BaseFGCPApiLiveTest.java b/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/services/BaseFGCPApiLiveTest.java index 1da6e1fa84..0a209d36e5 100644 --- a/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/services/BaseFGCPApiLiveTest.java +++ b/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/services/BaseFGCPApiLiveTest.java @@ -35,50 +35,50 @@ import com.google.inject.Module; */ public class BaseFGCPApiLiveTest extends BaseComputeServiceContextLiveTest { - protected RestContext fgcpContext; + protected RestContext fgcpContext; - public BaseFGCPApiLiveTest() { - provider = "fgcp"; - } + public BaseFGCPApiLiveTest() { + provider = "fgcp"; + } - @Override - protected Properties setupProperties() { - Properties overrides = super.setupProperties(); + @Override + protected Properties setupProperties() { + Properties overrides = super.setupProperties(); - String proxy = System.getenv("http_proxy"); - if (proxy != null) { + String proxy = System.getenv("http_proxy"); + if (proxy != null) { - String[] parts = proxy.split("http://|:|@"); + String[] parts = proxy.split("http://|:|@"); - overrides.setProperty(Constants.PROPERTY_PROXY_HOST, - parts[parts.length - 2]); - overrides.setProperty(Constants.PROPERTY_PROXY_PORT, - parts[parts.length - 1]); + overrides.setProperty(Constants.PROPERTY_PROXY_HOST, + parts[parts.length - 2]); + overrides.setProperty(Constants.PROPERTY_PROXY_PORT, + parts[parts.length - 1]); - if (parts.length >= 4) { - overrides.setProperty(Constants.PROPERTY_PROXY_USER, - parts[parts.length - 4]); - overrides.setProperty(Constants.PROPERTY_PROXY_PASSWORD, - parts[parts.length - 3]); - } - } + if (parts.length >= 4) { + overrides.setProperty(Constants.PROPERTY_PROXY_USER, + parts[parts.length - 4]); + overrides.setProperty(Constants.PROPERTY_PROXY_PASSWORD, + parts[parts.length - 3]); + } + } - // enables peer verification using the CAs bundled with the JRE (or - // value of javax.net.ssl.trustStore if set) - overrides.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, "false"); + // enables peer verification using the CAs bundled with the JRE (or + // value of javax.net.ssl.trustStore if set) + overrides.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, "false"); - return overrides; - } + return overrides; + } - @BeforeGroups(groups = { "integration", "live" }) - @Override - public void setupContext() { - super.setupContext(); - fgcpContext = view.unwrap(); - } + @BeforeGroups(groups = { "integration", "live" }) + @Override + public void setupContext() { + super.setupContext(); + fgcpContext = view.unwrap(); + } - @Override - protected Module getSshModule() { - return new SshjSshClientModule(); - } + @Override + protected Module getSshModule() { + return new SshjSshClientModule(); + } } diff --git a/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/services/BaseFGCPRestApiExpectTest.java b/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/services/BaseFGCPRestApiExpectTest.java index 2fb42da3df..4a90da03d0 100644 --- a/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/services/BaseFGCPRestApiExpectTest.java +++ b/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/services/BaseFGCPRestApiExpectTest.java @@ -46,11 +46,11 @@ import com.google.inject.Module; public class BaseFGCPRestApiExpectTest extends BaseRestClientExpectTest { - public BaseFGCPRestApiExpectTest() { + public BaseFGCPRestApiExpectTest() { provider = "fgcp"; - // self-signed dummy cert: - // keytool -genkey -alias test-fgcp -keyalg RSA -keysize 1024 -validity 5475 -dname "CN=localhost" -keystore jclouds-test-fgcp.p12 -storepass jcloudsjclouds -storetype pkcs12 + // self-signed dummy cert: + // keytool -genkey -alias test-fgcp -keyalg RSA -keysize 1024 -validity 5475 -dname "CN=localhost" -keystore jclouds-test-fgcp.p12 -storepass jcloudsjclouds -storetype pkcs12 String cert = "/certs/jclouds-test-fgcp.p12"; URL url = this.getClass().getResource(cert); assertNotNull(url, cert + " not found"); @@ -79,47 +79,47 @@ public class BaseFGCPRestApiExpectTest extends return new TestFGCPRestClientModule(); } - @Override - protected ProviderMetadata createProviderMetadata() { - return new FGCPProviderMetadata(); - } + @Override + protected ProviderMetadata createProviderMetadata() { + return new FGCPProviderMetadata(); + } - @Override - public Payload payloadFromResource(String resource) { - return super.payloadFromResource("/responses" + resource); - } + @Override + public Payload payloadFromResource(String resource) { + return super.payloadFromResource("/responses" + resource); + } - protected static HttpRequest buildGETWithQuery(String query) { - URI uri = URI.create("https://api.globalcloud.fujitsu.com.au/ovissapi/endpoint" - + "?Version=2012-02-18" - + "&" + query - + "&Locale=en" - + "&AccessKeyId=R01ULTA5OjAwJjEyMzQ1Njc4OTAmMS4wJlNIQTF3aXRoUlNB" -// + "&Signature=G2rGfLAkbq0IURQfXIWYxj3BnMGbjRk4KPnZLAze3Lt4SMMRt8lkjqKvR5Cm%2BnFpDN7J6IprVCCsIrRq5BqPeXT6xtWyb6qMNds2BAr1h%2FJePGs0UosOh2tgPUMSFlZwLVjgNyrSa2zeHA3AEHjF6H1jqcWXXqfCAD4SOHaNavk%3D"); - + "&Signature=G2rGfLAkbq0IURQfXIWYxj3BnMGbjRk4KPnZLAze3Lt4SMMRt8lkjqKvR5Cm%2BnFpDN7J6IprVCCs%0D%0AIrRq5BqPeXT6xtWyb6qMNds2BAr1h%2FJePGs0UosOh2tgPUMSFlZwLVjgNyrSa2zeHA3AEHjF6H1j%0D%0AqcWXXqfCAD4SOHaNavk%3D"); - return HttpRequest - .builder() - .method("GET") - .endpoint(uri) - .addHeader("Accept", "text/xml") - .addHeader("User-Agent", "OViSS-API-CLIENT") - .build(); - } + protected static HttpRequest buildGETWithQuery(String query) { + URI uri = URI.create("https://api.globalcloud.fujitsu.com.au/ovissapi/endpoint" + + "?Version=2012-02-18" + + "&" + query + + "&Locale=en" + + "&AccessKeyId=R01ULTA5OjAwJjEyMzQ1Njc4OTAmMS4wJlNIQTF3aXRoUlNB" +// + "&Signature=G2rGfLAkbq0IURQfXIWYxj3BnMGbjRk4KPnZLAze3Lt4SMMRt8lkjqKvR5Cm%2BnFpDN7J6IprVCCsIrRq5BqPeXT6xtWyb6qMNds2BAr1h%2FJePGs0UosOh2tgPUMSFlZwLVjgNyrSa2zeHA3AEHjF6H1jqcWXXqfCAD4SOHaNavk%3D"); + + "&Signature=G2rGfLAkbq0IURQfXIWYxj3BnMGbjRk4KPnZLAze3Lt4SMMRt8lkjqKvR5Cm%2BnFpDN7J6IprVCCs%0D%0AIrRq5BqPeXT6xtWyb6qMNds2BAr1h%2FJePGs0UosOh2tgPUMSFlZwLVjgNyrSa2zeHA3AEHjF6H1j%0D%0AqcWXXqfCAD4SOHaNavk%3D"); + return HttpRequest + .builder() + .method("GET") + .endpoint(uri) + .addHeader("Accept", "text/xml") + .addHeader("User-Agent", "OViSS-API-CLIENT") + .build(); + } - protected HttpRequest preparePOSTForAction(String action) { - return HttpRequest - .builder() - .method("POST") - .endpoint( - URI.create("https://api.globalcloud.fujitsu.com.au/ovissapi/endpoint")) - .payload( - payloadFromResourceWithContentType( - "/" + action.toLowerCase() + "-request.xml", - MediaType.TEXT_XML)) - .headers( - ImmutableMultimap. builder() - .put("Accept", "text/xml") - .put("User-Agent", "OViSS-API-CLIENT").build()) - .build(); - } + protected HttpRequest preparePOSTForAction(String action) { + return HttpRequest + .builder() + .method("POST") + .endpoint( + URI.create("https://api.globalcloud.fujitsu.com.au/ovissapi/endpoint")) + .payload( + payloadFromResourceWithContentType( + "/" + action.toLowerCase() + "-request.xml", + MediaType.TEXT_XML)) + .headers( + ImmutableMultimap. builder() + .put("Accept", "text/xml") + .put("User-Agent", "OViSS-API-CLIENT").build()) + .build(); + } } diff --git a/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/services/BuiltinServerApiExpectTest.java b/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/services/BuiltinServerApiExpectTest.java index acb2f165c3..a26b0ff101 100644 --- a/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/services/BuiltinServerApiExpectTest.java +++ b/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/services/BuiltinServerApiExpectTest.java @@ -18,8 +18,8 @@ */ package org.jclouds.fujitsu.fgcp.services; -import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; import java.util.Set; @@ -36,180 +36,180 @@ import org.testng.annotations.Test; @Test(groups = "unit", testName = "BuiltinServerApiExpectTest", singleThreaded = true) public class BuiltinServerApiExpectTest extends BaseFGCPRestApiExpectTest { - public void testStart() { - HttpRequest request = buildGETWithQuery("Action=StartEFM" - + "&efmId=CONTRACT-VSYS00001-S-0001" - + "&vsysId=CONTRACT-VSYS00001"); - HttpResponse response = HttpResponse.builder().statusCode(200) - .payload(payloadFromResource("/StartEFM-response.xml")) - .build(); + public void testStart() { + HttpRequest request = buildGETWithQuery("Action=StartEFM" + + "&efmId=CONTRACT-VSYS00001-S-0001" + + "&vsysId=CONTRACT-VSYS00001"); + HttpResponse response = HttpResponse.builder().statusCode(200) + .payload(payloadFromResource("/StartEFM-response.xml")) + .build(); - BuiltinServerApi api = requestSendsResponse(request, response) - .getFirewallApi(); + BuiltinServerApi api = requestSendsResponse(request, response) + .getFirewallApi(); - api.start("CONTRACT-VSYS00001-S-0001"); - } + api.start("CONTRACT-VSYS00001-S-0001"); + } - public void testStop() { - HttpRequest request = buildGETWithQuery("Action=StopEFM" - + "&efmId=CONTRACT-VSYS00001-S-0001" - + "&vsysId=CONTRACT-VSYS00001"); - HttpResponse response = HttpResponse.builder().statusCode(200) - .payload(payloadFromResource("/StopEFM-response.xml")) - .build(); + public void testStop() { + HttpRequest request = buildGETWithQuery("Action=StopEFM" + + "&efmId=CONTRACT-VSYS00001-S-0001" + + "&vsysId=CONTRACT-VSYS00001"); + HttpResponse response = HttpResponse.builder().statusCode(200) + .payload(payloadFromResource("/StopEFM-response.xml")) + .build(); - BuiltinServerApi api = requestSendsResponse(request, response) - .getFirewallApi(); + BuiltinServerApi api = requestSendsResponse(request, response) + .getFirewallApi(); - api.stop("CONTRACT-VSYS00001-S-0001"); - } + api.stop("CONTRACT-VSYS00001-S-0001"); + } - public void testDestroy() { - HttpRequest request = buildGETWithQuery("Action=DestroyEFM" - + "&efmId=CONTRACT-VSYS00001-S-0001" - + "&vsysId=CONTRACT-VSYS00001"); - HttpResponse response = HttpResponse.builder().statusCode(200) - .payload(payloadFromResource("/DestroyEFM-response.xml")) - .build(); + public void testDestroy() { + HttpRequest request = buildGETWithQuery("Action=DestroyEFM" + + "&efmId=CONTRACT-VSYS00001-S-0001" + + "&vsysId=CONTRACT-VSYS00001"); + HttpResponse response = HttpResponse.builder().statusCode(200) + .payload(payloadFromResource("/DestroyEFM-response.xml")) + .build(); - BuiltinServerApi api = requestSendsResponse(request, response) - .getFirewallApi(); + BuiltinServerApi api = requestSendsResponse(request, response) + .getFirewallApi(); - api.destroy("CONTRACT-VSYS00001-S-0001"); - } + api.destroy("CONTRACT-VSYS00001-S-0001"); + } - public void testGet() { - HttpRequest request = buildGETWithQuery("Action=GetEFMAttributes" - + "&efmId=CONTRACT-VSYS00001-S-0001" - + "&vsysId=CONTRACT-VSYS00001"); - HttpResponse response = HttpResponse - .builder() - .statusCode(200) - .payload( - payloadFromResource("/GetEFMAttributes-response.xml")) - .build(); + public void testGet() { + HttpRequest request = buildGETWithQuery("Action=GetEFMAttributes" + + "&efmId=CONTRACT-VSYS00001-S-0001" + + "&vsysId=CONTRACT-VSYS00001"); + HttpResponse response = HttpResponse + .builder() + .statusCode(200) + .payload( + payloadFromResource("/GetEFMAttributes-response.xml")) + .build(); - BuiltinServerApi api = requestSendsResponse(request, response) - .getFirewallApi(); + BuiltinServerApi api = requestSendsResponse(request, response) + .getFirewallApi(); - assertEquals(api.get("CONTRACT-VSYS00001-S-0001").getType(), BuiltinServer.BuiltinServerType.FW); - } + assertEquals(api.get("CONTRACT-VSYS00001-S-0001").getType(), BuiltinServer.BuiltinServerType.FW); + } /* - public void testGetDetails() { - HttpRequest request = buildGETWithQuery("Action=GetEFMConfiguration" - + "&efmId=CONTRACT-VSYS00001-S-0001" - + "&vsysId=CONTRACT-VSYS00001"); - HttpResponse response = HttpResponse - .builder() - .statusCode(200) - .payload( - payloadFromResource("/GetEFMConfiguration-response.xml")) - .build(); + public void testGetDetails() { + HttpRequest request = buildGETWithQuery("Action=GetEFMConfiguration" + + "&efmId=CONTRACT-VSYS00001-S-0001" + + "&vsysId=CONTRACT-VSYS00001"); + HttpResponse response = HttpResponse + .builder() + .statusCode(200) + .payload( + payloadFromResource("/GetEFMConfiguration-response.xml")) + .build(); - BuiltinServerApi api = requestSendsResponse(request, response) - .getFirewallApi(); + BuiltinServerApi api = requestSendsResponse(request, response) + .getFirewallApi(); -// assertNotNull(api.getDetails("CONTRACT-VSYS00001-S-0001")); - } +// assertNotNull(api.getDetails("CONTRACT-VSYS00001-S-0001")); + } */ - public void testGetStatus() { - HttpRequest request = buildGETWithQuery("Action=GetEFMStatus" - + "&efmId=CONTRACT-VSYS00001-S-0001" - + "&vsysId=CONTRACT-VSYS00001"); - HttpResponse response = HttpResponse - .builder() - .statusCode(200) - .payload( - payloadFromResource("/GetEFMStatus-response.xml")) - .build(); + public void testGetStatus() { + HttpRequest request = buildGETWithQuery("Action=GetEFMStatus" + + "&efmId=CONTRACT-VSYS00001-S-0001" + + "&vsysId=CONTRACT-VSYS00001"); + HttpResponse response = HttpResponse + .builder() + .statusCode(200) + .payload( + payloadFromResource("/GetEFMStatus-response.xml")) + .build(); - BuiltinServerApi api = requestSendsResponse(request, response) - .getFirewallApi(); + BuiltinServerApi api = requestSendsResponse(request, response) + .getFirewallApi(); - assertEquals(api.getStatus("CONTRACT-VSYS00001-S-0001"), BuiltinServerStatus.RUNNING); - } + assertEquals(api.getStatus("CONTRACT-VSYS00001-S-0001"), BuiltinServerStatus.RUNNING); + } - public void testUpdate() { - HttpRequest request = buildGETWithQuery("Action=UpdateEFMAttribute" - + "&efmId=CONTRACT-VSYS00001-S-0001" - + "&attributeValue=new%20name" - + "&attributeName=vserverName" - + "&vsysId=CONTRACT-VSYS00001"); - HttpResponse response = HttpResponse - .builder() - .statusCode(200) - .payload( - payloadFromResource("/UpdateEFMAttribute-response.xml")) - .build(); + public void testUpdate() { + HttpRequest request = buildGETWithQuery("Action=UpdateEFMAttribute" + + "&efmId=CONTRACT-VSYS00001-S-0001" + + "&attributeValue=new%20name" + + "&attributeName=vserverName" + + "&vsysId=CONTRACT-VSYS00001"); + HttpResponse response = HttpResponse + .builder() + .statusCode(200) + .payload( + payloadFromResource("/UpdateEFMAttribute-response.xml")) + .build(); - BuiltinServerApi api = requestSendsResponse(request, response) - .getFirewallApi(); + BuiltinServerApi api = requestSendsResponse(request, response) + .getFirewallApi(); - api.update("CONTRACT-VSYS00001-S-0001", "vserverName", "new name"); - } + api.update("CONTRACT-VSYS00001-S-0001", "vserverName", "new name"); + } - public void testBackup() { - HttpRequest request = buildGETWithQuery("Action=BackupEFM" - + "&efmId=CONTRACT-VSYS00001-S-0001" - + "&vsysId=CONTRACT-VSYS00001"); - HttpResponse response = HttpResponse.builder().statusCode(200) - .payload(payloadFromResource("/BackupEFM-response.xml")) - .build(); + public void testBackup() { + HttpRequest request = buildGETWithQuery("Action=BackupEFM" + + "&efmId=CONTRACT-VSYS00001-S-0001" + + "&vsysId=CONTRACT-VSYS00001"); + HttpResponse response = HttpResponse.builder().statusCode(200) + .payload(payloadFromResource("/BackupEFM-response.xml")) + .build(); - BuiltinServerApi api = requestSendsResponse(request, response) - .getFirewallApi(); + BuiltinServerApi api = requestSendsResponse(request, response) + .getFirewallApi(); - api.backup("CONTRACT-VSYS00001-S-0001"); - } + api.backup("CONTRACT-VSYS00001-S-0001"); + } - public void testRestore() { - HttpRequest request = buildGETWithQuery("Action=RestoreEFM" - + "&efmId=CONTRACT-VSYS00001-S-0001" - + "&backupId=003" - + "&vsysId=CONTRACT-VSYS00001"); - HttpResponse response = HttpResponse.builder().statusCode(200) - .payload(payloadFromResource("/RestoreEFM-response.xml")) - .build(); + public void testRestore() { + HttpRequest request = buildGETWithQuery("Action=RestoreEFM" + + "&efmId=CONTRACT-VSYS00001-S-0001" + + "&backupId=003" + + "&vsysId=CONTRACT-VSYS00001"); + HttpResponse response = HttpResponse.builder().statusCode(200) + .payload(payloadFromResource("/RestoreEFM-response.xml")) + .build(); - BuiltinServerApi api = requestSendsResponse(request, response) - .getFirewallApi(); + BuiltinServerApi api = requestSendsResponse(request, response) + .getFirewallApi(); - api.restore("CONTRACT-VSYS00001-S-0001", "003"); - } + api.restore("CONTRACT-VSYS00001-S-0001", "003"); + } - public void testListBackups() { - HttpRequest request = buildGETWithQuery("Action=ListEFMBackup" - + "&efmId=CONTRACT-VSYS00001-S-0001" - + "&vsysId=CONTRACT-VSYS00001"); - HttpResponse response = HttpResponse.builder().statusCode(200) - .payload(payloadFromResource("/ListEFMBackup-response.xml")) - .build(); + public void testListBackups() { + HttpRequest request = buildGETWithQuery("Action=ListEFMBackup" + + "&efmId=CONTRACT-VSYS00001-S-0001" + + "&vsysId=CONTRACT-VSYS00001"); + HttpResponse response = HttpResponse.builder().statusCode(200) + .payload(payloadFromResource("/ListEFMBackup-response.xml")) + .build(); - BuiltinServerApi api = requestSendsResponse(request, response) - .getFirewallApi(); + BuiltinServerApi api = requestSendsResponse(request, response) + .getFirewallApi(); - Set backups = api.listBackups("CONTRACT-VSYS00001-S-0001"); - assertNotNull(backups, "backups"); - assertEquals(backups.size(), 2); - assertEquals(backups.iterator().next().getId(), "001"); - assertEquals(backups.iterator().next().getTime(), "20121008201127"); - } + Set backups = api.listBackups("CONTRACT-VSYS00001-S-0001"); + assertNotNull(backups, "backups"); + assertEquals(backups.size(), 2); + assertEquals(backups.iterator().next().getId(), "001"); + assertEquals(backups.iterator().next().getTime(), "20121008201127"); + } - public void testDestroyBackup() { - HttpRequest request = buildGETWithQuery("Action=DestroyEFMBackup" - + "&efmId=CONTRACT-VSYS00001-S-0001" - + "&backupId=003" - + "&vsysId=CONTRACT-VSYS00001"); - HttpResponse response = HttpResponse.builder().statusCode(200) - .payload(payloadFromResource("/DestroyEFMBackup-response.xml")) - .build(); + public void testDestroyBackup() { + HttpRequest request = buildGETWithQuery("Action=DestroyEFMBackup" + + "&efmId=CONTRACT-VSYS00001-S-0001" + + "&backupId=003" + + "&vsysId=CONTRACT-VSYS00001"); + HttpResponse response = HttpResponse.builder().statusCode(200) + .payload(payloadFromResource("/DestroyEFMBackup-response.xml")) + .build(); - BuiltinServerApi api = requestSendsResponse(request, response) - .getFirewallApi(); + BuiltinServerApi api = requestSendsResponse(request, response) + .getFirewallApi(); - api.destroyBackup("CONTRACT-VSYS00001-S-0001", "003"); - } + api.destroyBackup("CONTRACT-VSYS00001-S-0001", "003"); + } } diff --git a/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/services/DiskImageApiExpectTest.java b/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/services/DiskImageApiExpectTest.java index d0ae9a027a..4e0efdae02 100644 --- a/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/services/DiskImageApiExpectTest.java +++ b/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/services/DiskImageApiExpectTest.java @@ -31,49 +31,49 @@ import org.testng.annotations.Test; @Test(groups = "unit", testName = "DiskImageApiExpectTest", singleThreaded = true) public class DiskImageApiExpectTest extends BaseFGCPRestApiExpectTest { - public void testGet() { - HttpRequest request = buildGETWithQuery("Action=GetDiskImageAttributes" - + "&diskImageId=IMG_A1B2C3_1234567890ABCD"); - HttpResponse response = HttpResponse.builder().statusCode(200) - .payload(payloadFromResource("/GetDiskImageAttributes-response.xml")) - .build(); + public void testGet() { + HttpRequest request = buildGETWithQuery("Action=GetDiskImageAttributes" + + "&diskImageId=IMG_A1B2C3_1234567890ABCD"); + HttpResponse response = HttpResponse.builder().statusCode(200) + .payload(payloadFromResource("/GetDiskImageAttributes-response.xml")) + .build(); - DiskImageApi api = requestSendsResponse(request, response) - .getDiskImageApi(); + DiskImageApi api = requestSendsResponse(request, response) + .getDiskImageApi(); - DiskImage image = api.get("IMG_A1B2C3_1234567890ABCD"); + DiskImage image = api.get("IMG_A1B2C3_1234567890ABCD"); - assertEquals(image.getId(), "IMG_A1B2C3_1234567890ABCD"); - assertEquals(image.getCreatorName(), "ABCDEFGH"); - } + assertEquals(image.getId(), "IMG_A1B2C3_1234567890ABCD"); + assertEquals(image.getCreatorName(), "ABCDEFGH"); + } - public void testUpdate() { - HttpRequest request = buildGETWithQuery("Action=UpdateDiskImageAttribute" - + "&diskImageId=IMG_A1B2C3_1234567890ABCD" - + "&attributeName=updateName" - + "&updateLcId=en" - + "&attributeValue=new-name"); - HttpResponse response = HttpResponse.builder().statusCode(200) - .payload(payloadFromResource("/UpdateDiskImageAttribute-response.xml")) - .build(); + public void testUpdate() { + HttpRequest request = buildGETWithQuery("Action=UpdateDiskImageAttribute" + + "&diskImageId=IMG_A1B2C3_1234567890ABCD" + + "&attributeName=updateName" + + "&updateLcId=en" + + "&attributeValue=new-name"); + HttpResponse response = HttpResponse.builder().statusCode(200) + .payload(payloadFromResource("/UpdateDiskImageAttribute-response.xml")) + .build(); - DiskImageApi api = requestSendsResponse(request, response) - .getDiskImageApi(); + DiskImageApi api = requestSendsResponse(request, response) + .getDiskImageApi(); - api.update("IMG_A1B2C3_1234567890ABCD", "en", "updateName", "new-name"); - } + api.update("IMG_A1B2C3_1234567890ABCD", "en", "updateName", "new-name"); + } - public void testDeregister() { - HttpRequest request = buildGETWithQuery("Action=UnregisterDiskImage" - + "&diskImageId=IMG_A1B2C3_1234567890ABCD"); - HttpResponse response = HttpResponse.builder().statusCode(200) - .payload(payloadFromResource("/UnregisterDiskImage-response.xml")) - .build(); + public void testDeregister() { + HttpRequest request = buildGETWithQuery("Action=UnregisterDiskImage" + + "&diskImageId=IMG_A1B2C3_1234567890ABCD"); + HttpResponse response = HttpResponse.builder().statusCode(200) + .payload(payloadFromResource("/UnregisterDiskImage-response.xml")) + .build(); - DiskImageApi api = requestSendsResponse(request, response) - .getDiskImageApi(); + DiskImageApi api = requestSendsResponse(request, response) + .getDiskImageApi(); - api.deregister("IMG_A1B2C3_1234567890ABCD"); - } + api.deregister("IMG_A1B2C3_1234567890ABCD"); + } } diff --git a/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/services/PublicIPAddressApiExpectTest.java b/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/services/PublicIPAddressApiExpectTest.java index 226ec070c2..8458fe2a92 100644 --- a/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/services/PublicIPAddressApiExpectTest.java +++ b/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/services/PublicIPAddressApiExpectTest.java @@ -33,77 +33,77 @@ import org.testng.annotations.Test; @Test(groups = "unit", testName = "PublicIPAddressApiExpectTest", singleThreaded = true) public class PublicIPAddressApiExpectTest extends BaseFGCPRestApiExpectTest { - public void testAttach() { - HttpRequest request = buildGETWithQuery("Action=AttachPublicIP" - + "&vsysId=CONTRACT-VSYS00001" - + "&publicIp=123.45.67.89"); - HttpResponse response = HttpResponse.builder().statusCode(200) - .payload(payloadFromResource("/AttachPublicIP-response.xml")) - .build(); + public void testAttach() { + HttpRequest request = buildGETWithQuery("Action=AttachPublicIP" + + "&vsysId=CONTRACT-VSYS00001" + + "&publicIp=123.45.67.89"); + HttpResponse response = HttpResponse.builder().statusCode(200) + .payload(payloadFromResource("/AttachPublicIP-response.xml")) + .build(); - PublicIPAddressApi api = requestSendsResponse(request, response) - .getPublicIPAddressApi(); + PublicIPAddressApi api = requestSendsResponse(request, response) + .getPublicIPAddressApi(); - api.attach("CONTRACT-VSYS00001", "123.45.67.89"); - } + api.attach("CONTRACT-VSYS00001", "123.45.67.89"); + } - public void testDetach() { - HttpRequest request = buildGETWithQuery("Action=DetachPublicIP" - + "&vsysId=CONTRACT-VSYS00001" - + "&publicIp=123.45.67.89"); - HttpResponse response = HttpResponse.builder().statusCode(200) - .payload(payloadFromResource("/DetachPublicIP-response.xml")) - .build(); + public void testDetach() { + HttpRequest request = buildGETWithQuery("Action=DetachPublicIP" + + "&vsysId=CONTRACT-VSYS00001" + + "&publicIp=123.45.67.89"); + HttpResponse response = HttpResponse.builder().statusCode(200) + .payload(payloadFromResource("/DetachPublicIP-response.xml")) + .build(); - PublicIPAddressApi api = requestSendsResponse(request, response) - .getPublicIPAddressApi(); + PublicIPAddressApi api = requestSendsResponse(request, response) + .getPublicIPAddressApi(); - api.detach("CONTRACT-VSYS00001", "123.45.67.89"); - } + api.detach("CONTRACT-VSYS00001", "123.45.67.89"); + } - public void testFree() { - HttpRequest request = buildGETWithQuery("Action=FreePublicIP" - + "&vsysId=CONTRACT-VSYS00001" - + "&publicIp=123.45.67.89"); - HttpResponse response = HttpResponse.builder().statusCode(200) - .payload(payloadFromResource("/FreePublicIP-response.xml")) - .build(); + public void testFree() { + HttpRequest request = buildGETWithQuery("Action=FreePublicIP" + + "&vsysId=CONTRACT-VSYS00001" + + "&publicIp=123.45.67.89"); + HttpResponse response = HttpResponse.builder().statusCode(200) + .payload(payloadFromResource("/FreePublicIP-response.xml")) + .build(); - PublicIPAddressApi api = requestSendsResponse(request, response) - .getPublicIPAddressApi(); + PublicIPAddressApi api = requestSendsResponse(request, response) + .getPublicIPAddressApi(); - api.free("CONTRACT-VSYS00001", "123.45.67.89"); - } + api.free("CONTRACT-VSYS00001", "123.45.67.89"); + } - public void testGetStatus() { - HttpRequest request = buildGETWithQuery("Action=GetPublicIPStatus" - + "&publicIp=123.45.67.89"); - HttpResponse response = HttpResponse.builder().statusCode(200) - .payload(payloadFromResource("/GetPublicIPStatus-response.xml")) - .build(); + public void testGetStatus() { + HttpRequest request = buildGETWithQuery("Action=GetPublicIPStatus" + + "&publicIp=123.45.67.89"); + HttpResponse response = HttpResponse.builder().statusCode(200) + .payload(payloadFromResource("/GetPublicIPStatus-response.xml")) + .build(); - PublicIPAddressApi api = requestSendsResponse(request, response) - .getPublicIPAddressApi(); + PublicIPAddressApi api = requestSendsResponse(request, response) + .getPublicIPAddressApi(); - PublicIPStatus status = api.getStatus("123.45.67.89"); - assertEquals(status, PublicIPStatus.ATTACHED); - } + PublicIPStatus status = api.getStatus("123.45.67.89"); + assertEquals(status, PublicIPStatus.ATTACHED); + } - public void testGet() { - HttpRequest request = buildGETWithQuery("Action=GetPublicIPAttributes" - + "&publicIp=123.45.67.89"); - HttpResponse response = HttpResponse.builder().statusCode(200) - .payload(payloadFromResource("/GetPublicIPAttributes-response.xml")) - .build(); + public void testGet() { + HttpRequest request = buildGETWithQuery("Action=GetPublicIPAttributes" + + "&publicIp=123.45.67.89"); + HttpResponse response = HttpResponse.builder().statusCode(200) + .payload(payloadFromResource("/GetPublicIPAttributes-response.xml")) + .build(); - PublicIPAddressApi api = requestSendsResponse(request, response) - .getPublicIPAddressApi(); + PublicIPAddressApi api = requestSendsResponse(request, response) + .getPublicIPAddressApi(); - PublicIP ip = api.get("123.45.67.89"); + PublicIP ip = api.get("123.45.67.89"); - assertNotNull(ip, "ip"); - assertEquals(ip.getAddress(), "123.45.67.89"); - assertEquals(ip.getVersion(), PublicIP.Version.IPv4); - } + assertNotNull(ip, "ip"); + assertEquals(ip.getAddress(), "123.45.67.89"); + assertEquals(ip.getVersion(), PublicIP.Version.IPv4); + } } diff --git a/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/services/SystemTemplateApiExpectTest.java b/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/services/SystemTemplateApiExpectTest.java index 182c13faf6..6b653c01f9 100644 --- a/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/services/SystemTemplateApiExpectTest.java +++ b/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/services/SystemTemplateApiExpectTest.java @@ -18,10 +18,8 @@ */ package org.jclouds.fujitsu.fgcp.services; -import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; -import org.jclouds.fujitsu.fgcp.domain.VSystem; import org.jclouds.fujitsu.fgcp.domain.VSystemDescriptor; import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpResponse; @@ -33,71 +31,71 @@ import org.testng.annotations.Test; @Test(groups = "unit", testName = "SystemTemplateApiExpectTest", singleThreaded = true) public class SystemTemplateApiExpectTest extends BaseFGCPRestApiExpectTest { - public void testGet() { - HttpRequest request = buildGETWithQuery("Action=GetVSYSDescriptorConfiguration" - + "&vsysDescriptorId=3-tier%20Skeleton"); - HttpResponse response = HttpResponse - .builder() - .statusCode(200) - .payload( - payloadFromResource("/GetVSYSDescriptorConfiguration-response.xml")) - .build(); - SystemTemplateApi client = requestSendsResponse(request, response) - .getSystemTemplateApi(); + public void testGet() { + HttpRequest request = buildGETWithQuery("Action=GetVSYSDescriptorConfiguration" + + "&vsysDescriptorId=3-tier%20Skeleton"); + HttpResponse response = HttpResponse + .builder() + .statusCode(200) + .payload( + payloadFromResource("/GetVSYSDescriptorConfiguration-response.xml")) + .build(); + SystemTemplateApi client = requestSendsResponse(request, response) + .getSystemTemplateApi(); - VSystemDescriptor desc = client.get("3-tier Skeleton"); - assertNotNull(desc, "desc"); -// assertEquals(desc.) - } + VSystemDescriptor desc = client.get("3-tier Skeleton"); + assertNotNull(desc, "desc"); +// assertEquals(desc.) + } - public void testUpdate() { - HttpRequest request = buildGETWithQuery("Action=UpdateVSYSDescriptorAttribute" - + "&vsysDescriptorId=3-tier%20Skeleton" + "&attributeName=updateName" - + "&updateLcId=en" - + "&attributeValue=new-name"); - HttpResponse response = HttpResponse - .builder() - .statusCode(200) - .payload( - payloadFromResource("/UpdateVSYSDescriptorAttribute-response.xml")) - .build(); + public void testUpdate() { + HttpRequest request = buildGETWithQuery("Action=UpdateVSYSDescriptorAttribute" + + "&vsysDescriptorId=3-tier%20Skeleton" + "&attributeName=updateName" + + "&updateLcId=en" + + "&attributeValue=new-name"); + HttpResponse response = HttpResponse + .builder() + .statusCode(200) + .payload( + payloadFromResource("/UpdateVSYSDescriptorAttribute-response.xml")) + .build(); - SystemTemplateApi api = requestSendsResponse(request, response) - .getSystemTemplateApi(); + SystemTemplateApi api = requestSendsResponse(request, response) + .getSystemTemplateApi(); - api.update("3-tier Skeleton", "en", "updateName", "new-name"); - } + api.update("3-tier Skeleton", "en", "updateName", "new-name"); + } - public void testDeregister() { - HttpRequest request = buildGETWithQuery("Action=UnregisterVSYSDescriptor" - + "&vsysDescriptorId=3-tier%20Skeleton"); - HttpResponse response = HttpResponse - .builder() - .statusCode(200) - .payload( - payloadFromResource("/UnregisterVSYSDescriptor-response.xml")) - .build(); + public void testDeregister() { + HttpRequest request = buildGETWithQuery("Action=UnregisterVSYSDescriptor" + + "&vsysDescriptorId=3-tier%20Skeleton"); + HttpResponse response = HttpResponse + .builder() + .statusCode(200) + .payload( + payloadFromResource("/UnregisterVSYSDescriptor-response.xml")) + .build(); - SystemTemplateApi api = requestSendsResponse(request, response) - .getSystemTemplateApi(); + SystemTemplateApi api = requestSendsResponse(request, response) + .getSystemTemplateApi(); - api.deregister("3-tier Skeleton"); - } + api.deregister("3-tier Skeleton"); + } - public void testDeregisterPrivateTemplate() { - HttpRequest request = buildGETWithQuery("Action=UnregisterPrivateVSYSDescriptor" - + "&vsysDescriptorId=3-tier%20Skeleton"); - HttpResponse response = HttpResponse - .builder() - .statusCode(200) - .payload( - payloadFromResource("/UnregisterPrivateVSYSDescriptor-response.xml")) - .build(); + public void testDeregisterPrivateTemplate() { + HttpRequest request = buildGETWithQuery("Action=UnregisterPrivateVSYSDescriptor" + + "&vsysDescriptorId=3-tier%20Skeleton"); + HttpResponse response = HttpResponse + .builder() + .statusCode(200) + .payload( + payloadFromResource("/UnregisterPrivateVSYSDescriptor-response.xml")) + .build(); - SystemTemplateApi api = requestSendsResponse(request, response) - .getSystemTemplateApi(); + SystemTemplateApi api = requestSendsResponse(request, response) + .getSystemTemplateApi(); - api.deregisterPrivateTemplate("3-tier Skeleton"); - } + api.deregisterPrivateTemplate("3-tier Skeleton"); + } } diff --git a/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/services/VirtualDCApiExpectTest.java b/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/services/VirtualDCApiExpectTest.java index 277a449fe6..32ae3ad2ef 100644 --- a/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/services/VirtualDCApiExpectTest.java +++ b/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/services/VirtualDCApiExpectTest.java @@ -41,166 +41,166 @@ import org.testng.annotations.Test; @Test(groups = "unit", testName = "VirtualDCApiExpectTest", singleThreaded = true) public class VirtualDCApiExpectTest extends BaseFGCPRestApiExpectTest { - public void testListVirtualSystems() { - HttpRequest request = buildGETWithQuery("Action=ListVSYS"); - HttpResponse response = HttpResponse.builder() - .statusCode(200) - .payload(payloadFromResource("/ListVSYS-response.xml")) - .build(); + public void testListVirtualSystems() { + HttpRequest request = buildGETWithQuery("Action=ListVSYS"); + HttpResponse response = HttpResponse.builder() + .statusCode(200) + .payload(payloadFromResource("/ListVSYS-response.xml")) + .build(); - VirtualDCApi api = requestSendsResponse(request, response).getVirtualDCApi(); + VirtualDCApi api = requestSendsResponse(request, response).getVirtualDCApi(); - Set vsysSet = api.listVirtualSystems(); - assertEquals(vsysSet.size(), 2); - } + Set vsysSet = api.listVirtualSystems(); + assertEquals(vsysSet.size(), 2); + } - public void testCreateVirtualSystem() { - HttpRequest request = buildGETWithQuery("Action=CreateVSYS&vsysDescriptorId=myDescId&vsysName=myVSYS"); - HttpResponse response = HttpResponse.builder() - .statusCode(200) - .payload(payloadFromResource("/CreateVSYS-response.xml")) - .build(); - VirtualDCApi api = requestSendsResponse(request, response) - .getVirtualDCApi(); + public void testCreateVirtualSystem() { + HttpRequest request = buildGETWithQuery("Action=CreateVSYS&vsysDescriptorId=myDescId&vsysName=myVSYS"); + HttpResponse response = HttpResponse.builder() + .statusCode(200) + .payload(payloadFromResource("/CreateVSYS-response.xml")) + .build(); + VirtualDCApi api = requestSendsResponse(request, response) + .getVirtualDCApi(); - String vsysId = api.createVirtualSystem("myDescId", "myVSYS"); - assertEquals(vsysId, "CONTRACT-VSYS00001", "vsysId: " + vsysId); - } + String vsysId = api.createVirtualSystem("myDescId", "myVSYS"); + assertEquals(vsysId, "CONTRACT-VSYS00001", "vsysId: " + vsysId); + } - public void testListServerTypes() { - HttpRequest request = buildGETWithQuery("Action=ListServerType&diskImageId=dummy"); - HttpResponse response = HttpResponse.builder() - .statusCode(200) - .payload(payloadFromResource("/ListServerType-response.xml")) - .build(); - VirtualDCApi api = requestSendsResponse(request, response) - .getVirtualDCApi(); + public void testListServerTypes() { + HttpRequest request = buildGETWithQuery("Action=ListServerType&diskImageId=dummy"); + HttpResponse response = HttpResponse.builder() + .statusCode(200) + .payload(payloadFromResource("/ListServerType-response.xml")) + .build(); + VirtualDCApi api = requestSendsResponse(request, response) + .getVirtualDCApi(); - Set serverTypes = api.listServerTypes(); - assertNotNull(serverTypes, "serverTypes"); - assertEquals(serverTypes.size(), 4, - "Unexpected number of server types: " + serverTypes.size()); - } + Set serverTypes = api.listServerTypes(); + assertNotNull(serverTypes, "serverTypes"); + assertEquals(serverTypes.size(), 4, + "Unexpected number of server types: " + serverTypes.size()); + } - public void testListPublicIPs() { - HttpRequest request = buildGETWithQuery("Action=ListPublicIP"); - HttpResponse response = HttpResponse.builder() - .statusCode(200) - .payload(payloadFromResource("/ListPublicIP-response.xml")) - .build(); - VirtualDCApi api = requestSendsResponse(request, response) - .getVirtualDCApi(); + public void testListPublicIPs() { + HttpRequest request = buildGETWithQuery("Action=ListPublicIP"); + HttpResponse response = HttpResponse.builder() + .statusCode(200) + .payload(payloadFromResource("/ListPublicIP-response.xml")) + .build(); + VirtualDCApi api = requestSendsResponse(request, response) + .getVirtualDCApi(); - Map ips = api.listPublicIPs(); + Map ips = api.listPublicIPs(); - assertNotNull(ips, "ips"); - assertEquals(ips.size(), 2, "Unexpected number of ips: " + ips.size()); - assertEquals(ips.keySet().size(), 2, "Unexpected number of ips: " + ips.size()); - assertTrue(ips.containsValue("ABCDEFGH-A123B456CE"), "missing system id"); - assertEquals(ips.keySet().iterator().next().getVersion(), PublicIP.Version.IPv4); - } + assertNotNull(ips, "ips"); + assertEquals(ips.size(), 2, "Unexpected number of ips: " + ips.size()); + assertEquals(ips.keySet().size(), 2, "Unexpected number of ips: " + ips.size()); + assertTrue(ips.containsValue("ABCDEFGH-A123B456CE"), "missing system id"); + assertEquals(ips.keySet().iterator().next().getVersion(), PublicIP.Version.IPv4); + } - public void testListDiskImages() { - HttpRequest request = buildGETWithQuery("Action=ListDiskImage"); - HttpResponse response = HttpResponse.builder() - .statusCode(200) - .payload(payloadFromResource("/ListDiskImages-response.xml")) - .build(); - VirtualDCApi api = requestSendsResponse(request, response) - .getVirtualDCApi(); + public void testListDiskImages() { + HttpRequest request = buildGETWithQuery("Action=ListDiskImage"); + HttpResponse response = HttpResponse.builder() + .statusCode(200) + .payload(payloadFromResource("/ListDiskImages-response.xml")) + .build(); + VirtualDCApi api = requestSendsResponse(request, response) + .getVirtualDCApi(); - Set images = api.listDiskImages(); + Set images = api.listDiskImages(); - assertNotNull(images, "images"); - assertTrue(images.size() > 5, "Unexpected number of images: " + images.size()); - } + assertNotNull(images, "images"); + assertTrue(images.size() > 5, "Unexpected number of images: " + images.size()); + } - public void testListDiskImage() { - HttpRequest request = buildGETWithQuery("Action=ListDiskImage&vsysDescriptorId=IMG_A1B2C3_1234567890ABCD"); - HttpResponse response = HttpResponse.builder() - .statusCode(200) - .payload(payloadFromResource("/ListDiskImage-response.xml")) - .build(); - VirtualDCApi api = requestSendsResponse(request, response) - .getVirtualDCApi(); + public void testListDiskImage() { + HttpRequest request = buildGETWithQuery("Action=ListDiskImage&vsysDescriptorId=IMG_A1B2C3_1234567890ABCD"); + HttpResponse response = HttpResponse.builder() + .statusCode(200) + .payload(payloadFromResource("/ListDiskImage-response.xml")) + .build(); + VirtualDCApi api = requestSendsResponse(request, response) + .getVirtualDCApi(); - Set images = api.listDiskImages(null, "IMG_A1B2C3_1234567890ABCD"); + Set images = api.listDiskImages(null, "IMG_A1B2C3_1234567890ABCD"); - assertNotNull(images, "images"); - assertTrue(images.size() == 1, "Unexpected number of images: " + images.size()); - } + assertNotNull(images, "images"); + assertTrue(images.size() == 1, "Unexpected number of images: " + images.size()); + } - public void testGetAddressRange() { - HttpRequest request = buildGETWithQuery("Action=GetAddressRange"); - HttpResponse response = HttpResponse.builder() - .statusCode(200) - .payload(payloadFromResource("/GetAddressRange-response.xml")) - .build(); - VirtualDCApi api = requestSendsResponse(request, response) - .getVirtualDCApi(); + public void testGetAddressRange() { + HttpRequest request = buildGETWithQuery("Action=GetAddressRange"); + HttpResponse response = HttpResponse.builder() + .statusCode(200) + .payload(payloadFromResource("/GetAddressRange-response.xml")) + .build(); + VirtualDCApi api = requestSendsResponse(request, response) + .getVirtualDCApi(); - Set range = api.getAddressRange(); - assertNotNull(range); - assertEquals(range.size(), 1); - } + Set range = api.getAddressRange(); + assertNotNull(range); + assertEquals(range.size(), 1); + } - public void testAddAddressRange() { - HttpRequest request = buildGETWithQuery("Action=AddAddressRange" - + "&pipFrom=192.168.0.0" - + "&pipTo=192.168.30.0"); - HttpResponse response = HttpResponse.builder() - .statusCode(200) - .payload(payloadFromResource("/AddAddressRange-response.xml")) - .build(); - VirtualDCApi api = requestSendsResponse(request, response) - .getVirtualDCApi(); + public void testAddAddressRange() { + HttpRequest request = buildGETWithQuery("Action=AddAddressRange" + + "&pipFrom=192.168.0.0" + + "&pipTo=192.168.30.0"); + HttpResponse response = HttpResponse.builder() + .statusCode(200) + .payload(payloadFromResource("/AddAddressRange-response.xml")) + .build(); + VirtualDCApi api = requestSendsResponse(request, response) + .getVirtualDCApi(); - api.addAddressRange("192.168.0.0", "192.168.30.0"); - } + api.addAddressRange("192.168.0.0", "192.168.30.0"); + } - public void testDeleteAddressRange() { - HttpRequest request = buildGETWithQuery("Action=DeleteAddressRange" - + "&pipFrom=192.168.0.0" - + "&pipTo=192.168.30.0"); - HttpResponse response = HttpResponse.builder() - .statusCode(200) - .payload(payloadFromResource("/DeleteAddressRange-response.xml")) - .build(); - VirtualDCApi api = requestSendsResponse(request, response) - .getVirtualDCApi(); + public void testDeleteAddressRange() { + HttpRequest request = buildGETWithQuery("Action=DeleteAddressRange" + + "&pipFrom=192.168.0.0" + + "&pipTo=192.168.30.0"); + HttpResponse response = HttpResponse.builder() + .statusCode(200) + .payload(payloadFromResource("/DeleteAddressRange-response.xml")) + .build(); + VirtualDCApi api = requestSendsResponse(request, response) + .getVirtualDCApi(); - api.deleteAddressRange("192.168.0.0", "192.168.30.0"); - } + api.deleteAddressRange("192.168.0.0", "192.168.30.0"); + } - public void testCreateAddressPool() { - HttpRequest request = buildGETWithQuery("Action=CreateAddressPool" - + "&pipFrom=192.168.0.0" - + "&pipTo=192.168.30.0"); - HttpResponse response = HttpResponse.builder() - .statusCode(200) - .payload(payloadFromResource("/CreateAddressPool-response.xml")) - .build(); - VirtualDCApi api = requestSendsResponse(request, response) - .getVirtualDCApi(); + public void testCreateAddressPool() { + HttpRequest request = buildGETWithQuery("Action=CreateAddressPool" + + "&pipFrom=192.168.0.0" + + "&pipTo=192.168.30.0"); + HttpResponse response = HttpResponse.builder() + .statusCode(200) + .payload(payloadFromResource("/CreateAddressPool-response.xml")) + .build(); + VirtualDCApi api = requestSendsResponse(request, response) + .getVirtualDCApi(); - api.createAddressPool("192.168.0.0", "192.168.30.0"); - } + api.createAddressPool("192.168.0.0", "192.168.30.0"); + } - public void testGetEventLog() { - HttpRequest request = buildGETWithQuery("Action=GetEventLog"); - HttpResponse response = HttpResponse.builder() - .statusCode(200) - .payload(payloadFromResource("/GetEventLog-response.xml")) - .build(); - VirtualDCApi api = requestSendsResponse(request, response) - .getVirtualDCApi(); + public void testGetEventLog() { + HttpRequest request = buildGETWithQuery("Action=GetEventLog"); + HttpResponse response = HttpResponse.builder() + .statusCode(200) + .payload(payloadFromResource("/GetEventLog-response.xml")) + .build(); + VirtualDCApi api = requestSendsResponse(request, response) + .getVirtualDCApi(); - Set logs = api.getEventLogs(); - assertNotNull(logs); - //TODO: get one with several -// assertEquals(logs.size(), 1); - } + Set logs = api.getEventLogs(); + assertNotNull(logs); + //TODO: get one with several +// assertEquals(logs.size(), 1); + } diff --git a/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/services/VirtualDCApiLiveTest.java b/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/services/VirtualDCApiLiveTest.java index 0e873ed543..16a5191972 100644 --- a/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/services/VirtualDCApiLiveTest.java +++ b/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/services/VirtualDCApiLiveTest.java @@ -34,43 +34,43 @@ import org.testng.annotations.Test; @Test(groups = "live", enabled = true, singleThreaded = true, testName = "VirtualDCApiLiveTest") public class VirtualDCApiLiveTest extends BaseFGCPApiLiveTest { - private VirtualDCApi api; + private VirtualDCApi api; - @BeforeGroups(groups = { "live" }) - public void setupContext() { - super.setupContext(); - api = fgcpContext.getApi().getVirtualDCApi(); - } + @BeforeGroups(groups = { "live" }) + public void setupContext() { + super.setupContext(); + api = fgcpContext.getApi().getVirtualDCApi(); + } - public void testListVirtualSystems() { -/* Properties overrides = setupProperties(); - RestContext context = new RestContextFactory().createContext(provider, ImmutableSet. of(new Log4JLoggingModule()), - overrides);*/ + public void testListVirtualSystems() { +/* Properties overrides = setupProperties(); + RestContext context = new RestContextFactory().createContext(provider, ImmutableSet. of(new Log4JLoggingModule()), + overrides);*/ - Set vsysSet = api.listVirtualSystems(); - assertNotNull(vsysSet, "vsysSet"); - assertTrue(vsysSet.size() > 0, "vsysSet.size() should be greater than 0"); - for (VSystem vsys : vsysSet) { - System.out.println(vsys); - } - } + Set vsysSet = api.listVirtualSystems(); + assertNotNull(vsysSet, "vsysSet"); + assertTrue(vsysSet.size() > 0, "vsysSet.size() should be greater than 0"); + for (VSystem vsys : vsysSet) { + System.out.println(vsys); + } + } -/* public void testCreateVirtualSystem() { - String vsysId = api.createVirtualSystem("abc", "def"); +/* public void testCreateVirtualSystem() { + String vsysId = api.createVirtualSystem("abc", "def"); - assertNotNull(vsysId, "vsysId"); - assertFalse(vsysId.equals(""), "vsysId is empty (\"\")"); - System.out.println("vsysId: " + vsysId); - }*/ + assertNotNull(vsysId, "vsysId"); + assertFalse(vsysId.equals(""), "vsysId is empty (\"\")"); + System.out.println("vsysId: " + vsysId); + }*/ - public void testListServerTypes() { - Set serverTypes = api.listServerTypes(); + public void testListServerTypes() { + Set serverTypes = api.listServerTypes(); - assertNotNull(serverTypes, "serverTypes"); - assertTrue(serverTypes.size() == 4, "serverTypes.size should return 4, not " + serverTypes.size()); + assertNotNull(serverTypes, "serverTypes"); + assertTrue(serverTypes.size() == 4, "serverTypes.size should return 4, not " + serverTypes.size()); -// System.out.println("listServerTypes: " + serverTypes); - } +// System.out.println("listServerTypes: " + serverTypes); + } diff --git a/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/services/VirtualServerApiExpectTest.java b/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/services/VirtualServerApiExpectTest.java index 198993c25d..b6e4ec7d97 100644 --- a/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/services/VirtualServerApiExpectTest.java +++ b/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/services/VirtualServerApiExpectTest.java @@ -18,8 +18,8 @@ */ package org.jclouds.fujitsu.fgcp.services; -import static org.testng.AssertJUnit.assertNotNull; import static org.testng.Assert.assertEquals; +import static org.testng.AssertJUnit.assertNotNull; import org.jclouds.fujitsu.fgcp.domain.VServerStatus; import org.jclouds.fujitsu.fgcp.domain.VServerWithDetails; @@ -33,189 +33,189 @@ import org.testng.annotations.Test; @Test(groups = "unit", testName = "VirtualServerApiExpectTest", singleThreaded = true) public class VirtualServerApiExpectTest extends BaseFGCPRestApiExpectTest { - public void testStart() { - HttpRequest request = buildGETWithQuery("Action=StartVServer" - + "&vserverId=CONTRACT-VSYS00001-S-0005" - + "&vsysId=CONTRACT-VSYS00001"); - HttpResponse response = HttpResponse.builder().statusCode(200) - .payload(payloadFromResource("/StartVServer-response.xml")) - .build(); + public void testStart() { + HttpRequest request = buildGETWithQuery("Action=StartVServer" + + "&vserverId=CONTRACT-VSYS00001-S-0005" + + "&vsysId=CONTRACT-VSYS00001"); + HttpResponse response = HttpResponse.builder().statusCode(200) + .payload(payloadFromResource("/StartVServer-response.xml")) + .build(); - VirtualServerApi api = requestSendsResponse(request, response) - .getVirtualServerApi(); + VirtualServerApi api = requestSendsResponse(request, response) + .getVirtualServerApi(); - api.start("CONTRACT-VSYS00001-S-0005"); - } + api.start("CONTRACT-VSYS00001-S-0005"); + } - public void testStop() { - HttpRequest request = buildGETWithQuery("Action=StopVServer" - + "&vserverId=CONTRACT-VSYS00001-S-0005" - + "&vsysId=CONTRACT-VSYS00001"); - HttpResponse response = HttpResponse.builder().statusCode(200) - .payload(payloadFromResource("/StopVServer-response.xml")) - .build(); + public void testStop() { + HttpRequest request = buildGETWithQuery("Action=StopVServer" + + "&vserverId=CONTRACT-VSYS00001-S-0005" + + "&vsysId=CONTRACT-VSYS00001"); + HttpResponse response = HttpResponse.builder().statusCode(200) + .payload(payloadFromResource("/StopVServer-response.xml")) + .build(); - VirtualServerApi api = requestSendsResponse(request, response) - .getVirtualServerApi(); + VirtualServerApi api = requestSendsResponse(request, response) + .getVirtualServerApi(); - api.stop("CONTRACT-VSYS00001-S-0005"); - } + api.stop("CONTRACT-VSYS00001-S-0005"); + } - public void testStopForcefully() { - HttpRequest request = buildGETWithQuery("Action=StopVServer" - + "&force=true" - + "&vserverId=CONTRACT-VSYS00001-S-0005" - + "&vsysId=CONTRACT-VSYS00001"); - HttpResponse response = HttpResponse.builder().statusCode(200) - .payload(payloadFromResource("/StopVServer-response.xml")) - .build(); + public void testStopForcefully() { + HttpRequest request = buildGETWithQuery("Action=StopVServer" + + "&force=true" + + "&vserverId=CONTRACT-VSYS00001-S-0005" + + "&vsysId=CONTRACT-VSYS00001"); + HttpResponse response = HttpResponse.builder().statusCode(200) + .payload(payloadFromResource("/StopVServer-response.xml")) + .build(); - VirtualServerApi api = requestSendsResponse(request, response) - .getVirtualServerApi(); + VirtualServerApi api = requestSendsResponse(request, response) + .getVirtualServerApi(); - api.stopForcefully("CONTRACT-VSYS00001-S-0005"); - } + api.stopForcefully("CONTRACT-VSYS00001-S-0005"); + } - public void testDestroy() { - HttpRequest request = buildGETWithQuery("Action=DestroyVServer" - + "&vserverId=CONTRACT-VSYS00001-S-0005" - + "&vsysId=CONTRACT-VSYS00001"); - HttpResponse response = HttpResponse.builder().statusCode(200) - .payload(payloadFromResource("/DestroyVServer-response.xml")) - .build(); + public void testDestroy() { + HttpRequest request = buildGETWithQuery("Action=DestroyVServer" + + "&vserverId=CONTRACT-VSYS00001-S-0005" + + "&vsysId=CONTRACT-VSYS00001"); + HttpResponse response = HttpResponse.builder().statusCode(200) + .payload(payloadFromResource("/DestroyVServer-response.xml")) + .build(); - VirtualServerApi api = requestSendsResponse(request, response) - .getVirtualServerApi(); + VirtualServerApi api = requestSendsResponse(request, response) + .getVirtualServerApi(); - api.destroy("CONTRACT-VSYS00001-S-0005"); - } + api.destroy("CONTRACT-VSYS00001-S-0005"); + } - public void testGet() { - HttpRequest request = buildGETWithQuery("Action=GetVServerAttributes" - + "&vserverId=CONTRACT-VSYS00001-S-0005" - + "&vsysId=CONTRACT-VSYS00001"); - HttpResponse response = HttpResponse - .builder() - .statusCode(200) - .payload( - payloadFromResource("/GetVServerAttributes-response.xml")) - .build(); + public void testGet() { + HttpRequest request = buildGETWithQuery("Action=GetVServerAttributes" + + "&vserverId=CONTRACT-VSYS00001-S-0005" + + "&vsysId=CONTRACT-VSYS00001"); + HttpResponse response = HttpResponse + .builder() + .statusCode(200) + .payload( + payloadFromResource("/GetVServerAttributes-response.xml")) + .build(); - VirtualServerApi api = requestSendsResponse(request, response) - .getVirtualServerApi(); + VirtualServerApi api = requestSendsResponse(request, response) + .getVirtualServerApi(); - assertNotNull(api.get("CONTRACT-VSYS00001-S-0005")); - } + assertNotNull(api.get("CONTRACT-VSYS00001-S-0005")); + } - public void testGetDetails() { - HttpRequest request = buildGETWithQuery("Action=GetVServerConfiguration" - + "&vserverId=CONTRACT-VSYS00001-S-0005" - + "&vsysId=CONTRACT-VSYS00001"); - HttpResponse response = HttpResponse - .builder() - .statusCode(200) - .payload( - payloadFromResource("/GetVServerConfiguration-response.xml")) - .build(); + public void testGetDetails() { + HttpRequest request = buildGETWithQuery("Action=GetVServerConfiguration" + + "&vserverId=CONTRACT-VSYS00001-S-0005" + + "&vsysId=CONTRACT-VSYS00001"); + HttpResponse response = HttpResponse + .builder() + .statusCode(200) + .payload( + payloadFromResource("/GetVServerConfiguration-response.xml")) + .build(); - VirtualServerApi api = requestSendsResponse(request, response) - .getVirtualServerApi(); + VirtualServerApi api = requestSendsResponse(request, response) + .getVirtualServerApi(); - VServerWithDetails server = api.getDetails("CONTRACT-VSYS00001-S-0005"); - assertNotNull(server); - assertEquals(server.getId(), "CONTRACT-VSYS00001-S-0005"); - assertEquals(server.getVnics().iterator().next().getNicNo(), 0); - assertEquals(server.getVnics().iterator().next().getPrivateIp(), "192.168.4.13"); - assertEquals(server.getVnics().iterator().next().getNetworkId(), "CONTRACT-VSYS00001-N-DMZ"); - assertEquals(server.getImage().getId(), "IMG_A1B2C3_1234567890ABCD"); - assertEquals(server.getImage().getSysvolSize(), 10.0f); - } + VServerWithDetails server = api.getDetails("CONTRACT-VSYS00001-S-0005"); + assertNotNull(server); + assertEquals(server.getId(), "CONTRACT-VSYS00001-S-0005"); + assertEquals(server.getVnics().iterator().next().getNicNo(), 0); + assertEquals(server.getVnics().iterator().next().getPrivateIp(), "192.168.4.13"); + assertEquals(server.getVnics().iterator().next().getNetworkId(), "CONTRACT-VSYS00001-N-DMZ"); + assertEquals(server.getImage().getId(), "IMG_A1B2C3_1234567890ABCD"); + assertEquals(server.getImage().getSysvolSize(), 10.0f); + } - public void testGetStatus() { - HttpRequest request = buildGETWithQuery("Action=GetVServerStatus" - + "&vserverId=CONTRACT-VSYS00001-S-0005" - + "&vsysId=CONTRACT-VSYS00001"); - HttpResponse response = HttpResponse - .builder() - .statusCode(200) - .payload( - payloadFromResource("/GetVServerStatus-response.xml")) - .build(); + public void testGetStatus() { + HttpRequest request = buildGETWithQuery("Action=GetVServerStatus" + + "&vserverId=CONTRACT-VSYS00001-S-0005" + + "&vsysId=CONTRACT-VSYS00001"); + HttpResponse response = HttpResponse + .builder() + .statusCode(200) + .payload( + payloadFromResource("/GetVServerStatus-response.xml")) + .build(); - VirtualServerApi api = requestSendsResponse(request, response) - .getVirtualServerApi(); + VirtualServerApi api = requestSendsResponse(request, response) + .getVirtualServerApi(); - assertEquals(api.getStatus("CONTRACT-VSYS00001-S-0005"), VServerStatus.STOPPED); - } + assertEquals(api.getStatus("CONTRACT-VSYS00001-S-0005"), VServerStatus.STOPPED); + } - public void testInitialPassword() { - HttpRequest request = buildGETWithQuery("Action=GetVServerInitialPassword" - + "&vserverId=CONTRACT-VSYS00001-S-0005" - + "&vsysId=CONTRACT-VSYS00001"); - HttpResponse response = HttpResponse - .builder() - .statusCode(200) - .payload( - payloadFromResource("/GetVServerInitialPassword-response.xml")) - .build(); + public void testInitialPassword() { + HttpRequest request = buildGETWithQuery("Action=GetVServerInitialPassword" + + "&vserverId=CONTRACT-VSYS00001-S-0005" + + "&vsysId=CONTRACT-VSYS00001"); + HttpResponse response = HttpResponse + .builder() + .statusCode(200) + .payload( + payloadFromResource("/GetVServerInitialPassword-response.xml")) + .build(); - VirtualServerApi api = requestSendsResponse(request, response) - .getVirtualServerApi(); + VirtualServerApi api = requestSendsResponse(request, response) + .getVirtualServerApi(); - assertEquals(api.getInitialPassword("CONTRACT-VSYS00001-S-0005"), "mySecretpwd1"); - } + assertEquals(api.getInitialPassword("CONTRACT-VSYS00001-S-0005"), "mySecretpwd1"); + } - public void testUpdate() { - HttpRequest request = buildGETWithQuery("Action=UpdateVServerAttribute" - + "&vserverId=CONTRACT-VSYS00001-S-0005" - + "&attributeValue=new%20name" - + "&attributeName=vserverName" - + "&vsysId=CONTRACT-VSYS00001"); - HttpResponse response = HttpResponse - .builder() - .statusCode(200) - .payload( - payloadFromResource("/UpdateVServerAttribute-response.xml")) - .build(); + public void testUpdate() { + HttpRequest request = buildGETWithQuery("Action=UpdateVServerAttribute" + + "&vserverId=CONTRACT-VSYS00001-S-0005" + + "&attributeValue=new%20name" + + "&attributeName=vserverName" + + "&vsysId=CONTRACT-VSYS00001"); + HttpResponse response = HttpResponse + .builder() + .statusCode(200) + .payload( + payloadFromResource("/UpdateVServerAttribute-response.xml")) + .build(); - VirtualServerApi api = requestSendsResponse(request, response) - .getVirtualServerApi(); + VirtualServerApi api = requestSendsResponse(request, response) + .getVirtualServerApi(); - api.update("CONTRACT-VSYS00001-S-0005", "vserverName", "new name"); - } + api.update("CONTRACT-VSYS00001-S-0005", "vserverName", "new name"); + } - public void testAttachDisk() { - HttpRequest request = buildGETWithQuery("Action=AttachVDisk" - + "&vserverId=CONTRACT-VSYS00001-S-0005" - + "&vdiskId=CONTRACT-VSYS00001-D-0001" - + "&vsysId=CONTRACT-VSYS00001"); - HttpResponse response = HttpResponse.builder().statusCode(200) - .payload(payloadFromResource("/AttachVDisk-response.xml")) - .build(); + public void testAttachDisk() { + HttpRequest request = buildGETWithQuery("Action=AttachVDisk" + + "&vserverId=CONTRACT-VSYS00001-S-0005" + + "&vdiskId=CONTRACT-VSYS00001-D-0001" + + "&vsysId=CONTRACT-VSYS00001"); + HttpResponse response = HttpResponse.builder().statusCode(200) + .payload(payloadFromResource("/AttachVDisk-response.xml")) + .build(); - VirtualServerApi api = requestSendsResponse(request, response) - .getVirtualServerApi(); + VirtualServerApi api = requestSendsResponse(request, response) + .getVirtualServerApi(); - api.attachDisk("CONTRACT-VSYS00001-S-0005", "CONTRACT-VSYS00001-D-0001"); - } + api.attachDisk("CONTRACT-VSYS00001-S-0005", "CONTRACT-VSYS00001-D-0001"); + } -/* public void testGetPerformanceInformation() { - HttpRequest request = buildGETWithQuery("Action=GetPerformanceInformation" - + "&serverId=CONTRACT-VSYS00001-S-0005" - + "&interval=10minute" - + "&vsysId=CONTRACT-VSYS00001"); - HttpResponse response = HttpResponse - .builder() - .statusCode(200) - .payload( - payloadFromResource("/GetPerformanceInformation-response.xml")) - .build(); +/* public void testGetPerformanceInformation() { + HttpRequest request = buildGETWithQuery("Action=GetPerformanceInformation" + + "&serverId=CONTRACT-VSYS00001-S-0005" + + "&interval=10minute" + + "&vsysId=CONTRACT-VSYS00001"); + HttpResponse response = HttpResponse + .builder() + .statusCode(200) + .payload( + payloadFromResource("/GetPerformanceInformation-response.xml")) + .build(); - VirtualServerApi api = requestSendsResponse(request, response) - .getVirtualServerApi(); + VirtualServerApi api = requestSendsResponse(request, response) + .getVirtualServerApi(); - assertNotNull(api.getPerformanceInformation( - "CONTRACT-VSYS00001-S-0005", "10minute")); - } + assertNotNull(api.getPerformanceInformation( + "CONTRACT-VSYS00001-S-0005", "10minute")); + } */ } diff --git a/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/services/VirtualSystemApiExpectTest.java b/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/services/VirtualSystemApiExpectTest.java index 31aaed1946..79fc009811 100644 --- a/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/services/VirtualSystemApiExpectTest.java +++ b/labs/fgcp/src/test/java/org/jclouds/fujitsu/fgcp/services/VirtualSystemApiExpectTest.java @@ -40,220 +40,220 @@ import org.testng.annotations.Test; @Test(groups = "unit", testName = "VirtualSystemApiExpectTest", singleThreaded = true) public class VirtualSystemApiExpectTest extends BaseFGCPRestApiExpectTest { - public void testGet() { - HttpRequest request = buildGETWithQuery("Action=GetVSYSAttributes&vsysId=ABCDEFGH-A123B456CE"); - HttpResponse response = HttpResponse - .builder() - .statusCode(200) - .payload( - payloadFromResource("/GetVSYSAttributes-response.xml")) - .build(); - VirtualSystemApi api = requestSendsResponse(request, response) - .getVirtualSystemApi(); + public void testGet() { + HttpRequest request = buildGETWithQuery("Action=GetVSYSAttributes&vsysId=ABCDEFGH-A123B456CE"); + HttpResponse response = HttpResponse + .builder() + .statusCode(200) + .payload( + payloadFromResource("/GetVSYSAttributes-response.xml")) + .build(); + VirtualSystemApi api = requestSendsResponse(request, response) + .getVirtualSystemApi(); - VSystem system = api.get("ABCDEFGH-A123B456CE"); - assertNotNull(system, "system"); - } + VSystem system = api.get("ABCDEFGH-A123B456CE"); + assertNotNull(system, "system"); + } - public void testGetDetails() { - HttpRequest request = buildGETWithQuery("Action=GetVSYSConfiguration&vsysId=ABCDEFGH-A123B456CE"); - HttpResponse response = HttpResponse - .builder() - .statusCode(200) - .payload( - payloadFromResource("/GetVSYSConfiguration-response.xml")) - .build(); - VirtualSystemApi api = requestSendsResponse(request, response) - .getVirtualSystemApi(); + public void testGetDetails() { + HttpRequest request = buildGETWithQuery("Action=GetVSYSConfiguration&vsysId=ABCDEFGH-A123B456CE"); + HttpResponse response = HttpResponse + .builder() + .statusCode(200) + .payload( + payloadFromResource("/GetVSYSConfiguration-response.xml")) + .build(); + VirtualSystemApi api = requestSendsResponse(request, response) + .getVirtualSystemApi(); - VSystem system = api.getDetails("ABCDEFGH-A123B456CE"); - assertNotNull(system, "system"); - } + VSystem system = api.getDetails("ABCDEFGH-A123B456CE"); + assertNotNull(system, "system"); + } - public void testGetStatus() { - HttpRequest request = buildGETWithQuery("Action=GetVSYSStatus" - + "&vsysId=ABCDEFGH-A123B456CE"); - HttpResponse response = HttpResponse.builder().statusCode(200) - .payload(payloadFromResource("/GetVSYSStatus-response.xml")) - .build(); - VirtualSystemApi api = requestSendsResponse(request, response) - .getVirtualSystemApi(); + public void testGetStatus() { + HttpRequest request = buildGETWithQuery("Action=GetVSYSStatus" + + "&vsysId=ABCDEFGH-A123B456CE"); + HttpResponse response = HttpResponse.builder().statusCode(200) + .payload(payloadFromResource("/GetVSYSStatus-response.xml")) + .build(); + VirtualSystemApi api = requestSendsResponse(request, response) + .getVirtualSystemApi(); - assertEquals(api.getStatus("ABCDEFGH-A123B456CE"), VSystemStatus.NORMAL); - } + assertEquals(api.getStatus("ABCDEFGH-A123B456CE"), VSystemStatus.NORMAL); + } - public void testUpdate() { - HttpRequest request = buildGETWithQuery("Action=UpdateVSYSAttribute" - + "&vsysId=ABCDEFGH-A123B456CE" + "&attributeValue=new-name" - + "&attributeName=updateName"); - HttpResponse response = HttpResponse - .builder() - .statusCode(200) - .payload( - payloadFromResource("/UpdateVDiskAttribute-response.xml")) - .build(); + public void testUpdate() { + HttpRequest request = buildGETWithQuery("Action=UpdateVSYSAttribute" + + "&vsysId=ABCDEFGH-A123B456CE" + "&attributeValue=new-name" + + "&attributeName=updateName"); + HttpResponse response = HttpResponse + .builder() + .statusCode(200) + .payload( + payloadFromResource("/UpdateVDiskAttribute-response.xml")) + .build(); - VirtualSystemApi api = requestSendsResponse(request, response) - .getVirtualSystemApi(); + VirtualSystemApi api = requestSendsResponse(request, response) + .getVirtualSystemApi(); - api.update("ABCDEFGH-A123B456CE", "updateName", "new-name"); - } + api.update("ABCDEFGH-A123B456CE", "updateName", "new-name"); + } - public void testListPublicIPs() { - HttpRequest request = buildGETWithQuery("Action=ListPublicIP" - + "&vsysId=ABCDEFGH-A123B456CE"); - HttpResponse response = HttpResponse - .builder() - .statusCode(200) - .payload( - payloadFromResource("/ListPublicIP_one_vsys-response.xml")) - .build(); - VirtualSystemApi api = requestSendsResponse(request, response) - .getVirtualSystemApi(); + public void testListPublicIPs() { + HttpRequest request = buildGETWithQuery("Action=ListPublicIP" + + "&vsysId=ABCDEFGH-A123B456CE"); + HttpResponse response = HttpResponse + .builder() + .statusCode(200) + .payload( + payloadFromResource("/ListPublicIP_one_vsys-response.xml")) + .build(); + VirtualSystemApi api = requestSendsResponse(request, response) + .getVirtualSystemApi(); - Set ips = api.listPublicIPs("ABCDEFGH-A123B456CE"); - assertNotNull(ips, "ips"); - assertTrue(ips.size() == 2, "Unexpected number of ips: " + ips.size()); - assertEquals(ips.iterator().next().getVersion(), PublicIP.Version.IPv4); - } + Set ips = api.listPublicIPs("ABCDEFGH-A123B456CE"); + assertNotNull(ips, "ips"); + assertTrue(ips.size() == 2, "Unexpected number of ips: " + ips.size()); + assertEquals(ips.iterator().next().getVersion(), PublicIP.Version.IPv4); + } - public void testListServers() { - HttpRequest request = buildGETWithQuery("Action=ListVServer" - + "&vsysId=ABCDEFGH-A123B456CE"); - HttpResponse response = HttpResponse - .builder() - .statusCode(200) - .payload( - payloadFromResource("/ListVServer-response.xml")) - .build(); - VirtualSystemApi api = requestSendsResponse(request, response) - .getVirtualSystemApi(); + public void testListServers() { + HttpRequest request = buildGETWithQuery("Action=ListVServer" + + "&vsysId=ABCDEFGH-A123B456CE"); + HttpResponse response = HttpResponse + .builder() + .statusCode(200) + .payload( + payloadFromResource("/ListVServer-response.xml")) + .build(); + VirtualSystemApi api = requestSendsResponse(request, response) + .getVirtualSystemApi(); - Set servers = api.listServers("ABCDEFGH-A123B456CE"); - assertNotNull(servers, "servers"); - assertEquals(servers.size(), 2); - } + Set servers = api.listServers("ABCDEFGH-A123B456CE"); + assertNotNull(servers, "servers"); + assertEquals(servers.size(), 2); + } - public void testDisks() { - HttpRequest request = buildGETWithQuery("Action=ListVDisk" - + "&vsysId=ABCDEFGH-A123B456CE"); - HttpResponse response = HttpResponse - .builder() - .statusCode(200) - .payload( - payloadFromResource("/ListVDisk-response.xml")) - .build(); - VirtualSystemApi api = requestSendsResponse(request, response) - .getVirtualSystemApi(); + public void testDisks() { + HttpRequest request = buildGETWithQuery("Action=ListVDisk" + + "&vsysId=ABCDEFGH-A123B456CE"); + HttpResponse response = HttpResponse + .builder() + .statusCode(200) + .payload( + payloadFromResource("/ListVDisk-response.xml")) + .build(); + VirtualSystemApi api = requestSendsResponse(request, response) + .getVirtualSystemApi(); - Set disks = api.listDisks("ABCDEFGH-A123B456CE"); - assertNotNull(disks, "disks"); - assertEquals(disks.size(), 1); - } + Set disks = api.listDisks("ABCDEFGH-A123B456CE"); + assertNotNull(disks, "disks"); + assertEquals(disks.size(), 1); + } - public void testListBuiltinServers() { - HttpRequest request = buildGETWithQuery("Action=ListEFM" - + "&vsysId=ABCDEFGH-A123B456CE" + "&efmType=FW"); - HttpResponse response = HttpResponse - .builder() - .statusCode(200) - .payload( - payloadFromResource("/ListEFM-response.xml")) - .build(); - VirtualSystemApi api = requestSendsResponse(request, response) - .getVirtualSystemApi(); + public void testListBuiltinServers() { + HttpRequest request = buildGETWithQuery("Action=ListEFM" + + "&vsysId=ABCDEFGH-A123B456CE" + "&efmType=FW"); + HttpResponse response = HttpResponse + .builder() + .statusCode(200) + .payload( + payloadFromResource("/ListEFM-response.xml")) + .build(); + VirtualSystemApi api = requestSendsResponse(request, response) + .getVirtualSystemApi(); - Set fws = api.listBuiltinServers("ABCDEFGH-A123B456CE", "FW"); - assertNotNull(fws, "fws"); - assertEquals(fws.size(), 1); - } + Set fws = api.listBuiltinServers("ABCDEFGH-A123B456CE", "FW"); + assertNotNull(fws, "fws"); + assertEquals(fws.size(), 1); + } - public void testAllocatePublicIP() { - HttpRequest request = buildGETWithQuery("Action=AllocatePublicIP&vsysId=ABCDEFGH-A123B456CE"); - HttpResponse response = HttpResponse - .builder() - .statusCode(200) - .payload( - payloadFromResource("/AllocatePublicIP-response.xml")) - .build(); - VirtualSystemApi api = requestSendsResponse(request, response) - .getVirtualSystemApi(); + public void testAllocatePublicIP() { + HttpRequest request = buildGETWithQuery("Action=AllocatePublicIP&vsysId=ABCDEFGH-A123B456CE"); + HttpResponse response = HttpResponse + .builder() + .statusCode(200) + .payload( + payloadFromResource("/AllocatePublicIP-response.xml")) + .build(); + VirtualSystemApi api = requestSendsResponse(request, response) + .getVirtualSystemApi(); - api.allocatePublicIP("ABCDEFGH-A123B456CE"); - } + api.allocatePublicIP("ABCDEFGH-A123B456CE"); + } - public void testCreateBuiltinServer() { - HttpRequest request = buildGETWithQuery("Action=CreateEFM" - + "&efmType=SLB" - + "&efmName=web%20load%20balancer" - + "&networkId=ABCDEFGH-A123B456CE-N-DMZ" - + "&vsysId=ABCDEFGH-A123B456CE"); - HttpResponse response = HttpResponse - .builder() - .statusCode(200) - .payload( - payloadFromResource("/CreateEFM-response.xml")) - .build(); - VirtualSystemApi api = requestSendsResponse(request, response) - .getVirtualSystemApi(); + public void testCreateBuiltinServer() { + HttpRequest request = buildGETWithQuery("Action=CreateEFM" + + "&efmType=SLB" + + "&efmName=web%20load%20balancer" + + "&networkId=ABCDEFGH-A123B456CE-N-DMZ" + + "&vsysId=ABCDEFGH-A123B456CE"); + HttpResponse response = HttpResponse + .builder() + .statusCode(200) + .payload( + payloadFromResource("/CreateEFM-response.xml")) + .build(); + VirtualSystemApi api = requestSendsResponse(request, response) + .getVirtualSystemApi(); - String id = api.createBuiltinServer("web load balancer", - "ABCDEFGH-A123B456CE-N-DMZ"); - assertEquals(id, "CONTRACT-EFM00001"); - } + String id = api.createBuiltinServer("web load balancer", + "ABCDEFGH-A123B456CE-N-DMZ"); + assertEquals(id, "CONTRACT-EFM00001"); + } - public void testCreateServer() { - HttpRequest request = buildGETWithQuery("Action=CreateVServer" - + "&vserverName=vm1" - + "&diskImageId=IMG_A1B2C3_1234567890ABCD" - + "&vserverType=economy" - + "&networkId=ABCDEFGH-A123B456CE-N-DMZ" - + "&vsysId=ABCDEFGH-A123B456CE"); - HttpResponse response = HttpResponse - .builder() - .statusCode(200) - .payload( - payloadFromResource("/CreateVServer-response.xml")) - .build(); - VirtualSystemApi api = requestSendsResponse(request, response) - .getVirtualSystemApi(); + public void testCreateServer() { + HttpRequest request = buildGETWithQuery("Action=CreateVServer" + + "&vserverName=vm1" + + "&diskImageId=IMG_A1B2C3_1234567890ABCD" + + "&vserverType=economy" + + "&networkId=ABCDEFGH-A123B456CE-N-DMZ" + + "&vsysId=ABCDEFGH-A123B456CE"); + HttpResponse response = HttpResponse + .builder() + .statusCode(200) + .payload( + payloadFromResource("/CreateVServer-response.xml")) + .build(); + VirtualSystemApi api = requestSendsResponse(request, response) + .getVirtualSystemApi(); - String id = api.createServer("vm1", "economy", "IMG_A1B2C3_1234567890ABCD", - "ABCDEFGH-A123B456CE-N-DMZ"); - assertEquals(id, "ABCDEFGH-A123B456CE-S-0007"); - } + String id = api.createServer("vm1", "economy", "IMG_A1B2C3_1234567890ABCD", + "ABCDEFGH-A123B456CE-N-DMZ"); + assertEquals(id, "ABCDEFGH-A123B456CE-S-0007"); + } - public void testCreateDisk() { - HttpRequest request = buildGETWithQuery("Action=CreateVDisk" - + "&vsysId=ABCDEFGH-A123B456CE" - + "&size=10" - + "&vdiskName=disk1"); - HttpResponse response = HttpResponse - .builder() - .statusCode(200) - .payload( - payloadFromResource("/CreateVDisk-response.xml")) - .build(); - VirtualSystemApi api = requestSendsResponse(request, response) - .getVirtualSystemApi(); + public void testCreateDisk() { + HttpRequest request = buildGETWithQuery("Action=CreateVDisk" + + "&vsysId=ABCDEFGH-A123B456CE" + + "&size=10" + + "&vdiskName=disk1"); + HttpResponse response = HttpResponse + .builder() + .statusCode(200) + .payload( + payloadFromResource("/CreateVDisk-response.xml")) + .build(); + VirtualSystemApi api = requestSendsResponse(request, response) + .getVirtualSystemApi(); - String id = api.createDisk("ABCDEFGH-A123B456CE", "disk1", 10); - assertEquals(id, "ABCDEFGH-A123B456CE-S-0006"); - } + String id = api.createDisk("ABCDEFGH-A123B456CE", "disk1", 10); + assertEquals(id, "ABCDEFGH-A123B456CE-S-0006"); + } /* - public void testRegisterAsPrivateImage() { - HttpRequest request = buildGETWithQuery("Action=AllocatePublicIP&vsysId=ABCDEFGH-A123B456CE"); - HttpResponse response = HttpResponse - .builder() - .statusCode(200) - .payload( - payloadFromResource("/AllocatePublicIP-response.xml")) - .build(); - VirtualSystemApi api = requestSendsResponse(request, response) - .getVirtualSystemApi(); + public void testRegisterAsPrivateImage() { + HttpRequest request = buildGETWithQuery("Action=AllocatePublicIP&vsysId=ABCDEFGH-A123B456CE"); + HttpResponse response = HttpResponse + .builder() + .statusCode(200) + .payload( + payloadFromResource("/AllocatePublicIP-response.xml")) + .build(); + VirtualSystemApi api = requestSendsResponse(request, response) + .getVirtualSystemApi(); - api.registerAsPrivateVSYSDescriptor("ABCDEFGH-A123B456CE"); - } + api.registerAsPrivateVSYSDescriptor("ABCDEFGH-A123B456CE"); + } */ } diff --git a/labs/fgcp/src/test/java/org/jclouds/http/internal/HttpInternalsLiveTest.java b/labs/fgcp/src/test/java/org/jclouds/http/internal/HttpInternalsLiveTest.java index 7ab8c2a667..e600072a1c 100644 --- a/labs/fgcp/src/test/java/org/jclouds/http/internal/HttpInternalsLiveTest.java +++ b/labs/fgcp/src/test/java/org/jclouds/http/internal/HttpInternalsLiveTest.java @@ -31,8 +31,8 @@ import org.testng.annotations.Test; @Test(groups = "live", enabled = true, singleThreaded = true, testName = "HttpInternalsLiveTest") public class HttpInternalsLiveTest extends BaseFGCPApiLiveTest { - @Test - public void testTrustedSSLContext() { - assertNotNull(context.utils().injector().getInstance(JavaUrlHttpCommandExecutorService.class).sslContextSupplier); - } + @Test + public void testTrustedSSLContext() { + assertNotNull(context.utils().injector().getInstance(JavaUrlHttpCommandExecutorService.class).sslContextSupplier); + } } diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/options/EditAccountOptions.java b/labs/glesys/src/main/java/org/jclouds/glesys/options/EditAccountOptions.java deleted file mode 100644 index 4d2d164435..0000000000 --- a/labs/glesys/src/main/java/org/jclouds/glesys/options/EditAccountOptions.java +++ /dev/null @@ -1,77 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.glesys.options; - - -/** - * @author Adam Lowe - * @see - */ -public class EditAccountOptions extends CreateAccountOptions { - - public static class Builder { - /** - * @see org.jclouds.glesys.options.EditAccountOptions#antispamLevel - */ - public static EditAccountOptions antispamLevel(int antispamLevel) { - return EditAccountOptions.class.cast(new EditAccountOptions().antispamLevel(antispamLevel)); - } - - /** - * @see org.jclouds.glesys.options.EditAccountOptions#antiVirus - */ - public static EditAccountOptions antiVirus(boolean antiVirus) { - return EditAccountOptions.class.cast(new EditAccountOptions().antiVirus(antiVirus)); - } - - /** - * @see org.jclouds.glesys.options.EditAccountOptions#autorespond - */ - public static EditAccountOptions autorespond(boolean autorespond) { - return EditAccountOptions.class.cast(new EditAccountOptions().autorespond(autorespond)); - } - - /** - * @see org.jclouds.glesys.options.EditAccountOptions#autorespondSaveEmail - */ - public static EditAccountOptions autorespondSaveEmail(boolean autorespondSaveEmail) { - return EditAccountOptions.class.cast(new EditAccountOptions().autorespondSaveEmail(autorespondSaveEmail)); - } - - /** - * @see org.jclouds.glesys.options.EditAccountOptions#autorespondMessage - */ - public static EditAccountOptions autorespondMessage(String autorespondMessage) { - return EditAccountOptions.class.cast(new EditAccountOptions().autorespondMessage(autorespondMessage)); - } - - /** - * @see org.jclouds.glesys.options.EditAccountOptions#password - */ - public static EditAccountOptions password(String password) { - return new EditAccountOptions().password(password); - } - } - - /** Reset the password for this account */ - public EditAccountOptions password(String password) { - formParameters.put("password", password); - return this; - } -} diff --git a/labs/greenqloud-compute/pom.xml b/labs/greenqloud-compute/pom.xml index 4c7ad33b44..768edc4c83 100644 --- a/labs/greenqloud-compute/pom.xml +++ b/labs/greenqloud-compute/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.labs diff --git a/labs/greenqloud-storage/pom.xml b/labs/greenqloud-storage/pom.xml index f9e9759785..d37961cc0f 100644 --- a/labs/greenqloud-storage/pom.xml +++ b/labs/greenqloud-storage/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.labs diff --git a/labs/iam/pom.xml b/labs/iam/pom.xml index 99a6e1ff51..43461b302f 100644 --- a/labs/iam/pom.xml +++ b/labs/iam/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.labs diff --git a/labs/jenkins/pom.xml b/labs/jenkins/pom.xml index 4e0cd8ba94..d6417ccc69 100644 --- a/labs/jenkins/pom.xml +++ b/labs/jenkins/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.labs diff --git a/labs/joyent-cloudapi/pom.xml b/labs/joyent-cloudapi/pom.xml index 1d0ac272fb..5243274c51 100644 --- a/labs/joyent-cloudapi/pom.xml +++ b/labs/joyent-cloudapi/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.labs diff --git a/labs/joyentcloud/pom.xml b/labs/joyentcloud/pom.xml index a3b94c284a..4278599f01 100644 --- a/labs/joyentcloud/pom.xml +++ b/labs/joyentcloud/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.labs diff --git a/labs/nodepool/pom.xml b/labs/nodepool/pom.xml index 33be7928e7..5c7d2041bc 100644 --- a/labs/nodepool/pom.xml +++ b/labs/nodepool/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.labs diff --git a/labs/nodepool/src/main/java/org/jclouds/nodepool/internal/JsonNodeMetadataStore.java b/labs/nodepool/src/main/java/org/jclouds/nodepool/internal/JsonNodeMetadataStore.java index 9d003cd494..5c71ef8ef2 100644 --- a/labs/nodepool/src/main/java/org/jclouds/nodepool/internal/JsonNodeMetadataStore.java +++ b/labs/nodepool/src/main/java/org/jclouds/nodepool/internal/JsonNodeMetadataStore.java @@ -23,7 +23,6 @@ import static com.google.common.base.Preconditions.checkState; import java.io.IOException; import java.io.InputStream; -import java.util.Collections; import java.util.Map; import java.util.Set; @@ -38,6 +37,7 @@ import org.jclouds.util.Strings2; import com.google.common.base.Supplier; import com.google.common.base.Throwables; +import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import com.google.inject.Inject; import com.google.inject.Singleton; @@ -109,7 +109,7 @@ public class JsonNodeMetadataStore implements NodeMetadataStore { @Override public Set loadAll(Set backendNodes) { if (backendNodes == null || backendNodes.isEmpty()) { - return Collections.emptySet(); + return ImmutableSet.of(); } final Set loadedSet = Sets.newLinkedHashSet(); for (NodeMetadata input : backendNodes) { diff --git a/labs/nodepool/src/test/java/org/jclouds/nodepool/NodeMetadataStoreTest.java b/labs/nodepool/src/test/java/org/jclouds/nodepool/NodeMetadataStoreTest.java index 3500bdf5df..25beec120e 100644 --- a/labs/nodepool/src/test/java/org/jclouds/nodepool/NodeMetadataStoreTest.java +++ b/labs/nodepool/src/test/java/org/jclouds/nodepool/NodeMetadataStoreTest.java @@ -25,7 +25,6 @@ import static org.testng.Assert.assertSame; import static org.testng.Assert.assertTrue; import java.io.File; -import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Properties; @@ -42,12 +41,13 @@ import org.jclouds.compute.options.TemplateOptions; import org.jclouds.logging.slf4j.config.SLF4JLoggingModule; import org.jclouds.nodepool.config.NodePoolProperties; import org.jclouds.nodepool.internal.NodeMetadataStore; -import org.jclouds.util.Strings2; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; +import com.google.common.base.Charsets; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; +import com.google.common.io.Files; import com.google.inject.Injector; /** @@ -94,8 +94,8 @@ public class NodeMetadataStoreTest { public void testStore() throws FileNotFoundException, IOException { store.store(nodeMeta1, templateOptions, "testgroup"); store.store(nodeMeta2, templateOptions, "testgroup"); - String readJSon = Strings2.toStringAndClose(new FileInputStream(baseDir + File.separator + "nodes" - + File.separator + nodeMeta1.getId())); + String readJSon = Files.toString(new File(baseDir + File.separator + "nodes" + + File.separator + nodeMeta1.getId()), Charsets.UTF_8); assertEquals(readJSon, "{\"group\":\"testgroup\",\"tags\":[\"tag1\",\"tag2\"]," + "\"userMetadata\":{\"testmetakey\":\"testmetavalue\",\"testmetakey2\":\"testmetavalue2\"}," + "\"user\":\"testuser\",\"password\":\"testpass\",\"privateKey\":\"pk\",\"authenticateSudo\":true}"); diff --git a/labs/openstack-glance/pom.xml b/labs/openstack-glance/pom.xml index a12df99345..617dbe9c3e 100644 --- a/labs/openstack-glance/pom.xml +++ b/labs/openstack-glance/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.labs diff --git a/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/GlanceApi.java b/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/GlanceApi.java index e1a4867740..6f0cd99852 100644 --- a/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/GlanceApi.java +++ b/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/GlanceApi.java @@ -23,8 +23,8 @@ import java.util.concurrent.TimeUnit; import org.jclouds.concurrent.Timeout; import org.jclouds.javax.annotation.Nullable; -import org.jclouds.location.Region; -import org.jclouds.location.functions.RegionToEndpoint; +import org.jclouds.location.Zone; +import org.jclouds.location.functions.ZoneToEndpoint; import org.jclouds.openstack.glance.v1_0.features.ImageApi; import org.jclouds.openstack.v2_0.features.ExtensionApi; import org.jclouds.rest.annotations.Delegate; @@ -44,23 +44,23 @@ import com.google.inject.Provides; public interface GlanceApi { /** * - * @return the Region codes configured + * @return the Zone codes configured */ @Provides - @Region - Set getConfiguredRegions(); + @Zone + Set getConfiguredZones(); /** * Provides synchronous access to Extension features. */ @Delegate - ExtensionApi getExtensionApiForRegion( - @EndpointParam(parser = RegionToEndpoint.class) @Nullable String region); + ExtensionApi getExtensionApiForZone( + @EndpointParam(parser = ZoneToEndpoint.class) @Nullable String zone); /** * Provides synchronous access to Image features. */ @Delegate - ImageApi getImageApiForRegion(@EndpointParam(parser = RegionToEndpoint.class) @Nullable String region); + ImageApi getImageApiForZone(@EndpointParam(parser = ZoneToEndpoint.class) @Nullable String zone); } diff --git a/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/GlanceApiMetadata.java b/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/GlanceApiMetadata.java index 6669d59c8f..9086048425 100644 --- a/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/GlanceApiMetadata.java +++ b/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/GlanceApiMetadata.java @@ -28,7 +28,7 @@ import org.jclouds.apis.ApiMetadata; import org.jclouds.openstack.glance.v1_0.config.GlanceRestClientModule; import org.jclouds.openstack.keystone.v2_0.config.CredentialTypes; import org.jclouds.openstack.keystone.v2_0.config.KeystoneAuthenticationModule; -import org.jclouds.openstack.keystone.v2_0.config.KeystoneAuthenticationModule.RegionModule; +import org.jclouds.openstack.keystone.v2_0.config.KeystoneAuthenticationModule.ZoneModule; import org.jclouds.openstack.v2_0.ServiceType; import org.jclouds.rest.RestContext; import org.jclouds.rest.internal.BaseRestApiMetadata; @@ -86,7 +86,7 @@ public class GlanceApiMetadata extends BaseRestApiMetadata { .defaultProperties(GlanceApiMetadata.defaultProperties()) .defaultModules(ImmutableSet.>builder() .add(KeystoneAuthenticationModule.class) - .add(RegionModule.class) + .add(ZoneModule.class) .add(GlanceRestClientModule.class).build()); } diff --git a/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/GlanceAsyncApi.java b/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/GlanceAsyncApi.java index d494d7a418..b36ab4421c 100644 --- a/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/GlanceAsyncApi.java +++ b/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/GlanceAsyncApi.java @@ -21,8 +21,8 @@ package org.jclouds.openstack.glance.v1_0; import java.util.Set; import org.jclouds.javax.annotation.Nullable; -import org.jclouds.location.Region; -import org.jclouds.location.functions.RegionToEndpoint; +import org.jclouds.location.Zone; +import org.jclouds.location.functions.ZoneToEndpoint; import org.jclouds.openstack.glance.v1_0.features.ImageAsyncApi; import org.jclouds.openstack.v2_0.features.ExtensionAsyncApi; import org.jclouds.rest.annotations.Delegate; @@ -41,23 +41,23 @@ import com.google.inject.Provides; public interface GlanceAsyncApi { /** * - * @return the Region codes configured + * @return the Zone codes configured */ @Provides - @Region - Set getConfiguredRegions(); + @Zone + Set getConfiguredZones(); /** * Provides asynchronous access to Extension features. */ @Delegate - ExtensionAsyncApi getExtensionApiForRegion( - @EndpointParam(parser = RegionToEndpoint.class) @Nullable String region); + ExtensionAsyncApi getExtensionApiForZone( + @EndpointParam(parser = ZoneToEndpoint.class) @Nullable String zone); /** * Provides asynchronous access to Image features. */ @Delegate - ImageAsyncApi getImageApiForRegion(@EndpointParam(parser = RegionToEndpoint.class) @Nullable String region); + ImageAsyncApi getImageApiForZone(@EndpointParam(parser = ZoneToEndpoint.class) @Nullable String zone); } diff --git a/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/config/GlanceRestClientModule.java b/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/config/GlanceRestClientModule.java index e6d266a052..e5bda4af23 100644 --- a/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/config/GlanceRestClientModule.java +++ b/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/config/GlanceRestClientModule.java @@ -96,7 +96,7 @@ public class GlanceRestClientModule>() { @Override public Set load(String key) throws Exception { - return glanceApi.get().getExtensionApiForRegion(key).listExtensions(); + return glanceApi.get().getExtensionApiForZone(key).list(); } }); } diff --git a/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/features/ImageApi.java b/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/features/ImageApi.java index b24e368359..0aceab60ab 100644 --- a/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/features/ImageApi.java +++ b/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/features/ImageApi.java @@ -19,9 +19,9 @@ package org.jclouds.openstack.glance.v1_0.features; import java.io.InputStream; -import java.util.Set; import java.util.concurrent.TimeUnit; +import org.jclouds.collect.PagedIterable; import org.jclouds.concurrent.Timeout; import org.jclouds.io.Payload; import org.jclouds.javax.annotation.Nullable; @@ -30,6 +30,7 @@ import org.jclouds.openstack.glance.v1_0.domain.ImageDetails; import org.jclouds.openstack.glance.v1_0.options.CreateImageOptions; import org.jclouds.openstack.glance.v1_0.options.ListImageOptions; import org.jclouds.openstack.glance.v1_0.options.UpdateImageOptions; +import org.jclouds.openstack.keystone.v2_0.domain.PaginatedCollection; /** * Image Services @@ -41,21 +42,31 @@ import org.jclouds.openstack.glance.v1_0.options.UpdateImageOptions; */ @Timeout(duration = 180, timeUnit = TimeUnit.SECONDS) public interface ImageApi { - /** - * Returns a set of brief metadata about images - */ - Set list(ListImageOptions... options); /** - * Returns a set of detailed metadata about images + * List all images (IDs, names, links) + * + * @return all images (IDs, names, links) */ - Set listInDetail(ListImageOptions... options); + PagedIterable list(); + + PaginatedCollection list(ListImageOptions options); + + /** + * List all images (all details) + * + * @return all images (all details) + */ + PagedIterable listInDetail(); + + PaginatedCollection listInDetail(ListImageOptions options); + /** * Return metadata about an image with id */ @Nullable - ImageDetails show(String id); + ImageDetails get(String id); /** * Return image data for image with id @@ -104,5 +115,5 @@ public interface ImageApi { * * @return true if successful */ - Boolean delete(String id); + boolean delete(String id); } diff --git a/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/features/ImageAsyncApi.java b/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/features/ImageAsyncApi.java index c4b41caf2c..31c7b5d974 100644 --- a/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/features/ImageAsyncApi.java +++ b/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/features/ImageAsyncApi.java @@ -19,7 +19,6 @@ package org.jclouds.openstack.glance.v1_0.features; import java.io.InputStream; -import java.util.Set; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; @@ -33,20 +32,26 @@ import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; +import org.jclouds.collect.PagedIterable; import org.jclouds.io.Payload; import org.jclouds.openstack.glance.v1_0.domain.Image; import org.jclouds.openstack.glance.v1_0.domain.ImageDetails; import org.jclouds.openstack.glance.v1_0.functions.ParseImageDetailsFromHeaders; +import org.jclouds.openstack.glance.v1_0.functions.internal.ParseImageDetails; +import org.jclouds.openstack.glance.v1_0.functions.internal.ParseImages; import org.jclouds.openstack.glance.v1_0.options.CreateImageOptions; import org.jclouds.openstack.glance.v1_0.options.ListImageOptions; import org.jclouds.openstack.glance.v1_0.options.UpdateImageOptions; +import org.jclouds.openstack.keystone.v2_0.domain.PaginatedCollection; import org.jclouds.openstack.keystone.v2_0.filters.AuthenticateRequest; +import org.jclouds.openstack.keystone.v2_0.functions.ReturnEmptyPaginatedCollectionOnNotFoundOr404; import org.jclouds.rest.annotations.ExceptionParser; import org.jclouds.rest.annotations.RequestFilters; import org.jclouds.rest.annotations.ResponseParser; import org.jclouds.rest.annotations.SelectJson; import org.jclouds.rest.annotations.SkipEncoding; -import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404; +import org.jclouds.rest.annotations.Transform; +import org.jclouds.rest.functions.ReturnEmptyPagedIterableOnNotFoundOr404; import org.jclouds.rest.functions.ReturnFalseOnNotFoundOr404; import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; @@ -65,34 +70,58 @@ import com.google.common.util.concurrent.ListenableFuture; @RequestFilters(AuthenticateRequest.class) public interface ImageAsyncApi { + /** - * @see ImageApi#list + * @see ImageApi#list() */ @GET - @SelectJson("images") @Consumes(MediaType.APPLICATION_JSON) @Path("/images") - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> list(ListImageOptions... options); - + @RequestFilters(AuthenticateRequest.class) + @ResponseParser(ParseImages.class) + @Transform(ParseImages.ToPagedIterable.class) + @ExceptionParser(ReturnEmptyPagedIterableOnNotFoundOr404.class) + ListenableFuture> list(); + + /** @see ImageApi#list(ListImageOptions) */ + @GET + @Consumes(MediaType.APPLICATION_JSON) + @Path("/images") + @RequestFilters(AuthenticateRequest.class) + @ResponseParser(ParseImages.class) + @ExceptionParser(ReturnEmptyPaginatedCollectionOnNotFoundOr404.class) + ListenableFuture> list(ListImageOptions options); + /** - * @see ImageApi#listInDetail + * @see ImageApi#listInDetail() */ @GET - @SelectJson("images") @Consumes(MediaType.APPLICATION_JSON) @Path("/images/detail") - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> listInDetail(ListImageOptions... options); + @RequestFilters(AuthenticateRequest.class) + @ResponseParser(ParseImageDetails.class) + @Transform(ParseImageDetails.ToPagedIterable.class) + @ExceptionParser(ReturnEmptyPagedIterableOnNotFoundOr404.class) + ListenableFuture> listInDetail(); + + /** @see ImageApi#listInDetail(ListImageOptions) */ + @GET + @Consumes(MediaType.APPLICATION_JSON) + @Path("/images/detail") + @RequestFilters(AuthenticateRequest.class) + @ResponseParser(ParseImageDetails.class) + @ExceptionParser(ReturnEmptyPaginatedCollectionOnNotFoundOr404.class) + ListenableFuture> listInDetail(ListImageOptions options); + /** - * @see ImageApi#show + * @see ImageApi#get */ @HEAD @Path("/images/{id}") @ResponseParser(ParseImageDetailsFromHeaders.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class) - ListenableFuture show(@PathParam("id") String id); + ListenableFuture get(@PathParam("id") String id); /** * @see ImageApi#getAsStream diff --git a/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/functions/internal/ParseImageDetails.java b/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/functions/internal/ParseImageDetails.java new file mode 100644 index 0000000000..b111370720 --- /dev/null +++ b/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/functions/internal/ParseImageDetails.java @@ -0,0 +1,96 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.glance.v1_0.functions.internal; + +import static com.google.common.base.Preconditions.checkNotNull; +import static org.jclouds.openstack.glance.v1_0.options.ListImageOptions.Builder.marker; + +import java.beans.ConstructorProperties; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.collect.IterableWithMarker; +import org.jclouds.collect.internal.CallerArg0ToPagedIterable; +import org.jclouds.http.functions.ParseJson; +import org.jclouds.json.Json; +import org.jclouds.openstack.glance.v1_0.GlanceApi; +import org.jclouds.openstack.glance.v1_0.domain.ImageDetails; +import org.jclouds.openstack.glance.v1_0.features.ImageApi; +import org.jclouds.openstack.glance.v1_0.functions.internal.ParseImageDetails.Images; +import org.jclouds.openstack.keystone.v2_0.domain.PaginatedCollection; +import org.jclouds.openstack.v2_0.domain.Link; + +import com.google.common.annotations.Beta; +import com.google.common.base.Function; +import com.google.inject.TypeLiteral; + +/** + * boiler plate until we determine a better way + * + * @author Adrian Cole + */ +@Beta +@Singleton +public class ParseImageDetails extends ParseJson> { + static class Images extends PaginatedCollection { + + @ConstructorProperties({ "images", "images_links" }) + protected Images(Iterable images, Iterable images_links) { + super(images, images_links); + } + + } + + @Inject + public ParseImageDetails(Json json) { + super(json, new TypeLiteral>() { + }); + } + + public static class ToPagedIterable extends CallerArg0ToPagedIterable { + + private final GlanceApi api; + + @Inject + protected ToPagedIterable(GlanceApi api) { + this.api = checkNotNull(api, "api"); + } + + @Override + protected Function> markerToNextForCallingArg0(final String zone) { + final ImageApi imageApi = api.getImageApiForZone(zone); + return new Function>() { + + @SuppressWarnings("unchecked") + @Override + public IterableWithMarker apply(Object input) { + return IterableWithMarker.class.cast(imageApi.listInDetail(marker(input.toString()))); + } + + @Override + public String toString() { + return "listInDetail()"; + } + }; + } + + } + +} diff --git a/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/functions/internal/ParseImages.java b/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/functions/internal/ParseImages.java new file mode 100644 index 0000000000..0b8ea223fc --- /dev/null +++ b/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/functions/internal/ParseImages.java @@ -0,0 +1,96 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.openstack.glance.v1_0.functions.internal; + +import static com.google.common.base.Preconditions.checkNotNull; +import static org.jclouds.openstack.glance.v1_0.options.ListImageOptions.Builder.marker; + +import java.beans.ConstructorProperties; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import org.jclouds.collect.IterableWithMarker; +import org.jclouds.collect.internal.CallerArg0ToPagedIterable; +import org.jclouds.http.functions.ParseJson; +import org.jclouds.json.Json; +import org.jclouds.openstack.glance.v1_0.GlanceApi; +import org.jclouds.openstack.glance.v1_0.domain.Image; +import org.jclouds.openstack.glance.v1_0.features.ImageApi; +import org.jclouds.openstack.glance.v1_0.functions.internal.ParseImages.Images; +import org.jclouds.openstack.keystone.v2_0.domain.PaginatedCollection; +import org.jclouds.openstack.v2_0.domain.Link; + +import com.google.common.annotations.Beta; +import com.google.common.base.Function; +import com.google.inject.TypeLiteral; + +/** + * boiler plate until we determine a better way + * + * @author Adrian Cole + */ +@Beta +@Singleton +public class ParseImages extends ParseJson> { + static class Images extends PaginatedCollection { + + @ConstructorProperties({ "images", "images_links" }) + protected Images(Iterable images, Iterable images_links) { + super(images, images_links); + } + + } + + @Inject + public ParseImages(Json json) { + super(json, new TypeLiteral>() { + }); + } + + public static class ToPagedIterable extends CallerArg0ToPagedIterable { + + private final GlanceApi api; + + @Inject + protected ToPagedIterable(GlanceApi api) { + this.api = checkNotNull(api, "api"); + } + + @Override + protected Function> markerToNextForCallingArg0(final String zone) { + final ImageApi imageApi = api.getImageApiForZone(zone); + return new Function>() { + + @SuppressWarnings("unchecked") + @Override + public IterableWithMarker apply(Object input) { + return IterableWithMarker.class.cast(imageApi.list(marker(input.toString()))); + } + + @Override + public String toString() { + return "list()"; + } + }; + } + + } + +} diff --git a/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/options/ListImageOptions.java b/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/options/ListImageOptions.java index 2df3f430c2..0328e90b4a 100644 --- a/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/options/ListImageOptions.java +++ b/labs/openstack-glance/src/main/java/org/jclouds/openstack/glance/v1_0/options/ListImageOptions.java @@ -18,8 +18,6 @@ */ package org.jclouds.openstack.glance.v1_0.options; -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Preconditions.checkState; import static org.jclouds.openstack.glance.v1_0.options.ImageField.CONTAINER_FORMAT; import static org.jclouds.openstack.glance.v1_0.options.ImageField.DISK_FORMAT; import static org.jclouds.openstack.glance.v1_0.options.ImageField.IS_PUBLIC; @@ -31,10 +29,12 @@ import static org.jclouds.openstack.glance.v1_0.options.ImageField.SIZE_MAX; import static org.jclouds.openstack.glance.v1_0.options.ImageField.SIZE_MIN; import static org.jclouds.openstack.glance.v1_0.options.ImageField.STATUS; -import org.jclouds.http.options.BaseHttpRequestOptions; +import java.util.Date; + import org.jclouds.openstack.glance.v1_0.domain.ContainerFormat; import org.jclouds.openstack.glance.v1_0.domain.DiskFormat; import org.jclouds.openstack.glance.v1_0.domain.Image.Status; +import org.jclouds.openstack.v2_0.options.PaginationOptions; /** *

Usage The recommended way to instantiate a ListImageOptions object is to statically import @@ -51,27 +51,9 @@ import org.jclouds.openstack.glance.v1_0.domain.Image.Status; * @author Adam Lowe * @see */ -public class ListImageOptions extends BaseHttpRequestOptions { +public class ListImageOptions extends PaginationOptions { public static final ListImageOptions NONE = new ListImageOptions(); - /** - * Given a string value x, return object names greater in value than the specified marker. - */ - public ListImageOptions marker(String marker) { - queryParameters.put("marker", checkNotNull(marker, "marker")); - return this; - } - - /** - * For an integer value n, limits the number of results to n values. - */ - public ListImageOptions limit(int limit) { - checkState(limit >= 0, "limit must be >= 0"); - checkState(limit <= 10000, "limit must be <= 10000"); - queryParameters.put("limit", Integer.toString(limit)); - return this; - } - /** * Return only those images having a matching name attribute */ @@ -267,8 +249,22 @@ public class ListImageOptions extends BaseHttpRequestOptions { * @see ListImageOptions#marker */ public static ListImageOptions marker(String marker) { - ListImageOptions options = new ListImageOptions(); - return options.marker(marker); + return new ListImageOptions().marker(marker); } } + + @Override + public ListImageOptions changesSince(Date ifModifiedSince) { + return ListImageOptions.class.cast(super.changesSince(ifModifiedSince)); + } + + @Override + public ListImageOptions marker(String marker) { + return ListImageOptions.class.cast(super.marker(marker)); + } + + @Override + public ListImageOptions limit(int limit) { + return ListImageOptions.class.cast(super.limit(limit)); + } } diff --git a/labs/openstack-glance/src/test/java/org/jclouds/openstack/glance/v1_0/features/ImageApiExpectTest.java b/labs/openstack-glance/src/test/java/org/jclouds/openstack/glance/v1_0/features/ImageApiExpectTest.java index a6df24ba1d..6eed0ebc87 100644 --- a/labs/openstack-glance/src/test/java/org/jclouds/openstack/glance/v1_0/features/ImageApiExpectTest.java +++ b/labs/openstack-glance/src/test/java/org/jclouds/openstack/glance/v1_0/features/ImageApiExpectTest.java @@ -64,9 +64,9 @@ public class ImageApiExpectTest extends BaseGlanceApiExpectTest { GlanceApi apiWhenExist = requestsSendResponses(keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, list, listResponse); - assertEquals(apiWhenExist.getConfiguredRegions(), ImmutableSet.of("az-1.region-a.geo-1")); + assertEquals(apiWhenExist.getConfiguredZones(), ImmutableSet.of("az-1.region-a.geo-1")); - assertEquals(apiWhenExist.getImageApiForRegion("az-1.region-a.geo-1").list().toString(), + assertEquals(apiWhenExist.getImageApiForZone("az-1.region-a.geo-1").list().concat().toString(), new ParseImagesTest().expected().toString()); } @@ -81,7 +81,7 @@ public class ImageApiExpectTest extends BaseGlanceApiExpectTest { GlanceApi apiWhenNoExist = requestsSendResponses(keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, list, listResponse); - assertTrue(apiWhenNoExist.getImageApiForRegion("az-1.region-a.geo-1").list().isEmpty()); + assertTrue(apiWhenNoExist.getImageApiForZone("az-1.region-a.geo-1").list().concat().isEmpty()); } public void testListInDetailWhenResponseIs2xx() throws Exception { @@ -97,9 +97,9 @@ public class ImageApiExpectTest extends BaseGlanceApiExpectTest { GlanceApi apiWhenExistInDetail = requestsSendResponses(keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, listInDetail, listInDetailResponse); - assertEquals(apiWhenExistInDetail.getConfiguredRegions(), ImmutableSet.of("az-1.region-a.geo-1")); + assertEquals(apiWhenExistInDetail.getConfiguredZones(), ImmutableSet.of("az-1.region-a.geo-1")); - assertEquals(apiWhenExistInDetail.getImageApiForRegion("az-1.region-a.geo-1").listInDetail().toString(), + assertEquals(apiWhenExistInDetail.getImageApiForZone("az-1.region-a.geo-1").listInDetail().concat().toString(), new ParseImagesInDetailTest().expected().toString()); } @@ -115,7 +115,7 @@ public class ImageApiExpectTest extends BaseGlanceApiExpectTest { GlanceApi apiWhenNoExistInDetail = requestsSendResponses(keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, listInDetail, listInDetailResponse); - assertTrue(apiWhenNoExistInDetail.getImageApiForRegion("az-1.region-a.geo-1").listInDetail().isEmpty()); + assertTrue(apiWhenNoExistInDetail.getImageApiForZone("az-1.region-a.geo-1").listInDetail().concat().isEmpty()); } public void testShowWhenResponseIs2xx() throws Exception { @@ -131,9 +131,9 @@ public class ImageApiExpectTest extends BaseGlanceApiExpectTest { GlanceApi apiWhenExist = requestsSendResponses(keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, show, showResponse); - assertEquals(apiWhenExist.getConfiguredRegions(), ImmutableSet.of("az-1.region-a.geo-1")); + assertEquals(apiWhenExist.getConfiguredZones(), ImmutableSet.of("az-1.region-a.geo-1")); - assertEquals(apiWhenExist.getImageApiForRegion("az-1.region-a.geo-1").show("fcc451d0-f6e4-4824-ad8f-70ec12326d07").toString(), + assertEquals(apiWhenExist.getImageApiForZone("az-1.region-a.geo-1").get("fcc451d0-f6e4-4824-ad8f-70ec12326d07").toString(), new ParseImageDetailsFromHeadersTest().expected().toString()); } @@ -148,7 +148,7 @@ public class ImageApiExpectTest extends BaseGlanceApiExpectTest { GlanceApi apiWhenNoExist = requestsSendResponses(keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, show, showResponse); - assertNull(apiWhenNoExist.getImageApiForRegion("az-1.region-a.geo-1").show("fcc451d0-f6e4-4824-ad8f-70ec12326d07")); + assertNull(apiWhenNoExist.getImageApiForZone("az-1.region-a.geo-1").get("fcc451d0-f6e4-4824-ad8f-70ec12326d07")); } @@ -163,9 +163,9 @@ public class ImageApiExpectTest extends BaseGlanceApiExpectTest { GlanceApi apiWhenExist = requestsSendResponses(keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, get, getResponse); - assertEquals(apiWhenExist.getConfiguredRegions(), ImmutableSet.of("az-1.region-a.geo-1")); + assertEquals(apiWhenExist.getConfiguredZones(), ImmutableSet.of("az-1.region-a.geo-1")); - assertEquals(Strings2.toStringAndClose(apiWhenExist.getImageApiForRegion("az-1.region-a.geo-1").getAsStream("fcc451d0-f6e4-4824-ad8f-70ec12326d07")), + assertEquals(Strings2.toStringAndClose(apiWhenExist.getImageApiForZone("az-1.region-a.geo-1").getAsStream("fcc451d0-f6e4-4824-ad8f-70ec12326d07")), "foo"); } @@ -180,7 +180,7 @@ public class ImageApiExpectTest extends BaseGlanceApiExpectTest { GlanceApi apiWhenNoExist = requestsSendResponses(keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, get, getResponse); - assertNull(apiWhenNoExist.getImageApiForRegion("az-1.region-a.geo-1").getAsStream("fcc451d0-f6e4-4824-ad8f-70ec12326d07")); + assertNull(apiWhenNoExist.getImageApiForZone("az-1.region-a.geo-1").getAsStream("fcc451d0-f6e4-4824-ad8f-70ec12326d07")); } public void testCreateWhenResponseIs2xx() throws Exception { @@ -197,9 +197,9 @@ public class ImageApiExpectTest extends BaseGlanceApiExpectTest { GlanceApi apiWhenExist = requestsSendResponses(keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, get, createResponse); - assertEquals(apiWhenExist.getConfiguredRegions(), ImmutableSet.of("az-1.region-a.geo-1")); + assertEquals(apiWhenExist.getConfiguredZones(), ImmutableSet.of("az-1.region-a.geo-1")); - assertEquals(apiWhenExist.getImageApiForRegion("az-1.region-a.geo-1").create("test", new StringPayload("somedata")), + assertEquals(apiWhenExist.getImageApiForZone("az-1.region-a.geo-1").create("test", new StringPayload("somedata")), new ParseImageDetailsTest().expected()); } @@ -218,9 +218,9 @@ public class ImageApiExpectTest extends BaseGlanceApiExpectTest { GlanceApi apiWhenExist = requestsSendResponses(keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, get, createResponse); - assertEquals(apiWhenExist.getConfiguredRegions(), ImmutableSet.of("az-1.region-a.geo-1")); + assertEquals(apiWhenExist.getConfiguredZones(), ImmutableSet.of("az-1.region-a.geo-1")); - apiWhenExist.getImageApiForRegion("az-1.region-a.geo-1").create("test", new StringPayload("somedata")); + apiWhenExist.getImageApiForZone("az-1.region-a.geo-1").create("test", new StringPayload("somedata")); } public void testReserveWhenResponseIs2xx() throws Exception { @@ -236,9 +236,9 @@ public class ImageApiExpectTest extends BaseGlanceApiExpectTest { GlanceApi apiWhenExist = requestsSendResponses(keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, get, createResponse); - assertEquals(apiWhenExist.getConfiguredRegions(), ImmutableSet.of("az-1.region-a.geo-1")); + assertEquals(apiWhenExist.getConfiguredZones(), ImmutableSet.of("az-1.region-a.geo-1")); - assertEquals(apiWhenExist.getImageApiForRegion("az-1.region-a.geo-1").reserve("test"), new ParseImageDetailsTest().expected()); + assertEquals(apiWhenExist.getImageApiForZone("az-1.region-a.geo-1").reserve("test"), new ParseImageDetailsTest().expected()); } @Test(expectedExceptions = AuthorizationException.class) @@ -255,9 +255,9 @@ public class ImageApiExpectTest extends BaseGlanceApiExpectTest { GlanceApi apiWhenExist = requestsSendResponses(keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, get, createResponse); - assertEquals(apiWhenExist.getConfiguredRegions(), ImmutableSet.of("az-1.region-a.geo-1")); + assertEquals(apiWhenExist.getConfiguredZones(), ImmutableSet.of("az-1.region-a.geo-1")); - apiWhenExist.getImageApiForRegion("az-1.region-a.geo-1").reserve("test"); + apiWhenExist.getImageApiForZone("az-1.region-a.geo-1").reserve("test"); } public void testUpdateMetadataWhenResponseIs2xx() throws Exception { @@ -282,9 +282,9 @@ public class ImageApiExpectTest extends BaseGlanceApiExpectTest { GlanceApi apiWhenExist = requestsSendResponses(keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, get, updateResponse); - assertEquals(apiWhenExist.getConfiguredRegions(), ImmutableSet.of("az-1.region-a.geo-1")); + assertEquals(apiWhenExist.getConfiguredZones(), ImmutableSet.of("az-1.region-a.geo-1")); - assertEquals(apiWhenExist.getImageApiForRegion("az-1.region-a.geo-1") + assertEquals(apiWhenExist.getImageApiForZone("az-1.region-a.geo-1") .update("fcc451d0-f6e4-4824-ad8f-70ec12326d07", UpdateImageOptions.Builder.name("newname"), UpdateImageOptions.Builder.isPublic(true), @@ -313,9 +313,9 @@ public class ImageApiExpectTest extends BaseGlanceApiExpectTest { GlanceApi apiWhenExist = requestsSendResponses(keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, get, updateResponse); - assertEquals(apiWhenExist.getConfiguredRegions(), ImmutableSet.of("az-1.region-a.geo-1")); + assertEquals(apiWhenExist.getConfiguredZones(), ImmutableSet.of("az-1.region-a.geo-1")); - apiWhenExist.getImageApiForRegion("az-1.region-a.geo-1") + apiWhenExist.getImageApiForZone("az-1.region-a.geo-1") .update("fcc451d0-f6e4-4824-ad8f-70ec12326d07", UpdateImageOptions.Builder.name("newname"), UpdateImageOptions.Builder.isPublic(true)); @@ -336,9 +336,9 @@ public class ImageApiExpectTest extends BaseGlanceApiExpectTest { GlanceApi apiWhenExist = requestsSendResponses(keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, get, updateResponse); - assertEquals(apiWhenExist.getConfiguredRegions(), ImmutableSet.of("az-1.region-a.geo-1")); + assertEquals(apiWhenExist.getConfiguredZones(), ImmutableSet.of("az-1.region-a.geo-1")); - assertEquals(apiWhenExist.getImageApiForRegion("az-1.region-a.geo-1").upload("fcc451d0-f6e4-4824-ad8f-70ec12326d07", + assertEquals(apiWhenExist.getImageApiForZone("az-1.region-a.geo-1").upload("fcc451d0-f6e4-4824-ad8f-70ec12326d07", new StringPayload("somenewdata")), new ParseImageDetailsTest().expected()); } @@ -360,9 +360,9 @@ public class ImageApiExpectTest extends BaseGlanceApiExpectTest { GlanceApi apiWhenExist = requestsSendResponses(keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, get, updateResponse); - assertEquals(apiWhenExist.getConfiguredRegions(), ImmutableSet.of("az-1.region-a.geo-1")); + assertEquals(apiWhenExist.getConfiguredZones(), ImmutableSet.of("az-1.region-a.geo-1")); - assertEquals(apiWhenExist.getImageApiForRegion("az-1.region-a.geo-1").upload("fcc451d0-f6e4-4824-ad8f-70ec12326d07", + assertEquals(apiWhenExist.getImageApiForZone("az-1.region-a.geo-1").upload("fcc451d0-f6e4-4824-ad8f-70ec12326d07", new StringPayload("somenewdata"), UpdateImageOptions.Builder.name("anothernewname")), new ParseImageDetailsTest().expected()); } @@ -383,9 +383,9 @@ public class ImageApiExpectTest extends BaseGlanceApiExpectTest { GlanceApi apiWhenExist = requestsSendResponses(keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, get, updateResponse); - assertEquals(apiWhenExist.getConfiguredRegions(), ImmutableSet.of("az-1.region-a.geo-1")); + assertEquals(apiWhenExist.getConfiguredZones(), ImmutableSet.of("az-1.region-a.geo-1")); - apiWhenExist.getImageApiForRegion("az-1.region-a.geo-1").upload("fcc451d0-f6e4-4824-ad8f-70ec12326d07", + apiWhenExist.getImageApiForZone("az-1.region-a.geo-1").upload("fcc451d0-f6e4-4824-ad8f-70ec12326d07", new StringPayload("somenewdata"), UpdateImageOptions.Builder.name("anothernewname")); } @@ -399,9 +399,9 @@ public class ImageApiExpectTest extends BaseGlanceApiExpectTest { GlanceApi apiWhenExist = requestsSendResponses(keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, get, getResponse); - assertEquals(apiWhenExist.getConfiguredRegions(), ImmutableSet.of("az-1.region-a.geo-1")); + assertEquals(apiWhenExist.getConfiguredZones(), ImmutableSet.of("az-1.region-a.geo-1")); - assertTrue(apiWhenExist.getImageApiForRegion("az-1.region-a.geo-1").delete("fcc451d0-f6e4-4824-ad8f-70ec12326d07")); + assertTrue(apiWhenExist.getImageApiForZone("az-1.region-a.geo-1").delete("fcc451d0-f6e4-4824-ad8f-70ec12326d07")); } public void testDeleteWhenResponseIs4xx() throws Exception { @@ -415,8 +415,8 @@ public class ImageApiExpectTest extends BaseGlanceApiExpectTest { GlanceApi apiWhenExist = requestsSendResponses(keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, get, getResponse); - assertEquals(apiWhenExist.getConfiguredRegions(), ImmutableSet.of("az-1.region-a.geo-1")); + assertEquals(apiWhenExist.getConfiguredZones(), ImmutableSet.of("az-1.region-a.geo-1")); - assertFalse(apiWhenExist.getImageApiForRegion("az-1.region-a.geo-1").delete("fcc451d0-f6e4-4824-ad8f-70ec12326d07")); + assertFalse(apiWhenExist.getImageApiForZone("az-1.region-a.geo-1").delete("fcc451d0-f6e4-4824-ad8f-70ec12326d07")); } } diff --git a/labs/openstack-glance/src/test/java/org/jclouds/openstack/glance/v1_0/features/ImageApiLiveTest.java b/labs/openstack-glance/src/test/java/org/jclouds/openstack/glance/v1_0/features/ImageApiLiveTest.java index ef457545fb..765cc52fc2 100644 --- a/labs/openstack-glance/src/test/java/org/jclouds/openstack/glance/v1_0/features/ImageApiLiveTest.java +++ b/labs/openstack-glance/src/test/java/org/jclouds/openstack/glance/v1_0/features/ImageApiLiveTest.java @@ -47,9 +47,9 @@ public class ImageApiLiveTest extends BaseGlanceApiLiveTest { @Test public void testList() throws Exception { - for (String zoneId : glanceContext.getApi().getConfiguredRegions()) { - ImageApi api = glanceContext.getApi().getImageApiForRegion(zoneId); - Set response = api.list(ListImageOptions.Builder.limit(100)); + for (String zoneId : glanceContext.getApi().getConfiguredZones()) { + ImageApi api = glanceContext.getApi().getImageApiForZone(zoneId); + Set response = api.list().concat().toImmutableSet(); assert null != response; for (Image image : response) { checkImage(image); @@ -65,13 +65,13 @@ public class ImageApiLiveTest extends BaseGlanceApiLiveTest { @Test public void testListInDetail() throws Exception { - for (String zoneId : glanceContext.getApi().getConfiguredRegions()) { - ImageApi api = glanceContext.getApi().getImageApiForRegion(zoneId); - Set response = api.listInDetail(); + for (String zoneId : glanceContext.getApi().getConfiguredZones()) { + ImageApi api = glanceContext.getApi().getImageApiForZone(zoneId); + Set response = api.listInDetail().concat().toImmutableSet(); assert null != response; for (ImageDetails image : response) { checkImage(image); - ImageDetails newDetails = api.show(image.getId()); + ImageDetails newDetails = api.get(image.getId()); checkImageDetails(newDetails); checkImageDetailsEqual(image, newDetails); } @@ -93,8 +93,8 @@ public class ImageApiLiveTest extends BaseGlanceApiLiveTest { @Test public void testCreateUpdateAndDeleteImage() { StringPayload imageData = new StringPayload("This isn't really an image!"); - for (String zoneId : glanceContext.getApi().getConfiguredRegions()) { - ImageApi api = glanceContext.getApi().getImageApiForRegion(zoneId); + for (String zoneId : glanceContext.getApi().getConfiguredZones()) { + ImageApi api = glanceContext.getApi().getImageApiForZone(zoneId); ImageDetails details = api.create("jclouds-live-test", imageData, diskFormat(DiskFormat.RAW), containerFormat(ContainerFormat.BARE)); assertEquals(details.getName(), "jclouds-live-test"); assertEquals(details.getSize().get().longValue(), imageData.getRawContent().length()); @@ -103,7 +103,9 @@ public class ImageApiLiveTest extends BaseGlanceApiLiveTest { assertEquals(details.getName(), "jclouds-live-test2"); assertEquals(details.getMinDisk(), 10); - Image fromListing = Iterables.getOnlyElement(api.list(ListImageOptions.Builder.name("jclouds-live-test2"), ListImageOptions.Builder.limit(2), ListImageOptions.Builder.containerFormat(ContainerFormat.BARE))); + Image fromListing = api.list( + ListImageOptions.Builder.containerFormat(ContainerFormat.BARE).name("jclouds-live-test2").limit(2)) + .get(0); assertEquals(fromListing.getId(), details.getId()); assertEquals(fromListing.getSize(), details.getSize()); @@ -118,8 +120,8 @@ public class ImageApiLiveTest extends BaseGlanceApiLiveTest { @Test public void testReserveUploadAndDeleteImage() { StringPayload imageData = new StringPayload("This isn't an image!"); - for (String zoneId : glanceContext.getApi().getConfiguredRegions()) { - ImageApi api = glanceContext.getApi().getImageApiForRegion(zoneId); + for (String zoneId : glanceContext.getApi().getConfiguredZones()) { + ImageApi api = glanceContext.getApi().getImageApiForZone(zoneId); ImageDetails details = api.reserve("jclouds-live-res-test", diskFormat(DiskFormat.RAW), containerFormat(ContainerFormat.BARE)); assertEquals(details.getName(), "jclouds-live-res-test"); @@ -128,7 +130,7 @@ public class ImageApiLiveTest extends BaseGlanceApiLiveTest { assertEquals(details.getSize().get().longValue(), imageData.getRawContent().length()); assertEquals(details.getMinDisk(), 10); - Image fromListing = Iterables.getOnlyElement(api.list(ListImageOptions.Builder.name("jclouds-live-res-test2"), ListImageOptions.Builder.limit(2), ListImageOptions.Builder.containerFormat(ContainerFormat.BARE))); + Image fromListing = Iterables.getOnlyElement(api.list(ListImageOptions.Builder.name("jclouds-live-res-test2").limit(2).containerFormat(ContainerFormat.BARE))); assertEquals(fromListing.getId(), details.getId()); assertEquals(fromListing.getSize(), details.getSize()); diff --git a/labs/openstack-quantum/pom.xml b/labs/openstack-quantum/pom.xml index ccaa60084d..d35b628931 100644 --- a/labs/openstack-quantum/pom.xml +++ b/labs/openstack-quantum/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.labs diff --git a/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/QuantumApi.java b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/QuantumApi.java index 2f9a5ed1e0..b2b24ee111 100644 --- a/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/QuantumApi.java +++ b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/QuantumApi.java @@ -26,8 +26,7 @@ import javax.ws.rs.PathParam; import org.jclouds.concurrent.Timeout; import org.jclouds.javax.annotation.Nullable; -import org.jclouds.location.Region; -import org.jclouds.location.functions.RegionToEndpoint; +import org.jclouds.location.Zone; import org.jclouds.location.functions.ZoneToEndpoint; import org.jclouds.openstack.quantum.v1_0.features.NetworkApi; import org.jclouds.openstack.quantum.v1_0.features.PortApi; @@ -48,30 +47,30 @@ import com.google.inject.Provides; @Timeout(duration = 60, timeUnit = TimeUnit.SECONDS) public interface QuantumApi { /** - * @return the Region codes configured + * @return the Zone codes configured */ @Provides - @Region - Set getConfiguredRegions(); + @Zone + Set getConfiguredZones(); /** * Provides synchronous access to Extension features. */ @Delegate - ExtensionApi getExtensionApiForRegion( - @EndpointParam(parser = RegionToEndpoint.class) @Nullable String region); + ExtensionApi getExtensionApiForZone( + @EndpointParam(parser = ZoneToEndpoint.class) @Nullable String zone); /** * Provides synchronous access to Network features. */ @Delegate - NetworkApi getNetworkApiForRegion(@EndpointParam(parser = RegionToEndpoint.class) @Nullable String region); + NetworkApi getNetworkApiForZone(@EndpointParam(parser = ZoneToEndpoint.class) @Nullable String zone); /** * Provides synchronous access to Port features. */ @Delegate @Path("/networks/{net}") - PortApi getPortApiForRegionAndNetwork(@EndpointParam(parser = RegionToEndpoint.class) @Nullable String region, + PortApi getPortApiForZoneAndNetwork(@EndpointParam(parser = ZoneToEndpoint.class) @Nullable String zone, @PathParam("net") String networkId); } diff --git a/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/QuantumApiMetadata.java b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/QuantumApiMetadata.java index 9d38d93e9c..9e986d7028 100644 --- a/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/QuantumApiMetadata.java +++ b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/QuantumApiMetadata.java @@ -27,7 +27,7 @@ import java.util.Properties; import org.jclouds.apis.ApiMetadata; import org.jclouds.openstack.keystone.v2_0.config.CredentialTypes; import org.jclouds.openstack.keystone.v2_0.config.KeystoneAuthenticationModule; -import org.jclouds.openstack.keystone.v2_0.config.KeystoneAuthenticationModule.RegionModule; +import org.jclouds.openstack.keystone.v2_0.config.KeystoneAuthenticationModule.ZoneModule; import org.jclouds.openstack.quantum.v1_0.config.QuantumRestClientModule; import org.jclouds.openstack.v2_0.ServiceType; import org.jclouds.rest.RestContext; @@ -85,7 +85,7 @@ public class QuantumApiMetadata extends BaseRestApiMetadata { .defaultProperties(QuantumApiMetadata.defaultProperties()) .defaultModules(ImmutableSet.>builder() .add(KeystoneAuthenticationModule.class) - .add(RegionModule.class) + .add(ZoneModule.class) .add(QuantumRestClientModule.class).build()); } diff --git a/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/QuantumAsyncApi.java b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/QuantumAsyncApi.java index 0ea08a3960..4a6ccd897a 100644 --- a/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/QuantumAsyncApi.java +++ b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/QuantumAsyncApi.java @@ -24,8 +24,8 @@ import javax.ws.rs.Path; import javax.ws.rs.PathParam; import org.jclouds.javax.annotation.Nullable; -import org.jclouds.location.Region; -import org.jclouds.location.functions.RegionToEndpoint; +import org.jclouds.location.Zone; +import org.jclouds.location.functions.ZoneToEndpoint; import org.jclouds.openstack.quantum.v1_0.features.NetworkAsyncApi; import org.jclouds.openstack.quantum.v1_0.features.PortAsyncApi; import org.jclouds.openstack.v2_0.features.ExtensionAsyncApi; @@ -45,30 +45,30 @@ import com.google.inject.Provides; public interface QuantumAsyncApi { /** * - * @return the Region codes configured + * @return the Zone codes configured */ @Provides - @Region - Set getConfiguredRegions(); + @Zone + Set getConfiguredZones(); /** * Provides asynchronous access to Extension features. */ @Delegate - ExtensionAsyncApi getExtensionApiForRegion( - @EndpointParam(parser = RegionToEndpoint.class) @Nullable String region); + ExtensionAsyncApi getExtensionApiForZone( + @EndpointParam(parser = ZoneToEndpoint.class) @Nullable String zone); /** * Provides asynchronous access to Network features. */ @Delegate - NetworkAsyncApi getNetworkApiForRegion(@EndpointParam(parser = RegionToEndpoint.class) @Nullable String region); + NetworkAsyncApi getNetworkApiForZone(@EndpointParam(parser = ZoneToEndpoint.class) @Nullable String zone); /** * Provides asynchronous access to Port features. */ @Delegate @Path("/networks/{net}") - PortAsyncApi getPortApiForRegionAndNetwork(@EndpointParam(parser = RegionToEndpoint.class) @Nullable String region, + PortAsyncApi getPortApiForZoneAndNetwork(@EndpointParam(parser = ZoneToEndpoint.class) @Nullable String zone, @PathParam("net") String networkId); } diff --git a/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/config/QuantumRestClientModule.java b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/config/QuantumRestClientModule.java index 4b7be5ba64..4290fa1f52 100644 --- a/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/config/QuantumRestClientModule.java +++ b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/config/QuantumRestClientModule.java @@ -70,6 +70,7 @@ public class QuantumRestClientModule>() { @Override public Set load(String key) throws Exception { - return quantumApi.get().getExtensionApiForRegion(key).listExtensions(); + return quantumApi.get().getExtensionApiForZone(key).list(); } }); } diff --git a/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/NetworkApi.java b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/NetworkApi.java index 116a23eef7..795118202a 100644 --- a/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/NetworkApi.java +++ b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/NetworkApi.java @@ -18,7 +18,6 @@ */ package org.jclouds.openstack.quantum.v1_0.features; -import java.util.Set; import java.util.concurrent.TimeUnit; import org.jclouds.concurrent.Timeout; @@ -26,6 +25,8 @@ import org.jclouds.openstack.quantum.v1_0.domain.Network; import org.jclouds.openstack.quantum.v1_0.domain.NetworkDetails; import org.jclouds.openstack.quantum.v1_0.domain.Reference; +import com.google.common.collect.FluentIterable; + /** * Provides synchronous access to Network operations on the openstack quantum API. *

@@ -44,12 +45,12 @@ public interface NetworkApi { * Returns the list of all networks currently defined in Quantum for the current tenant. The list provides the unique * identifier of each network configured for the tenant. */ - Set listReferences(); + FluentIterable listReferences(); /** * Returns all networks currently defined in Quantum for the current tenant. */ - Set list(); + FluentIterable list(); /** * Returns the specific network. diff --git a/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/NetworkAsyncApi.java b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/NetworkAsyncApi.java index ffb680528c..64687a5502 100644 --- a/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/NetworkAsyncApi.java +++ b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/NetworkAsyncApi.java @@ -18,8 +18,6 @@ */ package org.jclouds.openstack.quantum.v1_0.features; -import java.util.Set; - import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; @@ -40,9 +38,10 @@ import org.jclouds.rest.annotations.RequestFilters; import org.jclouds.rest.annotations.SelectJson; import org.jclouds.rest.annotations.SkipEncoding; import org.jclouds.rest.annotations.WrapWith; -import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404; +import org.jclouds.rest.functions.ReturnEmptyFluentIterableOnNotFoundOr404; import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; +import com.google.common.collect.FluentIterable; import com.google.common.util.concurrent.ListenableFuture; /** @@ -63,8 +62,8 @@ public interface NetworkAsyncApi { */ @GET @SelectJson("networks") - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> listReferences(); + @ExceptionParser(ReturnEmptyFluentIterableOnNotFoundOr404.class) + ListenableFuture> listReferences(); /** * @see NetworkApi#list @@ -72,8 +71,8 @@ public interface NetworkAsyncApi { @GET @SelectJson("networks") @Path("/detail") - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> list(); + @ExceptionParser(ReturnEmptyFluentIterableOnNotFoundOr404.class) + ListenableFuture> list(); /** * @see NetworkApi#get diff --git a/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/PortApi.java b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/PortApi.java index 5f65506caf..b4a1680e6e 100644 --- a/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/PortApi.java +++ b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/PortApi.java @@ -18,7 +18,6 @@ */ package org.jclouds.openstack.quantum.v1_0.features; -import java.util.Set; import java.util.concurrent.TimeUnit; import org.jclouds.concurrent.Timeout; @@ -27,6 +26,8 @@ import org.jclouds.openstack.quantum.v1_0.domain.Port; import org.jclouds.openstack.quantum.v1_0.domain.PortDetails; import org.jclouds.openstack.quantum.v1_0.domain.Reference; +import com.google.common.collect.FluentIterable; + /** * Provides synchronous access to Port operations on the openstack quantum API. *

@@ -44,12 +45,12 @@ public interface PortApi { /** * Returns the list of all ports currently defined in Quantum for the requested network */ - Set listReferences(); + FluentIterable listReferences(); /** * Returns the set of ports currently defined in Quantum for the requested network. */ - Set list(); + FluentIterable list(); /** * Returns a specific port. diff --git a/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/PortAsyncApi.java b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/PortAsyncApi.java index a11b474b1d..fccae571b5 100644 --- a/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/PortAsyncApi.java +++ b/labs/openstack-quantum/src/main/java/org/jclouds/openstack/quantum/v1_0/features/PortAsyncApi.java @@ -18,8 +18,6 @@ */ package org.jclouds.openstack.quantum.v1_0.features; -import java.util.Set; - import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; @@ -40,9 +38,10 @@ import org.jclouds.rest.annotations.RequestFilters; import org.jclouds.rest.annotations.SelectJson; import org.jclouds.rest.annotations.SkipEncoding; import org.jclouds.rest.annotations.WrapWith; -import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404; +import org.jclouds.rest.functions.ReturnEmptyFluentIterableOnNotFoundOr404; import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; +import com.google.common.collect.FluentIterable; import com.google.common.util.concurrent.ListenableFuture; /** @@ -63,8 +62,8 @@ public interface PortAsyncApi { */ @GET @SelectJson("ports") - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> listReferences(); + @ExceptionParser(ReturnEmptyFluentIterableOnNotFoundOr404.class) + ListenableFuture> listReferences(); /** * @see PortApi#list @@ -72,8 +71,8 @@ public interface PortAsyncApi { @GET @SelectJson("ports") @Path("/detail") - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> list(); + @ExceptionParser(ReturnEmptyFluentIterableOnNotFoundOr404.class) + ListenableFuture> list(); /** * @see PortApi#get diff --git a/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/features/NetworkApiExpectTest.java b/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/features/NetworkApiExpectTest.java index bf23dfb041..16190fa39a 100644 --- a/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/features/NetworkApiExpectTest.java +++ b/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/features/NetworkApiExpectTest.java @@ -53,9 +53,9 @@ public class NetworkApiExpectTest extends BaseQuantumApiExpectTest { keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, authenticatedGET().endpoint(endpoint + "/tenants/3456/networks").build(), HttpResponse.builder().statusCode(200).payload(payloadFromResourceWithContentType("/list_network_refs.json", APPLICATION_JSON)).build()) - .getNetworkApiForRegion("region-a.geo-1"); + .getNetworkApiForZone("region-a.geo-1"); - Set nets = api.listReferences(); + Set nets = api.listReferences().toImmutableSet(); assertEquals(nets, listOfNetworkRefs()); } @@ -64,7 +64,7 @@ public class NetworkApiExpectTest extends BaseQuantumApiExpectTest { keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, authenticatedGET().endpoint(endpoint + "/tenants/3456/networks").build(), HttpResponse.builder().statusCode(404).build()) - .getNetworkApiForRegion("region-a.geo-1"); + .getNetworkApiForZone("region-a.geo-1"); assertTrue(api.listReferences().isEmpty()); } @@ -74,9 +74,9 @@ public class NetworkApiExpectTest extends BaseQuantumApiExpectTest { keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, authenticatedGET().endpoint(endpoint + "/tenants/3456/networks/detail").build(), HttpResponse.builder().statusCode(200).payload(payloadFromResourceWithContentType("/list_networks.json", APPLICATION_JSON)).build()) - .getNetworkApiForRegion("region-a.geo-1"); + .getNetworkApiForZone("region-a.geo-1"); - Set nets = api.list(); + Set nets = api.list().toImmutableSet(); assertEquals(nets, listOfNetworks()); } @@ -85,7 +85,7 @@ public class NetworkApiExpectTest extends BaseQuantumApiExpectTest { keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, authenticatedGET().endpoint(endpoint + "/tenants/3456/networks/detail").build(), HttpResponse.builder().statusCode(404).build()) - .getNetworkApiForRegion("region-a.geo-1"); + .getNetworkApiForZone("region-a.geo-1"); assertTrue(api.list().isEmpty()); } @@ -95,7 +95,7 @@ public class NetworkApiExpectTest extends BaseQuantumApiExpectTest { keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, authenticatedGET().endpoint(endpoint + "/tenants/3456/networks/16dba3bc-f3fa-4775-afdc-237e12c72f6a").build(), HttpResponse.builder().statusCode(200).payload(payloadFromResourceWithContentType("/network.json", APPLICATION_JSON)).build()) - .getNetworkApiForRegion("region-a.geo-1"); + .getNetworkApiForZone("region-a.geo-1"); Network net = api.get("16dba3bc-f3fa-4775-afdc-237e12c72f6a"); assertEquals(net, new ParseNetworkTest().expected()); @@ -106,7 +106,7 @@ public class NetworkApiExpectTest extends BaseQuantumApiExpectTest { keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, authenticatedGET().endpoint(endpoint + "/tenants/3456/networks/16dba3bc-f3fa-4775-afdc-237e12c72f6a").build(), HttpResponse.builder().statusCode(404).build()) - .getNetworkApiForRegion("region-a.geo-1"); + .getNetworkApiForZone("region-a.geo-1"); assertNull(api.get("16dba3bc-f3fa-4775-afdc-237e12c72f6a")); } @@ -116,7 +116,7 @@ public class NetworkApiExpectTest extends BaseQuantumApiExpectTest { keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, authenticatedGET().endpoint(endpoint + "/tenants/3456/networks/16dba3bc-f3fa-4775-afdc-237e12c72f6a/detail").build(), HttpResponse.builder().statusCode(200).payload(payloadFromResourceWithContentType("/network_details.json", APPLICATION_JSON)).build()) - .getNetworkApiForRegion("region-a.geo-1"); + .getNetworkApiForZone("region-a.geo-1"); NetworkDetails net = api.getDetails("16dba3bc-f3fa-4775-afdc-237e12c72f6a"); assertEquals(net, new ParseNetworkDetailsTest().expected()); @@ -127,7 +127,7 @@ public class NetworkApiExpectTest extends BaseQuantumApiExpectTest { keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, authenticatedGET().endpoint(endpoint + "/tenants/3456/networks/16dba3bc-f3fa-4775-afdc-237e12c72f6a/detail").build(), HttpResponse.builder().statusCode(404).build()) - .getNetworkApiForRegion("region-a.geo-1"); + .getNetworkApiForZone("region-a.geo-1"); assertNull(api.getDetails("16dba3bc-f3fa-4775-afdc-237e12c72f6a")); } @@ -138,7 +138,7 @@ public class NetworkApiExpectTest extends BaseQuantumApiExpectTest { authenticatedGET().endpoint(endpoint + "/tenants/3456/networks").method("POST") .payload(payloadFromStringWithContentType("{\"network\":{\"name\":\"another-test\"}}", MediaType.APPLICATION_JSON)).build(), HttpResponse.builder().statusCode(200).payload(payloadFromStringWithContentType("{\"network\":{\"id\":\"12345\"}}", APPLICATION_JSON)).build()) - .getNetworkApiForRegion("region-a.geo-1"); + .getNetworkApiForZone("region-a.geo-1"); Reference net = api.create("another-test"); assertEquals(net, Reference.builder().id("12345").build()); @@ -151,7 +151,7 @@ public class NetworkApiExpectTest extends BaseQuantumApiExpectTest { authenticatedGET().endpoint(endpoint + "/tenants/3456/networks").method("POST") .payload(payloadFromStringWithContentType("{\"network\":{\"name\":\"another-test\"}}", MediaType.APPLICATION_JSON)).build(), HttpResponse.builder().statusCode(401).build()) - .getNetworkApiForRegion("region-a.geo-1"); + .getNetworkApiForZone("region-a.geo-1"); api.create("another-test"); } @@ -162,7 +162,7 @@ public class NetworkApiExpectTest extends BaseQuantumApiExpectTest { authenticatedGET().endpoint(endpoint + "/tenants/3456/networks/12345").method("PUT") .payload(payloadFromStringWithContentType("{\"network\":{\"name\":\"another-test\"}}", MediaType.APPLICATION_JSON)).build(), HttpResponse.builder().statusCode(200).build()) - .getNetworkApiForRegion("region-a.geo-1"); + .getNetworkApiForZone("region-a.geo-1"); assertTrue(api.rename("12345", "another-test")); } @@ -174,7 +174,7 @@ public class NetworkApiExpectTest extends BaseQuantumApiExpectTest { authenticatedGET().endpoint(endpoint + "/tenants/3456/networks/12345").method("PUT") .payload(payloadFromStringWithContentType("{\"network\":{\"name\":\"another-test\"}}", MediaType.APPLICATION_JSON)).build(), HttpResponse.builder().statusCode(404).build()) - .getNetworkApiForRegion("region-a.geo-1"); + .getNetworkApiForZone("region-a.geo-1"); api.rename("12345", "another-test"); } @@ -184,7 +184,7 @@ public class NetworkApiExpectTest extends BaseQuantumApiExpectTest { keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, authenticatedGET().endpoint(endpoint + "/tenants/3456/networks/12345").method("DELETE").build(), HttpResponse.builder().statusCode(200).build()) - .getNetworkApiForRegion("region-a.geo-1"); + .getNetworkApiForZone("region-a.geo-1"); assertTrue(api.delete("12345")); } @@ -195,7 +195,7 @@ public class NetworkApiExpectTest extends BaseQuantumApiExpectTest { keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, authenticatedGET().endpoint(endpoint + "/tenants/3456/networks/12345").method("DELETE").build(), HttpResponse.builder().statusCode(403).build()) - .getNetworkApiForRegion("region-a.geo-1"); + .getNetworkApiForZone("region-a.geo-1"); api.delete("12345"); } diff --git a/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/features/NetworkApiLiveTest.java b/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/features/NetworkApiLiveTest.java index 5add5bf041..6f5cdb115b 100644 --- a/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/features/NetworkApiLiveTest.java +++ b/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/features/NetworkApiLiveTest.java @@ -41,9 +41,9 @@ import com.google.common.collect.ImmutableList; public class NetworkApiLiveTest extends BaseQuantumApiLiveTest { public void testListNetworks() { - for (String regionId : quantumContext.getApi().getConfiguredRegions()) { - Set ids = quantumContext.getApi().getNetworkApiForRegion(regionId).listReferences(); - Set networks = quantumContext.getApi().getNetworkApiForRegion(regionId).list(); + for (String zoneId : quantumContext.getApi().getConfiguredZones()) { + Set ids = quantumContext.getApi().getNetworkApiForZone(zoneId).listReferences().toImmutableSet(); + Set networks = quantumContext.getApi().getNetworkApiForZone(zoneId).list().toImmutableSet(); assertNotNull(ids); assertEquals(ids.size(), networks.size()); for (Network network : networks) { @@ -54,8 +54,8 @@ public class NetworkApiLiveTest extends BaseQuantumApiLiveTest { } public void testCreateUpdateAndDeleteNetwork() { - for (String regionId : quantumContext.getApi().getConfiguredRegions()) { - NetworkApi api = quantumContext.getApi().getNetworkApiForRegion(regionId); + for (String zoneId : quantumContext.getApi().getConfiguredZones()) { + NetworkApi api = quantumContext.getApi().getNetworkApiForZone(zoneId); Reference net = api.create("jclouds-test"); assertNotNull(net); diff --git a/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/features/PortApiExpectTest.java b/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/features/PortApiExpectTest.java index 02a61a1c3d..47764d3fab 100644 --- a/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/features/PortApiExpectTest.java +++ b/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/features/PortApiExpectTest.java @@ -54,9 +54,9 @@ public class PortApiExpectTest extends BaseQuantumApiExpectTest { keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, authenticatedGET().endpoint(endpoint + "/tenants/3456/networks/1a104cf5-cb18-4d35-9407-2fd2646d9d0b/ports").build(), HttpResponse.builder().statusCode(200).payload(payloadFromStringWithContentType("{\"ports\": [{\"id\": \"a6058a59-fa8c-46cc-bac8-08904e6ff0a5\"}]}", APPLICATION_JSON)).build()) - .getPortApiForRegionAndNetwork("region-a.geo-1", "1a104cf5-cb18-4d35-9407-2fd2646d9d0b"); + .getPortApiForZoneAndNetwork("region-a.geo-1", "1a104cf5-cb18-4d35-9407-2fd2646d9d0b"); - Set nets = api.listReferences(); + Set nets = api.listReferences().toImmutableSet(); assertEquals(nets, ImmutableSet.of(Reference.builder().id("a6058a59-fa8c-46cc-bac8-08904e6ff0a5").build())); } @@ -65,7 +65,7 @@ public class PortApiExpectTest extends BaseQuantumApiExpectTest { keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, authenticatedGET().endpoint(endpoint + "/tenants/3456/networks/1a104cf5-cb18-4d35-9407-2fd2646d9d0b/ports").build(), HttpResponse.builder().statusCode(404).build()) - .getPortApiForRegionAndNetwork("region-a.geo-1", "1a104cf5-cb18-4d35-9407-2fd2646d9d0b"); + .getPortApiForZoneAndNetwork("region-a.geo-1", "1a104cf5-cb18-4d35-9407-2fd2646d9d0b"); assertTrue(api.listReferences().isEmpty()); } @@ -75,9 +75,9 @@ public class PortApiExpectTest extends BaseQuantumApiExpectTest { keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, authenticatedGET().endpoint(endpoint + "/tenants/3456/networks/1a104cf5-cb18-4d35-9407-2fd2646d9d0b/ports/detail").build(), HttpResponse.builder().statusCode(200).payload(payloadFromStringWithContentType("{\"ports\": [{\"state\": \"DOWN\", \"id\": \"814ae4bb-33d9-425f-8ee2-13a5c90b1465\"}]}", APPLICATION_JSON)).build()) - .getPortApiForRegionAndNetwork("region-a.geo-1", "1a104cf5-cb18-4d35-9407-2fd2646d9d0b"); + .getPortApiForZoneAndNetwork("region-a.geo-1", "1a104cf5-cb18-4d35-9407-2fd2646d9d0b"); - Set nets = api.list(); + Set nets = api.list().toImmutableSet(); assertEquals(nets, ImmutableSet.of(Port.builder().state(Port.State.DOWN).id("814ae4bb-33d9-425f-8ee2-13a5c90b1465").build())); } @@ -86,7 +86,7 @@ public class PortApiExpectTest extends BaseQuantumApiExpectTest { keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, authenticatedGET().endpoint(endpoint + "/tenants/3456/networks/1a104cf5-cb18-4d35-9407-2fd2646d9d0b/ports/detail").build(), HttpResponse.builder().statusCode(404).build()) - .getPortApiForRegionAndNetwork("region-a.geo-1", "1a104cf5-cb18-4d35-9407-2fd2646d9d0b"); + .getPortApiForZoneAndNetwork("region-a.geo-1", "1a104cf5-cb18-4d35-9407-2fd2646d9d0b"); assertTrue(api.list().isEmpty()); } @@ -96,7 +96,7 @@ public class PortApiExpectTest extends BaseQuantumApiExpectTest { keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, authenticatedGET().endpoint(endpoint + "/tenants/3456/networks/16dba3bc-f3fa-4775-afdc-237e12c72f6a/ports/646c123b-871a-4124-9fa2-a94f04a582df").build(), HttpResponse.builder().statusCode(200).payload(payloadFromResourceWithContentType("/port.json", APPLICATION_JSON)).build()) - .getPortApiForRegionAndNetwork("region-a.geo-1", "16dba3bc-f3fa-4775-afdc-237e12c72f6a"); + .getPortApiForZoneAndNetwork("region-a.geo-1", "16dba3bc-f3fa-4775-afdc-237e12c72f6a"); Port port = api.get("646c123b-871a-4124-9fa2-a94f04a582df"); assertEquals(port, new ParsePortTest().expected()); @@ -107,7 +107,7 @@ public class PortApiExpectTest extends BaseQuantumApiExpectTest { keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, authenticatedGET().endpoint(endpoint + "/tenants/3456/networks/16dba3bc-f3fa-4775-afdc-237e12c72f6a/ports/646c123b-871a-4124-9fa2-a94f04a582df").build(), HttpResponse.builder().statusCode(404).build()) - .getPortApiForRegionAndNetwork("region-a.geo-1", "16dba3bc-f3fa-4775-afdc-237e12c72f6a"); + .getPortApiForZoneAndNetwork("region-a.geo-1", "16dba3bc-f3fa-4775-afdc-237e12c72f6a"); assertNull(api.get("646c123b-871a-4124-9fa2-a94f04a582df")); } @@ -117,7 +117,7 @@ public class PortApiExpectTest extends BaseQuantumApiExpectTest { keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, authenticatedGET().endpoint(endpoint + "/tenants/3456/networks/16dba3bc-f3fa-4775-afdc-237e12c72f6a/ports/646c123b-871a-4124-9fa2-a94f04a582df/detail").build(), HttpResponse.builder().statusCode(200).payload(payloadFromResourceWithContentType("/port_details.json", APPLICATION_JSON)).build()) - .getPortApiForRegionAndNetwork("region-a.geo-1", "16dba3bc-f3fa-4775-afdc-237e12c72f6a"); + .getPortApiForZoneAndNetwork("region-a.geo-1", "16dba3bc-f3fa-4775-afdc-237e12c72f6a"); PortDetails net = api.getDetails("646c123b-871a-4124-9fa2-a94f04a582df"); assertEquals(net, new ParsePortDetailsTest().expected()); @@ -128,7 +128,7 @@ public class PortApiExpectTest extends BaseQuantumApiExpectTest { keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, authenticatedGET().endpoint(endpoint + "/tenants/3456/networks/16dba3bc-f3fa-4775-afdc-237e12c72f6a/ports/646c123b-871a-4124-9fa2-a94f04a582df/detail").build(), HttpResponse.builder().statusCode(404).build()) - .getPortApiForRegionAndNetwork("region-a.geo-1", "16dba3bc-f3fa-4775-afdc-237e12c72f6a"); + .getPortApiForZoneAndNetwork("region-a.geo-1", "16dba3bc-f3fa-4775-afdc-237e12c72f6a"); assertNull(api.getDetails("646c123b-871a-4124-9fa2-a94f04a582df")); } @@ -138,7 +138,7 @@ public class PortApiExpectTest extends BaseQuantumApiExpectTest { keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, authenticatedGET().endpoint(endpoint + "/tenants/3456/networks/16dba3bc-f3fa-4775-afdc-237e12c72f6a/ports").method("POST").build(), HttpResponse.builder().statusCode(200).payload(payloadFromStringWithContentType("{\"port\":{\"id\":\"12345\"}}", APPLICATION_JSON)).build()) - .getPortApiForRegionAndNetwork("region-a.geo-1", "16dba3bc-f3fa-4775-afdc-237e12c72f6a"); + .getPortApiForZoneAndNetwork("region-a.geo-1", "16dba3bc-f3fa-4775-afdc-237e12c72f6a"); Reference port = api.create(); assertEquals(port, Reference.builder().id("12345").build()); @@ -150,7 +150,7 @@ public class PortApiExpectTest extends BaseQuantumApiExpectTest { keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, authenticatedGET().endpoint(endpoint + "/tenants/3456/networks/16dba3bc-f3fa-4775-afdc-237e12c72f6a/ports").method("POST").build(), HttpResponse.builder().statusCode(404).build()) - .getPortApiForRegionAndNetwork("region-a.geo-1", "16dba3bc-f3fa-4775-afdc-237e12c72f6a"); + .getPortApiForZoneAndNetwork("region-a.geo-1", "16dba3bc-f3fa-4775-afdc-237e12c72f6a"); api.create(); } @@ -161,7 +161,7 @@ public class PortApiExpectTest extends BaseQuantumApiExpectTest { authenticatedGET().endpoint(endpoint + "/tenants/3456/networks/16dba3bc-f3fa-4775-afdc-237e12c72f6a/ports/77777").method("PUT") .payload(payloadFromStringWithContentType("{\"port\":{\"state\":\"ACTIVE\"}}", MediaType.APPLICATION_JSON)).build(), HttpResponse.builder().statusCode(200).build()) - .getPortApiForRegionAndNetwork("region-a.geo-1", "16dba3bc-f3fa-4775-afdc-237e12c72f6a"); + .getPortApiForZoneAndNetwork("region-a.geo-1", "16dba3bc-f3fa-4775-afdc-237e12c72f6a"); assertTrue(api.updateState("77777", Port.State.ACTIVE)); } @@ -173,7 +173,7 @@ public class PortApiExpectTest extends BaseQuantumApiExpectTest { authenticatedGET().endpoint(endpoint + "/tenants/3456/networks/16dba3bc-f3fa-4775-afdc-237e12c72f6a/ports/77777").method("PUT") .payload(payloadFromStringWithContentType("{\"port\":{\"state\":\"ACTIVE\"}}", MediaType.APPLICATION_JSON)).build(), HttpResponse.builder().statusCode(401).build()) - .getPortApiForRegionAndNetwork("region-a.geo-1", "16dba3bc-f3fa-4775-afdc-237e12c72f6a"); + .getPortApiForZoneAndNetwork("region-a.geo-1", "16dba3bc-f3fa-4775-afdc-237e12c72f6a"); api.updateState("77777", Port.State.ACTIVE); } @@ -183,7 +183,7 @@ public class PortApiExpectTest extends BaseQuantumApiExpectTest { keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, authenticatedGET().endpoint(endpoint + "/tenants/3456/networks/16dba3bc-f3fa-4775-afdc-237e12c72f6a/ports/77777/attachment").build(), HttpResponse.builder().statusCode(200).payload(payloadFromResourceWithContentType("/attachment.json", APPLICATION_JSON)).build()) - .getPortApiForRegionAndNetwork("region-a.geo-1", "16dba3bc-f3fa-4775-afdc-237e12c72f6a"); + .getPortApiForZoneAndNetwork("region-a.geo-1", "16dba3bc-f3fa-4775-afdc-237e12c72f6a"); Attachment attachment = api.showAttachment("77777"); assertEquals(attachment, Attachment.builder().id("jclouds-live-test").build()); @@ -194,7 +194,7 @@ public class PortApiExpectTest extends BaseQuantumApiExpectTest { keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, authenticatedGET().endpoint(endpoint + "/tenants/3456/networks/16dba3bc-f3fa-4775-afdc-237e12c72f6a/ports/77777/attachment").build(), HttpResponse.builder().statusCode(404).build()) - .getPortApiForRegionAndNetwork("region-a.geo-1", "16dba3bc-f3fa-4775-afdc-237e12c72f6a"); + .getPortApiForZoneAndNetwork("region-a.geo-1", "16dba3bc-f3fa-4775-afdc-237e12c72f6a"); assertNull(api.showAttachment("77777")); } @@ -206,7 +206,7 @@ public class PortApiExpectTest extends BaseQuantumApiExpectTest { .payload(payloadFromStringWithContentType("{\"attachment\":{\"id\":\"jclouds-live-test\"}}", MediaType.APPLICATION_JSON)) .method("PUT").build(), HttpResponse.builder().statusCode(200).build()) - .getPortApiForRegionAndNetwork("region-a.geo-1", "16dba3bc-f3fa-4775-afdc-237e12c72f6a"); + .getPortApiForZoneAndNetwork("region-a.geo-1", "16dba3bc-f3fa-4775-afdc-237e12c72f6a"); assertTrue(api.plugAttachment("77777", "jclouds-live-test")); } @@ -219,7 +219,7 @@ public class PortApiExpectTest extends BaseQuantumApiExpectTest { .payload(payloadFromStringWithContentType("{\"attachment\":{\"id\":\"jclouds-live-test\"}}", MediaType.APPLICATION_JSON)) .method("PUT").build(), HttpResponse.builder().statusCode(403).build()) - .getPortApiForRegionAndNetwork("region-a.geo-1", "16dba3bc-f3fa-4775-afdc-237e12c72f6a"); + .getPortApiForZoneAndNetwork("region-a.geo-1", "16dba3bc-f3fa-4775-afdc-237e12c72f6a"); api.plugAttachment("77777", "jclouds-live-test"); } @@ -228,7 +228,7 @@ public class PortApiExpectTest extends BaseQuantumApiExpectTest { keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, authenticatedGET().endpoint(endpoint + "/tenants/3456/networks/16dba3bc-f3fa-4775-afdc-237e12c72f6a/ports/77777/attachment").method("DELETE").build(), HttpResponse.builder().statusCode(200).build()) - .getPortApiForRegionAndNetwork("region-a.geo-1", "16dba3bc-f3fa-4775-afdc-237e12c72f6a"); + .getPortApiForZoneAndNetwork("region-a.geo-1", "16dba3bc-f3fa-4775-afdc-237e12c72f6a"); assertTrue(api.unplugAttachment("77777")); } @@ -239,7 +239,7 @@ public class PortApiExpectTest extends BaseQuantumApiExpectTest { keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess, authenticatedGET().endpoint(endpoint + "/tenants/3456/networks/16dba3bc-f3fa-4775-afdc-237e12c72f6a/ports/77777/attachment").method("DELETE").build(), HttpResponse.builder().statusCode(404).build()) - .getPortApiForRegionAndNetwork("region-a.geo-1", "16dba3bc-f3fa-4775-afdc-237e12c72f6a"); + .getPortApiForZoneAndNetwork("region-a.geo-1", "16dba3bc-f3fa-4775-afdc-237e12c72f6a"); api.unplugAttachment("77777"); } diff --git a/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/features/PortApiLiveTest.java b/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/features/PortApiLiveTest.java index b179061fe0..baf37ffcc8 100644 --- a/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/features/PortApiLiveTest.java +++ b/labs/openstack-quantum/src/test/java/org/jclouds/openstack/quantum/v1_0/features/PortApiLiveTest.java @@ -44,13 +44,13 @@ import com.google.common.collect.Iterables; public class PortApiLiveTest extends BaseQuantumApiLiveTest { public void testListPorts() { - for (String regionId : quantumContext.getApi().getConfiguredRegions()) { - NetworkApi netApi = quantumContext.getApi().getNetworkApiForRegion(regionId); - Set nets = netApi.listReferences(); + for (String zoneId : quantumContext.getApi().getConfiguredZones()) { + NetworkApi netApi = quantumContext.getApi().getNetworkApiForZone(zoneId); + Set nets = netApi.listReferences().toImmutableSet(); for(Reference net : nets) { - PortApi portApi = quantumContext.getApi().getPortApiForRegionAndNetwork(regionId, net.getId()); - Set portRefs = portApi.listReferences(); - Set ports = portApi.list(); + PortApi portApi = quantumContext.getApi().getPortApiForZoneAndNetwork(zoneId, net.getId()); + Set portRefs = portApi.listReferences().toImmutableSet(); + Set ports = portApi.list().toImmutableSet(); assertEquals(portRefs.size(), ports.size()); for (Port port : ports) { @@ -61,11 +61,11 @@ public class PortApiLiveTest extends BaseQuantumApiLiveTest { } public void testCreateUpdateAndDeletePort() { - for (String regionId : quantumContext.getApi().getConfiguredRegions()) { - NetworkApi netApi = quantumContext.getApi().getNetworkApiForRegion(regionId); + for (String zoneId : quantumContext.getApi().getConfiguredZones()) { + NetworkApi netApi = quantumContext.getApi().getNetworkApiForZone(zoneId); Reference net = netApi.create("jclouds-port-test"); assertNotNull(net); - PortApi portApi = quantumContext.getApi().getPortApiForRegionAndNetwork(regionId, net.getId()); + PortApi portApi = quantumContext.getApi().getPortApiForZoneAndNetwork(zoneId, net.getId()); Reference portRef = portApi.create(); assertNotNull(portRef); @@ -109,12 +109,12 @@ public class PortApiLiveTest extends BaseQuantumApiLiveTest { @Test(enabled=false) // assuming attachmentId matters in the wild public void testAttachAndDetachPort() { - for (String regionId : quantumContext.getApi().getConfiguredRegions()) { - NetworkApi netApi = quantumContext.getApi().getNetworkApiForRegion(regionId); + for (String zoneId : quantumContext.getApi().getConfiguredZones()) { + NetworkApi netApi = quantumContext.getApi().getNetworkApiForZone(zoneId); Reference net = netApi.create("jclouds-attach-test"); assertNotNull(net); - PortApi portApi = quantumContext.getApi().getPortApiForRegionAndNetwork(regionId, net.getId()); + PortApi portApi = quantumContext.getApi().getPortApiForZoneAndNetwork(zoneId, net.getId()); Reference port = portApi.create(); assertNotNull(port); diff --git a/labs/openstack-swift/pom.xml b/labs/openstack-swift/pom.xml index 4bab5dfd87..659e0a99a5 100644 --- a/labs/openstack-swift/pom.xml +++ b/labs/openstack-swift/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.labs diff --git a/labs/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/config/SwiftRestClientModule.java b/labs/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/config/SwiftRestClientModule.java index a0489d09d5..fe022ae57b 100644 --- a/labs/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/config/SwiftRestClientModule.java +++ b/labs/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/config/SwiftRestClientModule.java @@ -73,6 +73,7 @@ public class SwiftRestClientModule .put(ObjectApi.class, ObjectAsyncApi.class) .build(); + @SuppressWarnings("unchecked") public SwiftRestClientModule() { super(TypeToken.class.cast(TypeToken.of(SwiftApi.class)), TypeToken.class.cast(TypeToken.of(SwiftAsyncApi.class)), DELEGATE_MAP); } @@ -102,7 +103,7 @@ public class SwiftRestClientModule .build(new CacheLoader>() { @Override public Set load(String key) throws Exception { - return swiftApi.get().getExtensionApiForRegion(key).listExtensions(); + return swiftApi.get().getExtensionApiForRegion(key).list(); } }); } diff --git a/labs/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/domain/AccountMetadata.java b/labs/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/domain/Account.java similarity index 82% rename from labs/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/domain/AccountMetadata.java rename to labs/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/domain/Account.java index b3e70dab84..db428965da 100644 --- a/labs/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/domain/AccountMetadata.java +++ b/labs/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/domain/Account.java @@ -12,7 +12,7 @@ import com.google.common.base.Objects.ToStringHelper; * @author Adrian Cole * @see api doc */ -public class AccountMetadata { +public class Account { public static Builder builder() { return new Builder(); @@ -27,7 +27,7 @@ public class AccountMetadata { protected long bytesUsed; /** - * @see AccountMetadata#getContainerCount() + * @see Account#getContainerCount() */ public Builder containerCount(int containerCount) { this.containerCount = containerCount; @@ -35,18 +35,18 @@ public class AccountMetadata { } /** - * @see AccountMetadata#getBytesUsed() + * @see Account#getBytesUsed() */ public Builder bytesUsed(long bytesUsed) { this.bytesUsed = bytesUsed; return this; } - public AccountMetadata build() { - return new AccountMetadata(containerCount, bytesUsed); + public Account build() { + return new Account(containerCount, bytesUsed); } - public Builder fromAccountMetadata(AccountMetadata from) { + public Builder fromAccountMetadata(Account from) { return containerCount(from.getContainerCount()).bytesUsed(from.getBytesUsed()); } } @@ -55,7 +55,7 @@ public class AccountMetadata { protected long bytesUsed; @ConstructorProperties({"containerCount", "bytesUsed"}) - protected AccountMetadata(int containerCount, long bytesUsed) { + protected Account(int containerCount, long bytesUsed) { this.containerCount = containerCount; this.bytesUsed = bytesUsed; } @@ -80,8 +80,8 @@ public class AccountMetadata { if (this == object) { return true; } - if (object instanceof AccountMetadata) { - final AccountMetadata other = AccountMetadata.class.cast(object); + if (object instanceof Account) { + final Account other = Account.class.cast(object); return equal(getContainerCount(), other.getContainerCount()) && equal(getBytesUsed(), other.getBytesUsed()); } else { return false; diff --git a/labs/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/domain/ContainerMetadata.java b/labs/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/domain/Container.java similarity index 81% rename from labs/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/domain/ContainerMetadata.java rename to labs/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/domain/Container.java index 1cbff854b0..ef459e6d62 100644 --- a/labs/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/domain/ContainerMetadata.java +++ b/labs/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/domain/Container.java @@ -19,14 +19,14 @@ import com.google.common.base.Objects.ToStringHelper; * href="http://docs.openstack.org/api/openstack-object-storage/1.0/content/s_listcontainers.html">api * doc */ -public class ContainerMetadata implements Comparable { +public class Container implements Comparable { public static Builder builder() { return new Builder(); } public Builder toBuilder() { - return builder().fromAccountMetadata(this); + return builder().fromContainer(this); } public static class Builder { @@ -35,7 +35,7 @@ public class ContainerMetadata implements Comparable { protected int bytes; /** - * @see ContainerMetadata#getName() + * @see Container#getName() */ public Builder name(String name) { this.name = checkNotNull(name, "name"); @@ -43,7 +43,7 @@ public class ContainerMetadata implements Comparable { } /** - * @see ContainerMetadata#getCount() + * @see Container#getCount() */ public Builder count(int count) { this.count = count; @@ -51,18 +51,18 @@ public class ContainerMetadata implements Comparable { } /** - * @see ContainerMetadata#getBytes() + * @see Container#getBytes() */ public Builder bytes(int bytes) { this.bytes = bytes; return this; } - public ContainerMetadata build() { - return new ContainerMetadata(name, count, bytes); + public Container build() { + return new Container(name, count, bytes); } - public Builder fromAccountMetadata(ContainerMetadata from) { + public Builder fromContainer(Container from) { return name(from.getName()).count(from.getCount()).bytes(from.getBytes()); } } @@ -72,7 +72,7 @@ public class ContainerMetadata implements Comparable { protected int bytes; @ConstructorProperties({"name", "count", "bytes"}) - protected ContainerMetadata(String name, int count, int bytes) { + protected Container(String name, int count, int bytes) { this.name = checkNotNull(name, "name"); this.count = count; this.bytes = bytes; @@ -106,8 +106,8 @@ public class ContainerMetadata implements Comparable { if (this == object) { return true; } - if (object instanceof ContainerMetadata) { - final ContainerMetadata other = ContainerMetadata.class.cast(object); + if (object instanceof Container) { + final Container other = Container.class.cast(object); return equal(getName(), other.getName()) && equal(getCount(), other.getCount()) && equal(getBytes(), other.getBytes()); } else { @@ -130,7 +130,7 @@ public class ContainerMetadata implements Comparable { } @Override - public int compareTo(ContainerMetadata that) { + public int compareTo(Container that) { if (that == null) return 1; if (this == that) diff --git a/labs/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/features/AccountApi.java b/labs/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/features/AccountApi.java index 1cf2e2b664..78d8a31f04 100644 --- a/labs/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/features/AccountApi.java +++ b/labs/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/features/AccountApi.java @@ -18,13 +18,10 @@ */ package org.jclouds.openstack.swift.v1.features; -import java.util.Set; import java.util.concurrent.TimeUnit; import org.jclouds.concurrent.Timeout; -import org.jclouds.openstack.swift.v1.domain.AccountMetadata; -import org.jclouds.openstack.swift.v1.domain.ContainerMetadata; -import org.jclouds.openstack.swift.v1.options.ListContainersOptions; +import org.jclouds.openstack.swift.v1.domain.Account; /** * Storage Account Services @@ -37,26 +34,12 @@ import org.jclouds.openstack.swift.v1.options.ListContainersOptions; */ @Timeout(duration = 180, timeUnit = TimeUnit.SECONDS) public interface AccountApi { + /** * Retrieve Account Metadata * * @return account metadata including container count and bytes used */ - AccountMetadata getAccountMetadata(); - - /** - * @see #listContainers(ListContainersOptions) - */ - Set listContainers(); - - /** - * retrieve a list of existing storage containers ordered by name. The sort order for the name is - * based on a binary comparison, a single built-in collating sequence that compares string data - * using SQLite's memcmp() function, regardless of text encoding. - * - * @param options - * @return a list of existing storage containers ordered by name. - */ - Set listContainers(ListContainersOptions options); + Account get(); } diff --git a/labs/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/features/AccountAsyncApi.java b/labs/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/features/AccountAsyncApi.java index de64deef66..9473428a5b 100644 --- a/labs/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/features/AccountAsyncApi.java +++ b/labs/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/features/AccountAsyncApi.java @@ -18,25 +18,15 @@ */ package org.jclouds.openstack.swift.v1.features; -import java.util.Set; - -import javax.ws.rs.Consumes; -import javax.ws.rs.GET; import javax.ws.rs.HEAD; import javax.ws.rs.Path; -import javax.ws.rs.core.MediaType; import org.jclouds.openstack.keystone.v2_0.filters.AuthenticateRequest; -import org.jclouds.openstack.swift.v1.domain.AccountMetadata; -import org.jclouds.openstack.swift.v1.domain.ContainerMetadata; +import org.jclouds.openstack.swift.v1.domain.Account; import org.jclouds.openstack.swift.v1.functions.ParseAccountMetadataResponseFromHeaders; -import org.jclouds.openstack.swift.v1.options.ListContainersOptions; -import org.jclouds.rest.annotations.ExceptionParser; -import org.jclouds.rest.annotations.QueryParams; import org.jclouds.rest.annotations.RequestFilters; import org.jclouds.rest.annotations.ResponseParser; import org.jclouds.rest.annotations.SkipEncoding; -import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404; import com.google.common.util.concurrent.ListenableFuture; @@ -54,30 +44,11 @@ import com.google.common.util.concurrent.ListenableFuture; public interface AccountAsyncApi { /** - * @see AccountApi#getAccountMetadata + * @see AccountApi#get */ @HEAD @ResponseParser(ParseAccountMetadataResponseFromHeaders.class) @Path("/") - ListenableFuture getAccountMetadata(); + ListenableFuture get(); - /** - * @see AccountApi#listContainers() - */ - @GET - @Consumes(MediaType.APPLICATION_JSON) - @QueryParams(keys = "format", values = "json") - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - @Path("/") - ListenableFuture> listContainers(); - - /** - * @see AccountApi#listContainers(ListContainersOptions) - */ - @GET - @Consumes(MediaType.APPLICATION_JSON) - @QueryParams(keys = "format", values = "json") - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - @Path("/") - ListenableFuture> listContainers(ListContainersOptions options); } diff --git a/labs/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/features/ContainerApi.java b/labs/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/features/ContainerApi.java index 7da668efc8..f87e2b4ad1 100644 --- a/labs/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/features/ContainerApi.java +++ b/labs/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/features/ContainerApi.java @@ -21,6 +21,10 @@ package org.jclouds.openstack.swift.v1.features; import java.util.concurrent.TimeUnit; import org.jclouds.concurrent.Timeout; +import org.jclouds.openstack.swift.v1.domain.Container; +import org.jclouds.openstack.swift.v1.options.ListContainersOptions; + +import com.google.common.collect.FluentIterable; /** * Storage Container Services @@ -34,4 +38,19 @@ import org.jclouds.concurrent.Timeout; @Timeout(duration = 180, timeUnit = TimeUnit.SECONDS) public interface ContainerApi { + /** + * @see #list(ListContainersOptions) + */ + FluentIterable list(); + + /** + * retrieve a list of existing storage containers ordered by name. The sort order for the name is + * based on a binary comparison, a single built-in collating sequence that compares string data + * using SQLite's memcmp() function, regardless of text encoding. + * + * @param options + * @return a list of existing storage containers ordered by name. + */ + FluentIterable list(ListContainersOptions options); + } diff --git a/labs/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/features/ContainerAsyncApi.java b/labs/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/features/ContainerAsyncApi.java index 996d6a2007..b5978b1088 100644 --- a/labs/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/features/ContainerAsyncApi.java +++ b/labs/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/features/ContainerAsyncApi.java @@ -18,9 +18,22 @@ */ package org.jclouds.openstack.swift.v1.features; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.core.MediaType; + import org.jclouds.openstack.keystone.v2_0.filters.AuthenticateRequest; +import org.jclouds.openstack.swift.v1.domain.Container; +import org.jclouds.openstack.swift.v1.options.ListContainersOptions; +import org.jclouds.rest.annotations.ExceptionParser; +import org.jclouds.rest.annotations.QueryParams; import org.jclouds.rest.annotations.RequestFilters; import org.jclouds.rest.annotations.SkipEncoding; +import org.jclouds.rest.functions.ReturnEmptyFluentIterableOnNotFoundOr404; + +import com.google.common.collect.FluentIterable; +import com.google.common.util.concurrent.ListenableFuture; /** * Storage Container Services @@ -35,4 +48,23 @@ import org.jclouds.rest.annotations.SkipEncoding; @RequestFilters(AuthenticateRequest.class) public interface ContainerAsyncApi { + /** + * @see ContainerApi#list() + */ + @GET + @Consumes(MediaType.APPLICATION_JSON) + @QueryParams(keys = "format", values = "json") + @ExceptionParser(ReturnEmptyFluentIterableOnNotFoundOr404.class) + @Path("/") + ListenableFuture> list(); + + /** + * @see ContainerApi#list(ListContainersOptions) + */ + @GET + @Consumes(MediaType.APPLICATION_JSON) + @QueryParams(keys = "format", values = "json") + @ExceptionParser(ReturnEmptyFluentIterableOnNotFoundOr404.class) + @Path("/") + ListenableFuture> list(ListContainersOptions options); } diff --git a/labs/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/functions/ParseAccountMetadataResponseFromHeaders.java b/labs/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/functions/ParseAccountMetadataResponseFromHeaders.java index e01ccadfed..d0271e6966 100644 --- a/labs/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/functions/ParseAccountMetadataResponseFromHeaders.java +++ b/labs/openstack-swift/src/main/java/org/jclouds/openstack/swift/v1/functions/ParseAccountMetadataResponseFromHeaders.java @@ -19,22 +19,22 @@ package org.jclouds.openstack.swift.v1.functions; import org.jclouds.http.HttpResponse; -import org.jclouds.openstack.swift.v1.domain.AccountMetadata; +import org.jclouds.openstack.swift.v1.domain.Account; import com.google.common.base.Function; /** - * This parses {@link AccountMetadata} from HTTP headers. + * This parses {@link Account} from HTTP headers. * * @author James Murty */ -public class ParseAccountMetadataResponseFromHeaders implements Function { +public class ParseAccountMetadataResponseFromHeaders implements Function { /** - * parses the http response headers to create a new {@link AccountMetadata} object. + * parses the http response headers to create a new {@link Account} object. */ - public AccountMetadata apply(HttpResponse from) { - return AccountMetadata.builder() + public Account apply(HttpResponse from) { + return Account.builder() .bytesUsed(Long.parseLong(from.getFirstHeaderOrNull("X-Account-Bytes-Used"))) .containerCount(Integer.parseInt(from.getFirstHeaderOrNull("X-Account-Container-Count"))) .build(); diff --git a/labs/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/PasswordAuthenticationExpectTest.java b/labs/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/PasswordAuthenticationExpectTest.java index 1678c1499a..fa0006e92f 100644 --- a/labs/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/PasswordAuthenticationExpectTest.java +++ b/labs/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/PasswordAuthenticationExpectTest.java @@ -50,22 +50,22 @@ public class PasswordAuthenticationExpectTest extends BaseSwiftApiExpectTest { } public void testListContainersWhenResponseIs2xx() throws Exception { - HttpRequest listContainers = HttpRequest + HttpRequest list = HttpRequest .builder() .method("GET") .endpoint("https://objects.jclouds.org/v1.0/40806637803162/?format=json") .addHeader("Accept", "application/json") .addHeader("X-Auth-Token", authToken).build(); - HttpResponse listContainersResponse = HttpResponse.builder().statusCode(200) + HttpResponse listResponse = HttpResponse.builder().statusCode(200) .payload(payloadFromResource("/container_list.json")).build(); SwiftApi apiWhenContainersExist = requestsSendResponses(keystoneAuthWithUsernameAndPassword, - responseWithKeystoneAccess, listContainers, listContainersResponse); + responseWithKeystoneAccess, list, listResponse); assertEquals(apiWhenContainersExist.getConfiguredRegions(), ImmutableSet.of("region-a.geo-1")); - assertEquals(apiWhenContainersExist.getAccountApiForRegion("region-a.geo-1").listContainers().toString(), + assertEquals(apiWhenContainersExist.getContainerApiForRegion("region-a.geo-1").list().toString(), new ParseContainerListTest().expected().toString()); } diff --git a/labs/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/features/AccountApiExpectTest.java b/labs/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/features/AccountApiExpectTest.java index edf50af3e9..edffd00ebf 100644 --- a/labs/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/features/AccountApiExpectTest.java +++ b/labs/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/features/AccountApiExpectTest.java @@ -23,13 +23,10 @@ import static org.testng.Assert.assertEquals; import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpResponse; import org.jclouds.openstack.swift.v1.SwiftApi; -import org.jclouds.openstack.swift.v1.domain.AccountMetadata; +import org.jclouds.openstack.swift.v1.domain.Account; import org.jclouds.openstack.swift.v1.internal.BaseSwiftApiExpectTest; -import org.jclouds.openstack.swift.v1.parse.ParseContainerListTest; import org.testng.annotations.Test; -import com.google.common.collect.ImmutableSet; - /** * @author Adrian Cole */ @@ -38,59 +35,23 @@ public class AccountApiExpectTest extends BaseSwiftApiExpectTest { public void testGetAccountMetadataWhenResponseIs2xx() throws Exception { - HttpRequest getAccountMetadata = HttpRequest + HttpRequest get = HttpRequest .builder() .method("HEAD") .endpoint("https://objects.jclouds.org/v1.0/40806637803162/") .addHeader("X-Auth-Token", authToken).build(); - HttpResponse listContainersResponse = HttpResponse.builder().statusCode(204) + HttpResponse listResponse = HttpResponse.builder().statusCode(204) .addHeader("X-Account-Container-Count", "3") .addHeader("X-Account-Bytes-Used", "323479").build(); - SwiftApi apiWhenContainersExist = requestsSendResponses(keystoneAuthWithUsernameAndPassword, - responseWithKeystoneAccess, getAccountMetadata, listContainersResponse); + SwiftApi apiWhenExists = requestsSendResponses(keystoneAuthWithUsernameAndPassword, + responseWithKeystoneAccess, get, listResponse); assertEquals( - apiWhenContainersExist.getAccountApiForRegion("region-a.geo-1").getAccountMetadata(), - AccountMetadata.builder().containerCount(3).bytesUsed(323479).build()); + apiWhenExists.getAccountApiForRegion("region-a.geo-1").get(), + Account.builder().containerCount(3).bytesUsed(323479).build()); } - public void testListContainersWhenResponseIs2xx() throws Exception { - - HttpRequest listContainers = HttpRequest - .builder() - .method("GET") - .endpoint("https://objects.jclouds.org/v1.0/40806637803162/?format=json") - .addHeader("Accept", "application/json") - .addHeader("X-Auth-Token", authToken).build(); - - HttpResponse listContainersResponse = HttpResponse.builder().statusCode(200) - .payload(payloadFromResource("/container_list.json")).build(); - - SwiftApi apiWhenContainersExist = requestsSendResponses(keystoneAuthWithUsernameAndPassword, - responseWithKeystoneAccess, listContainers, listContainersResponse); - - assertEquals( - apiWhenContainersExist.getAccountApiForRegion("region-a.geo-1").listContainers() - .toString(), new ParseContainerListTest().expected().toString()); - } - - public void testListContainersWhenResponseIs404() throws Exception { - HttpRequest listContainers = HttpRequest - .builder() - .method("GET") - .endpoint("https://objects.jclouds.org/v1.0/40806637803162/?format=json") - .addHeader("Accept", "application/json") - .addHeader("X-Auth-Token", authToken).build(); - - HttpResponse listContainersResponse = HttpResponse.builder().statusCode(404).build(); - - SwiftApi apiWhenNoContainersExist = requestsSendResponses(keystoneAuthWithUsernameAndPassword, - responseWithKeystoneAccess, listContainers, listContainersResponse); - - assertEquals(apiWhenNoContainersExist.getAccountApiForRegion("region-a.geo-1").listContainers(), ImmutableSet.of()); - - } } diff --git a/labs/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/features/AccountApiLiveTest.java b/labs/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/features/AccountApiLiveTest.java index 8521c0e236..6232d6dbdf 100644 --- a/labs/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/features/AccountApiLiveTest.java +++ b/labs/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/features/AccountApiLiveTest.java @@ -21,10 +21,7 @@ package org.jclouds.openstack.swift.v1.features; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; -import java.util.Set; - -import org.jclouds.openstack.swift.v1.domain.AccountMetadata; -import org.jclouds.openstack.swift.v1.domain.ContainerMetadata; +import org.jclouds.openstack.swift.v1.domain.Account; import org.jclouds.openstack.swift.v1.internal.BaseSwiftApiLiveTest; import org.testng.annotations.Test; @@ -38,24 +35,11 @@ public class AccountApiLiveTest extends BaseSwiftApiLiveTest { public void testGetAccountMetadata() throws Exception { for (String regionId : swiftContext.getApi().getConfiguredRegions()) { AccountApi api = swiftContext.getApi().getAccountApiForRegion(regionId); - AccountMetadata account = api.getAccountMetadata(); + Account account = api.get(); assertNotNull(account); assertTrue(account.getContainerCount() >= 0); assertTrue(account.getBytesUsed() >= 0); } } - @Test - public void testListContainers() throws Exception { - for (String regionId : swiftContext.getApi().getConfiguredRegions()) { - AccountApi api = swiftContext.getApi().getAccountApiForRegion(regionId); - Set response = api.listContainers(); - assertNotNull(response); - for (ContainerMetadata container : response) { - assertNotNull(container.getName()); - assertTrue(container.getCount() >= 0); - assertTrue(container.getBytes() >= 0); - } - } - } } diff --git a/labs/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/features/ContainerApiExpectTest.java b/labs/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/features/ContainerApiExpectTest.java index 0982343a51..eec3a43d2e 100644 --- a/labs/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/features/ContainerApiExpectTest.java +++ b/labs/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/features/ContainerApiExpectTest.java @@ -18,14 +18,59 @@ */ package org.jclouds.openstack.swift.v1.features; +import static org.testng.Assert.assertEquals; + +import org.jclouds.http.HttpRequest; +import org.jclouds.http.HttpResponse; +import org.jclouds.openstack.swift.v1.SwiftApi; import org.jclouds.openstack.swift.v1.internal.BaseSwiftApiExpectTest; +import org.jclouds.openstack.swift.v1.parse.ParseContainerListTest; import org.testng.annotations.Test; +import com.google.common.collect.ImmutableSet; + /** * * @author Adrian Cole */ @Test(groups = "unit", testName = "ContainerAsyncApiTest") public class ContainerApiExpectTest extends BaseSwiftApiExpectTest { + public void testListContainersWhenResponseIs2xx() throws Exception { + + HttpRequest list = HttpRequest + .builder() + .method("GET") + .endpoint("https://objects.jclouds.org/v1.0/40806637803162/?format=json") + .addHeader("Accept", "application/json") + .addHeader("X-Auth-Token", authToken).build(); + + HttpResponse listResponse = HttpResponse.builder().statusCode(200) + .payload(payloadFromResource("/container_list.json")).build(); + + SwiftApi apiWhenContainersExist = requestsSendResponses(keystoneAuthWithUsernameAndPassword, + responseWithKeystoneAccess, list, listResponse); + + assertEquals( + apiWhenContainersExist.getContainerApiForRegion("region-a.geo-1").list() + .toString(), new ParseContainerListTest().expected().toString()); + } + + public void testListContainersWhenResponseIs404() throws Exception { + HttpRequest list = HttpRequest + .builder() + .method("GET") + .endpoint("https://objects.jclouds.org/v1.0/40806637803162/?format=json") + .addHeader("Accept", "application/json") + .addHeader("X-Auth-Token", authToken).build(); + + HttpResponse listResponse = HttpResponse.builder().statusCode(404).build(); + + SwiftApi apiWhenNoContainersExist = requestsSendResponses(keystoneAuthWithUsernameAndPassword, + responseWithKeystoneAccess, list, listResponse); + + assertEquals(apiWhenNoContainersExist.getContainerApiForRegion("region-a.geo-1").list().toImmutableSet(), + ImmutableSet.of()); + + } } diff --git a/labs/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/features/ContainerApiLiveTest.java b/labs/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/features/ContainerApiLiveTest.java index 909e8bdefc..031ef21dab 100644 --- a/labs/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/features/ContainerApiLiveTest.java +++ b/labs/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/features/ContainerApiLiveTest.java @@ -18,9 +18,15 @@ */ package org.jclouds.openstack.swift.v1.features; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertTrue; + +import org.jclouds.openstack.swift.v1.domain.Container; import org.jclouds.openstack.swift.v1.internal.BaseSwiftApiLiveTest; import org.testng.annotations.Test; +import com.google.common.collect.FluentIterable; + /** * * @author Adrian Cole @@ -28,4 +34,17 @@ import org.testng.annotations.Test; @Test(groups = "live", testName = "ContainerApiLiveTest") public class ContainerApiLiveTest extends BaseSwiftApiLiveTest { + @Test + public void testListContainers() throws Exception { + for (String regionId : swiftContext.getApi().getConfiguredRegions()) { + ContainerApi api = swiftContext.getApi().getContainerApiForRegion(regionId); + FluentIterable response = api.list(); + assertNotNull(response); + for (Container container : response) { + assertNotNull(container.getName()); + assertTrue(container.getCount() >= 0); + assertTrue(container.getBytes() >= 0); + } + } + } } diff --git a/labs/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/options/ListContainersOptionsTest.java b/labs/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/options/ListContainersOptionsTest.java index 64b207034b..2461cd3cda 100644 --- a/labs/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/options/ListContainersOptionsTest.java +++ b/labs/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/options/ListContainersOptionsTest.java @@ -22,7 +22,7 @@ import static org.jclouds.openstack.swift.v1.options.ListContainersOptions.Build import static org.jclouds.openstack.swift.v1.options.ListContainersOptions.Builder.marker; import static org.testng.Assert.assertEquals; -import java.util.Collections; +import com.google.common.collect.ImmutableList; import org.jclouds.http.options.HttpRequestOptions; import org.testng.annotations.Test; @@ -50,19 +50,19 @@ public class ListContainersOptionsTest { public void testMarker() { ListContainersOptions options = new ListContainersOptions(); options.marker("test"); - assertEquals(options.buildQueryParameters().get("marker"), Collections.singletonList("test")); + assertEquals(options.buildQueryParameters().get("marker"), ImmutableList.of("test")); } @Test public void testNullMarker() { ListContainersOptions options = new ListContainersOptions(); - assertEquals(options.buildQueryParameters().get("marker"), Collections.EMPTY_LIST); + assertEquals(options.buildQueryParameters().get("marker"), ImmutableList.of()); } @Test public void testMarkerStatic() { ListContainersOptions options = marker("test"); - assertEquals(options.buildQueryParameters().get("marker"), Collections.singletonList("test")); + assertEquals(options.buildQueryParameters().get("marker"), ImmutableList.of("test")); } @Test(expectedExceptions = NullPointerException.class) @@ -74,19 +74,19 @@ public class ListContainersOptionsTest { public void testLimit() { ListContainersOptions options = new ListContainersOptions(); options.limit(1000); - assertEquals(options.buildQueryParameters().get("limit"), Collections.singletonList("1000")); + assertEquals(options.buildQueryParameters().get("limit"), ImmutableList.of("1000")); } @Test public void testNullLimit() { ListContainersOptions options = new ListContainersOptions(); - assertEquals(options.buildQueryParameters().get("limit"), Collections.EMPTY_LIST); + assertEquals(options.buildQueryParameters().get("limit"), ImmutableList.of()); } @Test public void testLimitStatic() { ListContainersOptions options = limit(1000); - assertEquals(options.buildQueryParameters().get("limit"), Collections.singletonList("1000")); + assertEquals(options.buildQueryParameters().get("limit"), ImmutableList.of("1000")); } @Test(expectedExceptions = IllegalStateException.class) diff --git a/labs/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/parse/ParseContainerListTest.java b/labs/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/parse/ParseContainerListTest.java index 3c583121c4..7cc36c3aab 100644 --- a/labs/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/parse/ParseContainerListTest.java +++ b/labs/openstack-swift/src/test/java/org/jclouds/openstack/swift/v1/parse/ParseContainerListTest.java @@ -24,7 +24,7 @@ import javax.ws.rs.Consumes; import javax.ws.rs.core.MediaType; import org.jclouds.json.BaseSetParserTest; -import org.jclouds.openstack.swift.v1.domain.ContainerMetadata; +import org.jclouds.openstack.swift.v1.domain.Container; import org.testng.annotations.Test; import com.google.common.collect.ImmutableSet; @@ -34,7 +34,7 @@ import com.google.common.collect.ImmutableSet; * @author Adrian Cole */ @Test(groups = "unit", testName = "ParseContainerListTest") -public class ParseContainerListTest extends BaseSetParserTest { +public class ParseContainerListTest extends BaseSetParserTest { @Override public String resource() { @@ -43,14 +43,14 @@ public class ParseContainerListTest extends BaseSetParserTest @Override @Consumes(MediaType.APPLICATION_JSON) - public Set expected() { + public Set expected() { return ImmutableSet - .of(ContainerMetadata.builder() + .of(Container.builder() .name("test_container_1") .count(2) .bytes(78) .build(), - ContainerMetadata.builder() + Container.builder() .name("test_container_2") .count(1) .bytes(17) diff --git a/labs/opsource-servers/pom.xml b/labs/opsource-servers/pom.xml index 71011b0d7a..dac1ffd579 100644 --- a/labs/opsource-servers/pom.xml +++ b/labs/opsource-servers/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.labs diff --git a/labs/pom.xml b/labs/pom.xml index 5a445e29e9..ecd833cf74 100644 --- a/labs/pom.xml +++ b/labs/pom.xml @@ -24,7 +24,7 @@ jclouds-project org.jclouds - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../project/pom.xml org.jclouds.labs @@ -34,7 +34,6 @@ virtualbox vcloud-director - glesys opsource-servers elb aws-elb @@ -61,6 +60,6 @@ fgcp fgcp-au fgcp-de - sqs + abiquo diff --git a/labs/rds/pom.xml b/labs/rds/pom.xml index 822518f760..251c0e1c01 100644 --- a/labs/rds/pom.xml +++ b/labs/rds/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.labs diff --git a/labs/savvis-symphonyvpdc/pom.xml b/labs/savvis-symphonyvpdc/pom.xml index c69a761d1c..60abab2f72 100644 --- a/labs/savvis-symphonyvpdc/pom.xml +++ b/labs/savvis-symphonyvpdc/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider diff --git a/labs/savvis-symphonyvpdc/src/test/java/org/jclouds/savvis/vpdc/features/BrowsingAsyncApiTest.java b/labs/savvis-symphonyvpdc/src/test/java/org/jclouds/savvis/vpdc/features/BrowsingAsyncApiTest.java index 0aa9a1b050..b55ab503ea 100644 --- a/labs/savvis-symphonyvpdc/src/test/java/org/jclouds/savvis/vpdc/features/BrowsingAsyncApiTest.java +++ b/labs/savvis-symphonyvpdc/src/test/java/org/jclouds/savvis/vpdc/features/BrowsingAsyncApiTest.java @@ -42,7 +42,7 @@ import com.google.inject.TypeLiteral; * * @author Adrian Cole */ -@Test(groups = "unit") +@Test(groups = "unit", testName = "BrowsingAsyncApiTest") public class BrowsingAsyncApiTest extends BaseVPDCAsyncApiTest { public void testOrg() throws SecurityException, NoSuchMethodException, IOException { diff --git a/labs/smartos-ssh/pom.xml b/labs/smartos-ssh/pom.xml index c93ed79778..aca2ce1150 100644 --- a/labs/smartos-ssh/pom.xml +++ b/labs/smartos-ssh/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.labs diff --git a/labs/sqs/src/main/java/org/jclouds/sqs/SQSApi.java b/labs/sqs/src/main/java/org/jclouds/sqs/SQSApi.java deleted file mode 100644 index b164c8bc7c..0000000000 --- a/labs/sqs/src/main/java/org/jclouds/sqs/SQSApi.java +++ /dev/null @@ -1,157 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.sqs; - -import java.net.URI; -import java.util.Set; -import java.util.concurrent.TimeUnit; - -import org.jclouds.concurrent.Timeout; -import org.jclouds.javax.annotation.Nullable; -import org.jclouds.sqs.domain.Message; -import org.jclouds.sqs.domain.MessageIdAndMD5; -import org.jclouds.sqs.options.CreateQueueOptions; -import org.jclouds.sqs.options.ListQueuesOptions; -import org.jclouds.sqs.options.ReceiveMessageOptions; -import org.jclouds.sqs.options.SendMessageOptions; - -/** - * Provides access to SQS via their REST API. - *

- * - * @see SQSAsyncApi - * @author Adrian Cole - */ -@Timeout(duration = 30, timeUnit = TimeUnit.SECONDS) -public interface SQSApi { - - /** - * The ListQueues action returns a list of your queues. The maximum number of - * queues that can be returned is 1000. If you specify a value for the - * optional QueueNamePrefix parameter, only queues with a name beginning with - * the specified value are returned - * - * @param region - * Queues are Region-specific. - * @param options - * specify prefix or other options - * - * @see - */ - Set listQueuesInRegion(@Nullable String region); - - Set listQueuesInRegion(@Nullable String region, ListQueuesOptions options); - - /** - * - * The CreateQueue action creates a new queue. - *

- * When you request CreateQueue, you provide a name for the queue. To - * successfully create a new queue, you must provide a name that is unique - * within the scope of your own queues. If you provide the name of an - * existing queue, a new queue isn't created and an error isn't returned. - * Instead, the request succeeds and the queue URL for the existing queue is - * returned (for more information about queue URLs, see Queue and Message - * Identifiers in the Amazon SQS Developer Guide). Exception: if you provide - * a value for DefaultVisibilityTimeout that is different from the value for - * the existing queue, you receive an error. - *

Note

- * - * If you delete a queue, you must wait at least 60 seconds before creating a - * queue with the same name. - *

- * A default value for the queue's visibility timeout (30 seconds) is set - * when the queue is created. You can override this value with the - * DefaultVisibilityTimeout request parameter. For more information, see - * Visibility Timeout in the Amazon SQS Developer Guide. - * - * @param region - * Queues are Region-specific. - * @param queueName - * The name to use for the queue created. Constraints: Maximum 80 - * characters; alphanumeric characters, hyphens (-), and - * underscores (_) are allowed. - * @param options - * like the visibility timeout (in seconds) to use for this queue. - */ - URI createQueueInRegion(@Nullable String region, String queueName); - - URI createQueueInRegion(@Nullable String region, String queueName, CreateQueueOptions options); - - /** - * The DeleteQueue action deletes the queue specified by the queue URL, - * regardless of whether the queue is empty. If the specified queue does not - * exist, SQS returns a successful response.

- * Caution

- * - * Use DeleteQueue with care; once you delete your queue, any messages in the - * queue are no longer available. - *

- * When you delete a queue, the deletion process takes up to 60 seconds. - * Requests you send involving that queue during the 60 seconds might - * succeed. For example, a SendMessage request might succeed, but after the - * 60 seconds, the queue and that message you sent no longer exist. Also, - * when you delete a queue, you must wait at least 60 seconds before creating - * a queue with the same name. - *

- * We reserve the right to delete queues that have had no activity for more - * than 30 days. For more information, see About SQS Queues in the Amazon SQS - * Developer Guide. - * - * @param queue - * queue you want to delete - */ - void deleteQueue(URI queue); - - /** - * The SendMessage action delivers a message to the specified queue. The - * maximum allowed message size is 8 KB. - *

- * Important - *

- * The following list shows the characters (in Unicode) allowed in your - * message, according to the W3C XML specification (for more information, go - * to http://www.w3.org/TR/REC-xml/#charsets). If you send any characters not - * included in the list, your request will be rejected. - *

- * #x9 | #xA | #xD | [#x20 to #xD7FF] | [#xE000 to #xFFFD] | [#x10000 to - * #x10FFFF] - * - * @param queue - * queue you want to send to - * - * @param message - * The message to send. Type: String maximum 8 KB in size. For a - * list of allowed characters, see the preceding important note - * @return md5 of the content sent - */ - MessageIdAndMD5 sendMessage(URI queue, String message); - - MessageIdAndMD5 sendMessage(URI queue, String message, SendMessageOptions options); - - Message receiveMessage(URI queue); - - Message receiveMessage(URI queue, ReceiveMessageOptions options); - - Set receiveMessages(URI queue, int max); - - Set receiveMessages(URI queue, int max, ReceiveMessageOptions options); -} diff --git a/labs/sqs/src/main/java/org/jclouds/sqs/SQSAsyncApi.java b/labs/sqs/src/main/java/org/jclouds/sqs/SQSAsyncApi.java deleted file mode 100644 index cdb88d9275..0000000000 --- a/labs/sqs/src/main/java/org/jclouds/sqs/SQSAsyncApi.java +++ /dev/null @@ -1,173 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.sqs; - -import static org.jclouds.sqs.reference.SQSParameters.ACTION; -import static org.jclouds.sqs.reference.SQSParameters.VERSION; - -import java.net.URI; -import java.util.Set; - -import javax.ws.rs.FormParam; -import javax.ws.rs.POST; -import javax.ws.rs.Path; - -import org.jclouds.Constants; -import org.jclouds.aws.filters.FormSigner; -import org.jclouds.javax.annotation.Nullable; -import org.jclouds.location.functions.RegionToEndpointOrProviderIfNull; -import org.jclouds.rest.annotations.EndpointParam; -import org.jclouds.rest.annotations.FormParams; -import org.jclouds.rest.annotations.RequestFilters; -import org.jclouds.rest.annotations.ResponseParser; -import org.jclouds.rest.annotations.VirtualHost; -import org.jclouds.rest.annotations.XMLResponseParser; -import org.jclouds.sqs.domain.Message; -import org.jclouds.sqs.domain.MessageIdAndMD5; -import org.jclouds.sqs.options.CreateQueueOptions; -import org.jclouds.sqs.options.ListQueuesOptions; -import org.jclouds.sqs.options.ReceiveMessageOptions; -import org.jclouds.sqs.options.SendMessageOptions; -import org.jclouds.sqs.xml.MessageHandler; -import org.jclouds.sqs.xml.ReceiveMessageResponseHandler; -import org.jclouds.sqs.xml.RegexListQueuesResponseHandler; -import org.jclouds.sqs.xml.RegexMessageIdAndMD5Handler; -import org.jclouds.sqs.xml.RegexQueueHandler; - -import com.google.common.util.concurrent.ListenableFuture; - -/** - * Provides access to SQS via their REST API. - *

- * - * @author Adrian Cole - */ -@RequestFilters(FormSigner.class) -@FormParams(keys = VERSION, values = "{" + Constants.PROPERTY_API_VERSION + "}") -@VirtualHost -public interface SQSAsyncApi { - - /** - * @see SQSApi#listQueuesInRegion - */ - @POST - @Path("/") - @FormParams(keys = ACTION, values = "ListQueues") - @ResponseParser(RegexListQueuesResponseHandler.class) - ListenableFuture> listQueuesInRegion( - @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region); - - /** - * @see SQSApi#listQueuesInRegion - */ - @POST - @Path("/") - @FormParams(keys = ACTION, values = "ListQueues") - @ResponseParser(RegexListQueuesResponseHandler.class) - ListenableFuture> listQueuesInRegion( - @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region, - ListQueuesOptions options); - - /** - * @see SQSApi#createQueueInRegion - */ - @POST - @Path("/") - @FormParams(keys = ACTION, values = "CreateQueue") - @ResponseParser(RegexQueueHandler.class) - ListenableFuture createQueueInRegion( - @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region, - @FormParam("QueueName") String queueName); - - /** - * @see SQSApi#createQueueInRegion - */ - @POST - @Path("/") - @FormParams(keys = ACTION, values = "CreateQueue") - @ResponseParser(RegexQueueHandler.class) - ListenableFuture createQueueInRegion( - @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @Nullable String region, - @FormParam("QueueName") String queueName, CreateQueueOptions options); - - /** - * @see SQSApi#deleteQueue - */ - @POST - @Path("/") - @FormParams(keys = ACTION, values = "DeleteQueue") - ListenableFuture deleteQueue(@EndpointParam URI queue); - - /** - * @see SQSApi#sendMessage - */ - @POST - @Path("/") - @FormParams(keys = ACTION, values = "SendMessage") - @ResponseParser(RegexMessageIdAndMD5Handler.class) - ListenableFuture sendMessage(@EndpointParam URI queue, @FormParam("MessageBody") String message); - - /** - * @see SQSApi#sendMessage - */ - @POST - @Path("/") - @FormParams(keys = ACTION, values = "SendMessage") - @ResponseParser(RegexMessageIdAndMD5Handler.class) - ListenableFuture sendMessage(@EndpointParam URI queue, @FormParam("MessageBody") String message, - SendMessageOptions options); - - /** - * @see SQSApi#receiveMessage - */ - @POST - @Path("/") - @FormParams(keys = ACTION, values = "ReceiveMessage") - @XMLResponseParser(MessageHandler.class) - ListenableFuture receiveMessage(@EndpointParam URI queue); - - /** - * @see SQSApi#receiveMessage - */ - @POST - @Path("/") - @FormParams(keys = ACTION, values = "ReceiveMessage") - @XMLResponseParser(MessageHandler.class) - ListenableFuture receiveMessage(@EndpointParam URI queue, ReceiveMessageOptions options); - - /** - * @see SQSApi#receiveMessages - */ - @POST - @Path("/") - @FormParams(keys = ACTION, values = "ReceiveMessage") - @XMLResponseParser(ReceiveMessageResponseHandler.class) - ListenableFuture> receiveMessages(@EndpointParam URI queue, @FormParam("MaxNumberOfMessages") int max); - - /** - * @see SQSApi#receiveMessages - */ - @POST - @Path("/") - @FormParams(keys = ACTION, values = "ReceiveMessage") - @XMLResponseParser(ReceiveMessageResponseHandler.class) - ListenableFuture> receiveMessages(@EndpointParam URI queue, @FormParam("MaxNumberOfMessages") int max, - ReceiveMessageOptions options); - -} diff --git a/labs/sqs/src/test/java/org/jclouds/sqs/SQSApiExpectTest.java b/labs/sqs/src/test/java/org/jclouds/sqs/SQSApiExpectTest.java deleted file mode 100644 index 10b636ff14..0000000000 --- a/labs/sqs/src/test/java/org/jclouds/sqs/SQSApiExpectTest.java +++ /dev/null @@ -1,113 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.sqs; - -import static org.testng.Assert.assertEquals; - -import java.net.URI; - -import org.jclouds.http.HttpRequest; -import org.jclouds.http.HttpResponse; -import org.jclouds.sqs.internal.BaseSQSApiExpectTest; -import org.jclouds.sqs.parse.ReceiveMessageResponseTest; -import org.jclouds.sqs.parse.SendMessageResponseTest; -import org.testng.annotations.Test; - -import com.google.common.collect.Iterables; - -/** - * @author Adrian Cole - */ -@Test(groups = "unit", testName = "SQSApiExpectTest") -public class SQSApiExpectTest extends BaseSQSApiExpectTest { - - HttpRequest sendMessage = HttpRequest.builder() - .method("POST") - .endpoint("https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/") - .addHeader("Host", "sqs.us-east-1.amazonaws.com") - .addFormParam("Action", "SendMessage") - .addFormParam("MessageBody", "hardyharhar") - .addFormParam("Signature", "PVzszzgIcT1xt9%2BEzGzWB2Bt8zDadBc48HsgF89AoJE%3D") - .addFormParam("SignatureMethod", "HmacSHA256") - .addFormParam("SignatureVersion", "2") - .addFormParam("Timestamp", "2009-11-08T15%3A54%3A08.897Z") - .addFormParam("Version", "2011-10-01") - .addFormParam("AWSAccessKeyId", "identity").build(); - - public void testSendMessageWhenResponseIs2xx() throws Exception { - - HttpResponse sendMessageResponse = HttpResponse.builder().statusCode(200) - .payload(payloadFromResourceWithContentType("/send_message.xml", "text/xml")).build(); - - SQSApi apiWhenExist = requestSendsResponse(sendMessage, sendMessageResponse); - - assertEquals(apiWhenExist.sendMessage(URI.create("https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/"), "hardyharhar").toString(), new SendMessageResponseTest().expected().toString()); - } - - - HttpRequest receiveMessage = HttpRequest.builder() - .method("POST") - .endpoint("https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/") - .addHeader("Host", "sqs.us-east-1.amazonaws.com") - .addFormParam("Action", "ReceiveMessage") - .addFormParam("Signature", "UURXsAjggoaz5P1h2EFswRd8Ji9euHmXhHvrAmIqM1E%3D") - .addFormParam("SignatureMethod", "HmacSHA256") - .addFormParam("SignatureVersion", "2") - .addFormParam("Timestamp", "2009-11-08T15%3A54%3A08.897Z") - .addFormParam("Version", "2011-10-01") - .addFormParam("AWSAccessKeyId", "identity").build(); - - public void testReceiveMessageWhenResponseIs2xx() throws Exception { - - HttpResponse receiveMessageResponse = HttpResponse.builder().statusCode(200) - .payload(payloadFromResourceWithContentType("/messages.xml", "text/xml")).build(); - - SQSApi apiWhenExist = requestSendsResponse(receiveMessage, receiveMessageResponse); - - assertEquals( - apiWhenExist.receiveMessage(URI.create("https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/")) - .toString(), Iterables.get(new ReceiveMessageResponseTest().expected(), 0).toString()); - } - - - HttpRequest receiveMessages = HttpRequest.builder() - .method("POST") - .endpoint("https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/") - .addHeader("Host", "sqs.us-east-1.amazonaws.com") - .addFormParam("Action", "ReceiveMessage") - .addFormParam("MaxNumberOfMessages", "10") - .addFormParam("Signature", "pZ9B4%2BTBvQA4n0joP4t8ue5x0xmKMd9prpVLVoT%2F7qU%3D") - .addFormParam("SignatureMethod", "HmacSHA256") - .addFormParam("SignatureVersion", "2") - .addFormParam("Timestamp", "2009-11-08T15%3A54%3A08.897Z") - .addFormParam("Version", "2011-10-01") - .addFormParam("AWSAccessKeyId", "identity").build(); - - public void testReceiveMessagesWhenResponseIs2xx() throws Exception { - - HttpResponse receiveMessagesResponse = HttpResponse.builder().statusCode(200) - .payload(payloadFromResourceWithContentType("/messages.xml", "text/xml")).build(); - - SQSApi apiWhenExist = requestSendsResponse(receiveMessages, receiveMessagesResponse); - - assertEquals( - apiWhenExist.receiveMessages(URI.create("https://sqs.us-east-1.amazonaws.com/993194456877/adrian-sqs11/"), 10) - .toString(), new ReceiveMessageResponseTest().expected().toString()); - } -} diff --git a/labs/sqs/src/test/java/org/jclouds/sqs/SQSApiLiveTest.java b/labs/sqs/src/test/java/org/jclouds/sqs/SQSApiLiveTest.java deleted file mode 100644 index eddb8356f8..0000000000 --- a/labs/sqs/src/test/java/org/jclouds/sqs/SQSApiLiveTest.java +++ /dev/null @@ -1,137 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.sqs; - -import static org.jclouds.sqs.options.ListQueuesOptions.Builder.queuePrefix; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertTrue; - -import java.net.URI; -import java.util.Set; -import java.util.SortedSet; - -import org.jclouds.aws.AWSResponseException; -import org.jclouds.sqs.internal.BaseSQSApiLiveTest; -import org.jclouds.sqs.options.ReceiveMessageOptions; -import org.testng.annotations.AfterTest; -import org.testng.annotations.Test; - -import com.google.common.base.Charsets; -import com.google.common.collect.Iterables; -import com.google.common.collect.Sets; -import com.google.common.hash.HashCode; -import com.google.common.hash.Hashing; - -/** - * Tests behavior of {@code SQSApi} - * - * @author Adrian Cole - */ -@Test(groups = "live", singleThreaded = true, testName = "SQSApiLiveTest") -public class SQSApiLiveTest extends BaseSQSApiLiveTest { - - private Set queues = Sets.newHashSet(); - - @Test - protected void testListQueues() throws InterruptedException { - listQueuesInRegion(null); - } - - protected void listQueuesInRegion(String region) throws InterruptedException { - SortedSet allResults = Sets.newTreeSet(context.getApi().listQueuesInRegion(region)); - assertNotNull(allResults); - if (allResults.size() >= 1) { - URI queue = allResults.last(); - assertQueueInList(region, queue); - } - } - - public static final String PREFIX = System.getProperty("user.name") + "-sqs"; - - @Test - protected void testCreateQueue() throws InterruptedException { - createQueueInRegion(null, PREFIX + "1"); - } - - public String createQueueInRegion(final String region, String queueName) throws InterruptedException { - try { - Set result = context.getApi().listQueuesInRegion(region, queuePrefix(queueName)); - if (result.size() >= 1) { - context.getApi().deleteQueue(Iterables.getLast(result)); - queueName += 1;// cannot recreate a queue within 60 seconds - } - } catch (Exception e) { - - } - URI queue = null; - int tries = 0; - while (queue == null && tries < 5) { - try { - tries++; - queue = context.getApi().createQueueInRegion(region, queueName); - } catch (AWSResponseException e) { - queueName += "1"; - if (e.getError().getCode().equals("AWS.SimpleQueueService.QueueDeletedRecently"))// TODO - // retry - // handler - continue; - throw e; - } - } - assertQueueInList(region, queue); - queues.add(queue); - return queueName; - } - - String message = "hardyharhar"; - HashCode md5 = Hashing.md5().hashString(message, Charsets.UTF_8); - - @Test(dependsOnMethods = "testCreateQueue") - protected void testSendMessage() { - for (URI queue : queues) { - assertEquals(context.getApi().sendMessage(queue, message).getMD5(), md5); - } - } - - @Test(dependsOnMethods = "testSendMessage") - protected void testReceiveMessage() { - for (URI queue : queues) { - assertEquals(context.getApi().receiveMessage(queue, ReceiveMessageOptions.Builder.attribute("All")).getMD5(), - md5); - } - } - - private void assertQueueInList(final String region, URI queue) throws InterruptedException { - final URI finalQ = queue; - assertEventually(new Runnable() { - public void run() { - Set result = context.getApi().listQueuesInRegion(region); - assertNotNull(result); - assert result.size() >= 1 : result; - assertTrue(result.contains(finalQ), finalQ + " not in " + result); - } - }); - } - - @AfterTest - public void shutdown() { - context.close(); - } -} diff --git a/labs/sqs/src/test/java/org/jclouds/sqs/internal/BaseSQSApiLiveTest.java b/labs/sqs/src/test/java/org/jclouds/sqs/internal/BaseSQSApiLiveTest.java deleted file mode 100644 index 1d0b35e2fa..0000000000 --- a/labs/sqs/src/test/java/org/jclouds/sqs/internal/BaseSQSApiLiveTest.java +++ /dev/null @@ -1,71 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.sqs.internal; - -import org.jclouds.apis.BaseContextLiveTest; -import org.jclouds.rest.RestContext; -import org.jclouds.sqs.SQSApi; -import org.jclouds.sqs.SQSApiMetadata; -import org.jclouds.sqs.SQSAsyncApi; -import org.testng.annotations.Test; - -import com.google.common.reflect.TypeToken; - -/** - * - * @author Adrian Cole - */ -@Test(groups = "live") -public class BaseSQSApiLiveTest extends BaseContextLiveTest> { - - public BaseSQSApiLiveTest() { - provider = "sqs"; - } - - @Override - protected TypeToken> contextType() { - return SQSApiMetadata.CONTEXT_TOKEN; - } - - private static final int INCONSISTENCY_WINDOW = 10000; - - /** - * Due to eventual consistency, container commands may not return correctly - * immediately. Hence, we will try up to the inconsistency window to see if - * the assertion completes. - */ - protected static void assertEventually(Runnable assertion) throws InterruptedException { - long start = System.currentTimeMillis(); - AssertionError error = null; - for (int i = 0; i < 30; i++) { - try { - assertion.run(); - if (i > 0) - System.err.printf("%d attempts and %dms asserting %s%n", i + 1, System.currentTimeMillis() - start, - assertion.getClass().getSimpleName()); - return; - } catch (AssertionError e) { - error = e; - } - Thread.sleep(INCONSISTENCY_WINDOW / 30); - } - if (error != null) - throw error; - } -} diff --git a/labs/vcloud-director/pom.xml b/labs/vcloud-director/pom.xml index 0971f57635..3eae6abf93 100644 --- a/labs/vcloud-director/pom.xml +++ b/labs/vcloud-director/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.labs diff --git a/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/binders/BindUserOrgAndPasswordAsBasicAuthorizationHeader.java b/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/binders/BindUserOrgAndPasswordAsBasicAuthorizationHeader.java index 039fbad3a5..538b8395c8 100644 --- a/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/binders/BindUserOrgAndPasswordAsBasicAuthorizationHeader.java +++ b/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/binders/BindUserOrgAndPasswordAsBasicAuthorizationHeader.java @@ -20,7 +20,6 @@ package org.jclouds.vcloud.director.v1_5.binders; import static com.google.common.base.Preconditions.checkNotNull; -import java.io.UnsupportedEncodingException; import java.util.Map; import javax.inject.Singleton; @@ -30,6 +29,7 @@ import org.jclouds.crypto.CryptoStreams; import org.jclouds.http.HttpRequest; import org.jclouds.rest.MapBinder; +import com.google.common.base.Charsets; import com.google.common.base.Throwables; /** @@ -45,15 +45,11 @@ public class BindUserOrgAndPasswordAsBasicAuthorizationHeader implements MapBind @SuppressWarnings("unchecked") @Override public R bindToRequest(R request, Map postParams) { - try { - String header = "Basic " - + CryptoStreams.base64(String.format("%s@%s:%s", checkNotNull(postParams.get("user"), "user"), - checkNotNull(postParams.get("org"), "org"), - checkNotNull(postParams.get("password"), "password")).getBytes("UTF-8")); - return (R) request.toBuilder().replaceHeader(HttpHeaders.AUTHORIZATION, header).build(); - } catch (UnsupportedEncodingException e) { - throw Throwables.propagate(e); - } + String header = "Basic " + + CryptoStreams.base64(String.format("%s@%s:%s", checkNotNull(postParams.get("user"), "user"), + checkNotNull(postParams.get("org"), "org"), + checkNotNull(postParams.get("password"), "password")).getBytes(Charsets.UTF_8)); + return (R) request.toBuilder().replaceHeader(HttpHeaders.AUTHORIZATION, header).build(); } @Override diff --git a/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/domain/AbstractVAppType.java b/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/domain/AbstractVAppType.java index 356118c13a..12e6dd5262 100644 --- a/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/domain/AbstractVAppType.java +++ b/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/domain/AbstractVAppType.java @@ -21,7 +21,6 @@ package org.jclouds.vcloud.director.v1_5.domain; import static com.google.common.base.Objects.equal; import static com.google.common.base.Preconditions.checkNotNull; -import java.util.Collections; import java.util.Set; import javax.xml.bind.annotation.XmlAttribute; @@ -201,7 +200,7 @@ public abstract class AbstractVAppType extends ResourceEntity { * */ public Set getSections() { - return sections != null ? ImmutableSet.copyOf(sections) : Collections.emptySet(); + return sections != null ? ImmutableSet.copyOf(sections) : ImmutableSet.of(); } /** diff --git a/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/domain/ProductSectionList.java b/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/domain/ProductSectionList.java index 52df0dd820..96e8737fb5 100644 --- a/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/domain/ProductSectionList.java +++ b/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/domain/ProductSectionList.java @@ -22,7 +22,6 @@ import static com.google.common.base.Objects.equal; import static com.google.common.base.Preconditions.checkNotNull; import java.util.Collection; -import java.util.Collections; import java.util.Iterator; import java.util.Set; @@ -118,7 +117,7 @@ public class ProductSectionList extends Resource implements Set * Gets the value of the productSection property. */ public Set getProductSections() { - return productSections != null ? ImmutableSet.copyOf(productSections) : Collections.emptySet(); + return productSections != null ? ImmutableSet.copyOf(productSections) : ImmutableSet.of(); } @Override diff --git a/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/domain/Resource.java b/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/domain/Resource.java index 521c30dc81..534b902686 100644 --- a/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/domain/Resource.java +++ b/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/domain/Resource.java @@ -131,7 +131,7 @@ public class Resource { protected Resource(Builder builder) { this.href = builder.href; this.type = builder.type; - this.links = builder.links == null ? Collections.emptySet() : builder.links; + this.links = builder.links == null ? ImmutableSet.of() : builder.links; } protected Resource() { diff --git a/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/domain/VAppTemplate.java b/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/domain/VAppTemplate.java index 18a61f5575..c3614e4034 100644 --- a/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/domain/VAppTemplate.java +++ b/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/domain/VAppTemplate.java @@ -21,7 +21,6 @@ package org.jclouds.vcloud.director.v1_5.domain; import static com.google.common.base.Objects.equal; import static com.google.common.base.Preconditions.checkNotNull; -import java.util.Collections; import java.util.Set; import javax.xml.bind.annotation.XmlAttribute; @@ -179,7 +178,7 @@ public class VAppTemplate extends ResourceEntity { protected VAppTemplate(Builder builder) { super(builder); this.owner = builder.owner; - this.children = builder.children.isEmpty() ? Collections.emptySet() : ImmutableSet.copyOf(builder.children); + this.children = builder.children.isEmpty() ? ImmutableSet.of() : ImmutableSet.copyOf(builder.children); this.sections = builder.sections.isEmpty() ? null : ImmutableSet.copyOf(builder.sections); this.vAppScopedLocalId = builder.vAppScopedLocalId; this.ovfDescriptorUploaded = builder.ovfDescriptorUploaded; @@ -229,7 +228,7 @@ public class VAppTemplate extends ResourceEntity { * */ public Set getSections() { - return sections != null ? ImmutableSet.copyOf(sections) : Collections.emptySet(); + return sections != null ? ImmutableSet.copyOf(sections) : ImmutableSet.of(); } /** diff --git a/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/domain/params/CaptureVAppParams.java b/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/domain/params/CaptureVAppParams.java index a9fb259c0b..c76bfec972 100644 --- a/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/domain/params/CaptureVAppParams.java +++ b/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/domain/params/CaptureVAppParams.java @@ -22,7 +22,6 @@ import static com.google.common.base.Objects.equal; import static com.google.common.base.Preconditions.checkNotNull; import java.net.URI; -import java.util.Collections; import java.util.Set; import javax.xml.bind.annotation.XmlElement; @@ -207,7 +206,7 @@ public class CaptureVAppParams extends ParamsType { * */ public Set getSections() { - return sections != null ? ImmutableSet.copyOf(sections) : Collections.emptySet(); + return sections != null ? ImmutableSet.copyOf(sections) : ImmutableSet.of(); } @Override diff --git a/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/domain/params/ControlAccessParams.java b/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/domain/params/ControlAccessParams.java index edf0403572..2e6141a622 100644 --- a/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/domain/params/ControlAccessParams.java +++ b/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/domain/params/ControlAccessParams.java @@ -21,7 +21,6 @@ package org.jclouds.vcloud.director.v1_5.domain.params; import static com.google.common.base.Objects.equal; import static com.google.common.base.Preconditions.checkNotNull; -import java.util.Collections; import java.util.List; import java.util.Set; @@ -170,7 +169,7 @@ public class ControlAccessParams { * Required on create and edit if {@link #isSharedToEveryone()} is false. */ public List getAccessSettings() { - return accessSettings == null ? Collections.emptyList() : accessSettings; + return accessSettings == null ? ImmutableList.of() : accessSettings; } @Override diff --git a/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/domain/params/InstantiationParams.java b/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/domain/params/InstantiationParams.java index 9fed19580d..671aa4c988 100644 --- a/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/domain/params/InstantiationParams.java +++ b/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/domain/params/InstantiationParams.java @@ -21,7 +21,6 @@ package org.jclouds.vcloud.director.v1_5.domain.params; import static com.google.common.base.Objects.equal; import static com.google.common.base.Preconditions.checkNotNull; -import java.util.Collections; import java.util.Set; import javax.xml.bind.annotation.XmlElementRef; @@ -151,7 +150,7 @@ public class InstantiationParams { * */ public Set getSections() { - return sections != null ? ImmutableSet.copyOf(sections) : Collections.emptySet(); + return sections != null ? ImmutableSet.copyOf(sections) : ImmutableSet.of(); } @Override diff --git a/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/functions/ReturnPayloadBytes.java b/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/functions/ReturnPayloadBytes.java index 7e5dcd524b..2696393d3b 100644 --- a/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/functions/ReturnPayloadBytes.java +++ b/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/functions/ReturnPayloadBytes.java @@ -37,7 +37,7 @@ public class ReturnPayloadBytes implements Function { @Override public byte[] apply(HttpResponse from) { try { - return ByteStreams.toByteArray(from.getPayload().getInput()); + return ByteStreams.toByteArray(from.getPayload()); } catch (IOException e) { throw Throwables.propagate(e); } diff --git a/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/handlers/VCloudDirectorErrorHandler.java b/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/handlers/VCloudDirectorErrorHandler.java index 49c936c914..0bb65c663b 100644 --- a/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/handlers/VCloudDirectorErrorHandler.java +++ b/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/handlers/VCloudDirectorErrorHandler.java @@ -20,6 +20,7 @@ package org.jclouds.vcloud.director.v1_5.handlers; import static org.jclouds.http.HttpUtils.closeClientButKeepContentStream; +import java.io.ByteArrayInputStream; import javax.inject.Singleton; import javax.xml.bind.JAXB; @@ -27,7 +28,6 @@ import org.jclouds.http.HttpCommand; import org.jclouds.http.HttpErrorHandler; import org.jclouds.http.HttpResponse; import org.jclouds.http.HttpResponseException; -import org.jclouds.io.InputSuppliers; import org.jclouds.rest.AuthorizationException; import org.jclouds.rest.ResourceNotFoundException; import org.jclouds.vcloud.director.v1_5.VCloudDirectorException; @@ -58,7 +58,7 @@ public class VCloudDirectorErrorHandler implements HttpErrorHandler { // Try to create a VCloudDirectorException from XML payload, if it exists if (response.getPayload() != null && response.getPayload().getContentMetadata().getContentType().startsWith(VCloudDirectorMediaType.ERROR)) { try { - Error error = JAXB.unmarshal(InputSuppliers.of(data).getInput(), Error.class); + Error error = JAXB.unmarshal(new ByteArrayInputStream(data), Error.class); exception = new VCloudDirectorException(error); message = error.getMessage(); } catch (Exception e) { diff --git a/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/internal/VCloudDirectorContextImpl.java b/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/internal/VCloudDirectorContextImpl.java index 6778e5bb92..d2056c779d 100644 --- a/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/internal/VCloudDirectorContextImpl.java +++ b/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/internal/VCloudDirectorContextImpl.java @@ -21,6 +21,7 @@ package org.jclouds.vcloud.director.v1_5.internal; import javax.inject.Inject; import javax.inject.Singleton; +import org.jclouds.annotations.Name; import org.jclouds.lifecycle.Closer; import org.jclouds.providers.ProviderMetadata; import org.jclouds.rest.RestContext; @@ -45,9 +46,9 @@ public class VCloudDirectorContextImpl extends RestContextImpl adminContext; @Inject - VCloudDirectorContextImpl(ProviderMetadata providerMetadata, @Identity String identity, Utils utils, Closer closer, + VCloudDirectorContextImpl(@Name String name, ProviderMetadata providerMetadata, @Identity String identity, Utils utils, Closer closer, Injector injector, RestContext adminContext) { - super(providerMetadata, identity, utils, closer, injector, TypeLiteral.get(VCloudDirectorApi.class), + super(name, providerMetadata, identity, utils, closer, injector, TypeLiteral.get(VCloudDirectorApi.class), TypeLiteral.get(VCloudDirectorAsyncApi.class)); this.adminContext = adminContext; } diff --git a/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/predicates/TaskStatusEquals.java b/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/predicates/TaskStatusEquals.java index 15cf4423f1..62adc85a7f 100644 --- a/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/predicates/TaskStatusEquals.java +++ b/labs/vcloud-director/src/main/java/org/jclouds/vcloud/director/v1_5/predicates/TaskStatusEquals.java @@ -33,6 +33,7 @@ import org.jclouds.vcloud.director.v1_5.domain.Task.Status; import org.jclouds.vcloud.director.v1_5.features.TaskApi; import com.google.common.base.Predicate; +import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; /** @@ -51,7 +52,7 @@ public class TaskStatusEquals implements Predicate { private Collection failingStatuses; public TaskStatusEquals(TaskApi taskApi, Status expectedStatus, Set failingStatuses) { - this(taskApi, Collections.singleton(expectedStatus), failingStatuses); + this(taskApi, ImmutableSet.of(expectedStatus), failingStatuses); } public TaskStatusEquals(TaskApi taskApi, Set expectedStatuses, Set failingStatuses) { diff --git a/labs/vcloud-director/src/test/java/org/jclouds/vcloud/director/v1_5/features/MediaApiLiveTest.java b/labs/vcloud-director/src/test/java/org/jclouds/vcloud/director/v1_5/features/MediaApiLiveTest.java index 6b7af00e2c..31217a249a 100644 --- a/labs/vcloud-director/src/test/java/org/jclouds/vcloud/director/v1_5/features/MediaApiLiveTest.java +++ b/labs/vcloud-director/src/test/java/org/jclouds/vcloud/director/v1_5/features/MediaApiLiveTest.java @@ -44,7 +44,6 @@ import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import java.net.URISyntaxException; -import java.util.Collections; import java.util.Set; import org.jclouds.io.Payloads; @@ -67,6 +66,7 @@ import org.testng.annotations.Test; import com.google.common.base.Predicates; import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; /** @@ -185,7 +185,7 @@ public class MediaApiLiveTest extends BaseVCloudDirectorApiLiveTest { public void testGetMediaOwner() { Owner directOwner = mediaApi.getOwner(media.getId()); assertEquals(owner.toBuilder().user(owner.getUser()).build(), - directOwner.toBuilder().links(Collections. emptySet()).build(), String.format( + directOwner.toBuilder().links(ImmutableSet. of()).build(), String.format( GETTER_RETURNS_SAME_OBJ, "getOwner()", "owner", "media.getOwner()", owner.toString(), directOwner.toString())); diff --git a/labs/vcloud-director/src/test/java/org/jclouds/vcloud/director/v1_5/features/admin/AdminCatalogApiExpectTest.java b/labs/vcloud-director/src/test/java/org/jclouds/vcloud/director/v1_5/features/admin/AdminCatalogApiExpectTest.java index c6af0da41c..4032b3234c 100644 --- a/labs/vcloud-director/src/test/java/org/jclouds/vcloud/director/v1_5/features/admin/AdminCatalogApiExpectTest.java +++ b/labs/vcloud-director/src/test/java/org/jclouds/vcloud/director/v1_5/features/admin/AdminCatalogApiExpectTest.java @@ -50,7 +50,7 @@ import com.google.common.net.HttpHeaders; * * @author grkvlt@apache.org, Adrian Cole */ -@Test(groups = { "unit", "admin" }, singleThreaded = true, testName = "CatalogApiExpectTest") +@Test(groups = { "unit", "admin" }, singleThreaded = true, testName = "AdminCatalogApiExpectTest") public class AdminCatalogApiExpectTest extends VCloudDirectorAdminApiExpectTest { static String catalog = "7212e451-76e1-4631-b2de-ba1dfd8080e4"; diff --git a/labs/vcloud-director/src/test/java/org/jclouds/vcloud/director/v1_5/features/admin/AdminCatalogApiLiveTest.java b/labs/vcloud-director/src/test/java/org/jclouds/vcloud/director/v1_5/features/admin/AdminCatalogApiLiveTest.java index 463d0bdc72..b562471e25 100644 --- a/labs/vcloud-director/src/test/java/org/jclouds/vcloud/director/v1_5/features/admin/AdminCatalogApiLiveTest.java +++ b/labs/vcloud-director/src/test/java/org/jclouds/vcloud/director/v1_5/features/admin/AdminCatalogApiLiveTest.java @@ -28,8 +28,6 @@ import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; -import java.util.Collections; - import org.jclouds.vcloud.director.v1_5.domain.AdminCatalog; import org.jclouds.vcloud.director.v1_5.domain.Checks; import org.jclouds.vcloud.director.v1_5.domain.Link; @@ -44,6 +42,7 @@ import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; +import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; /** @@ -127,7 +126,7 @@ public class AdminCatalogApiLiveTest extends BaseVCloudDirectorApiLiveTest { owner = catalogApi.getOwner(catalog.getId()); Checks.checkOwner(owner); assertTrue( - equal(owner.toBuilder().links(Collections. emptySet()).build(), + equal(owner.toBuilder().links(ImmutableSet. of()).build(), newOwner.toBuilder().user(newOwner.getUser()).build()), String.format(OBJ_FIELD_UPDATABLE, CATALOG, "owner")); } finally { diff --git a/labs/vcloud-director/src/test/java/org/jclouds/vcloud/director/v1_5/features/admin/AdminNetworkApiLiveTest.java b/labs/vcloud-director/src/test/java/org/jclouds/vcloud/director/v1_5/features/admin/AdminNetworkApiLiveTest.java index 8c23d1b786..4f4c24608a 100644 --- a/labs/vcloud-director/src/test/java/org/jclouds/vcloud/director/v1_5/features/admin/AdminNetworkApiLiveTest.java +++ b/labs/vcloud-director/src/test/java/org/jclouds/vcloud/director/v1_5/features/admin/AdminNetworkApiLiveTest.java @@ -26,7 +26,7 @@ import static org.jclouds.vcloud.director.v1_5.VCloudDirectorLiveTestConstants.U import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; -import java.util.Collections; +import com.google.common.collect.ImmutableSet; import org.jclouds.vcloud.director.v1_5.domain.Checks; import org.jclouds.vcloud.director.v1_5.domain.Task; @@ -89,7 +89,7 @@ public class AdminNetworkApiLiveTest extends BaseVCloudDirectorApiLiveTest { OrgNetwork oldNetwork = Network.toSubType(network) .toBuilder() - .tasks(Collections.emptySet()) + .tasks(ImmutableSet.of()) .build(); OrgNetwork editNetwork = getMutatedOrgNetwork(oldNetwork); @@ -153,7 +153,7 @@ public class AdminNetworkApiLiveTest extends BaseVCloudDirectorApiLiveTest { private static OrgNetwork getMutatedOrgNetwork(OrgNetwork network) { OrgNetwork.Builder networkBuilder = OrgNetwork.builder().fromNetwork(network) - .tasks(Collections.emptySet()) + .tasks(ImmutableSet.of()) // .name("new "+network.getName()) .description("new "+network.getDescription()) .configuration(getMutatedNetworkConfiguration(network.getConfiguration())); diff --git a/labs/vcloud-director/src/test/java/org/jclouds/vcloud/director/v1_5/features/admin/UserApiExpectTest.java b/labs/vcloud-director/src/test/java/org/jclouds/vcloud/director/v1_5/features/admin/UserApiExpectTest.java index 4d053506f2..a2d0dcfd5d 100644 --- a/labs/vcloud-director/src/test/java/org/jclouds/vcloud/director/v1_5/features/admin/UserApiExpectTest.java +++ b/labs/vcloud-director/src/test/java/org/jclouds/vcloud/director/v1_5/features/admin/UserApiExpectTest.java @@ -26,7 +26,6 @@ import static org.jclouds.vcloud.director.v1_5.VCloudDirectorMediaType.USER; import static org.testng.Assert.assertEquals; import java.net.URI; -import java.util.Collections; import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpResponse; @@ -39,6 +38,8 @@ import org.jclouds.vcloud.director.v1_5.domain.User; import org.jclouds.vcloud.director.v1_5.internal.VCloudDirectorAdminApiExpectTest; import org.testng.annotations.Test; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableSet; import com.google.common.net.HttpHeaders; /** @@ -251,7 +252,7 @@ public class UserApiExpectTest extends VCloudDirectorAdminApiExpectTest { .href(URI.create("https://vcloudbeta.bluelock.com/api/admin/role/ff1e0c91-1288-3664-82b7-a6fa303af4d1")) .build()) .password("password") - .groups(Collections.emptyList()) + .groups(ImmutableList.of()) .build(); } diff --git a/labs/vcloud-director/src/test/java/org/jclouds/vcloud/director/v1_5/internal/BaseVCloudDirectorApiLiveTest.java b/labs/vcloud-director/src/test/java/org/jclouds/vcloud/director/v1_5/internal/BaseVCloudDirectorApiLiveTest.java index 503b895e71..e61ae31472 100644 --- a/labs/vcloud-director/src/test/java/org/jclouds/vcloud/director/v1_5/internal/BaseVCloudDirectorApiLiveTest.java +++ b/labs/vcloud-director/src/test/java/org/jclouds/vcloud/director/v1_5/internal/BaseVCloudDirectorApiLiveTest.java @@ -46,7 +46,6 @@ import static org.testng.Assert.fail; import java.net.URI; import java.text.SimpleDateFormat; -import java.util.Collections; import java.util.Date; import java.util.Random; import java.util.Set; @@ -602,7 +601,7 @@ public abstract class BaseVCloudDirectorApiLiveTest extends BaseContextLiveTest< protected boolean taskDoneEventually(Task task) { TaskApi taskApi = context.getApi().getTaskApi(); TaskStatusEquals predicate = new TaskStatusEquals(taskApi, ImmutableSet.of(Task.Status.ABORTED, - Task.Status.CANCELED, Task.Status.ERROR, Task.Status.SUCCESS), Collections. emptySet()); + Task.Status.CANCELED, Task.Status.ERROR, Task.Status.SUCCESS), ImmutableSet. of()); RetryablePredicate retryablePredicate = new RetryablePredicate(predicate, LONG_TASK_TIMEOUT_SECONDS * 1000L); return retryablePredicate.apply(task); diff --git a/labs/virtualbox/README.md b/labs/virtualbox/README.md index 9b7e26d86a..b618fa9d92 100644 --- a/labs/virtualbox/README.md +++ b/labs/virtualbox/README.md @@ -1,11 +1,19 @@ #Setup -Have virtualbox 4.1.8 installed. +Have virtualbox 4.1.20r80170 installed. Have an ssh daemon with passwordless login to localhost (i.e. "ssh [me]@localhost" must work without password). +To achieve that, be sure you have your ssh public key (at System.getProperty("user.home") + "/.ssh/id_rsa") in your '.ssh/authorized_keys'. +Please look at [this example]http://www.linuxproblem.org/art_9.html for more details. -That's it! +You can have also specify '-Dvirtualbox.identity' and '-Dvirtualbox.credential' if you want to use a username and password of your local machine. + +In order to make available a preseed file, jclouds-vbox will start a PreseedServer at `http://localhost:23232` that will serve a preseed.cfg file. +Make sure your firewall rules are not blocking this port. +If you need to override this default you can use -Djclouds.virtualbox.preconfigurationurl=http://localhost:PORT/preseed.cfg, with a different PORT. + +That's it! -------------- @@ -17,7 +25,7 @@ Enjoy local cloud goodness by running: > (use 'org.jclouds.compute2) > (import 'org.jclouds.scriptbuilder.statements.login.AdminAccess) -> (def compute (compute-service "virtualbox" "admin" "12345" :sshj :slf4j)) +> (def compute (compute-service "virtualbox" "user" "password" :sshj :slf4j)) > (create-nodes compute "local-cluster" 2 (build-template compute { :run-script (AdminAccess/standard) } )) -------------- @@ -39,8 +47,8 @@ It *should* behave as any other provider, if not please report. - jclouds-vbox is still at alpha stage please report any issues you find. - jclouds-vbox has been mostly tested on Mac OSX, it might work on Linux iff vbox is running and correctly set up, but it won't work on windows for the moment. -- cached isos, vm's and most configs are kept at ~/.jclouds-vbox/ by default. -- jclouds-vbox assumes vbox has the default host-only network vboxnet0, that the network is in 192.168.86.0/255.255.255.0 and that the host has address 1 in this network. +- cached isos, vm's and most configs are kept at ~/.jclouds-vbox/ by default, you can override -Dtest.virtualbox.workingDir=/path/to/your/workingDir. +- jclouds-vbox assumes vbox has the default host-only network vboxnet0, that the network is in 192.168.86.0/255.255.255.0 and that the host has address 1 in this network. -------------- diff --git a/labs/virtualbox/pom.xml b/labs/virtualbox/pom.xml index 820018decf..48281e202b 100644 --- a/labs/virtualbox/pom.xml +++ b/labs/virtualbox/pom.xml @@ -25,7 +25,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.labs @@ -37,12 +37,17 @@ http://localhost:18083/ 4.1.4 - 4.1.8r75467 - administrator - 12345 - imageId=test-ubuntu-11.10-i386,loginUser=toor:password,authenticateSudo=true + 4.1.20r80170 + ${user.name} + CHANGE_ME + osFamily=UBUNTU,osVersionMatches=12.04.1,os64Bit=true,osArchMatches=amd64,loginUser=toor:password,authenticateSudo=true org.jclouds.virtualbox*;version="${project.version}" - org.jclouds*;version="${project.version}",* + + org.jclouds*;version="${project.version}", + org.eclipse.jetty*;version="[7.5,9)", + javax.servlet*;version="[2.5,3)", + * + @@ -110,6 +115,7 @@ org.testng testng 6.3.1 + test snakeyaml @@ -136,6 +142,7 @@ 1 + false ${test.virtualbox.endpoint} ${test.virtualbox.api-version} diff --git a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/VirtualBoxApiMetadata.java b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/VirtualBoxApiMetadata.java index f7c1b7fef9..c65f208341 100644 --- a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/VirtualBoxApiMetadata.java +++ b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/VirtualBoxApiMetadata.java @@ -24,6 +24,8 @@ import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_IMAGE import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_INSTALLATION_KEY_SEQUENCE; import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_PRECONFIGURATION_URL; import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_WORKINGDIR; +import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_GUEST_MEMORY; + import java.io.File; import java.net.URI; @@ -72,16 +74,17 @@ public class VirtualBoxApiMetadata extends BaseApiMetadata { + "initrd=/install/initrd.gz -- "); String workingDir = System.getProperty("test.virtualbox.workingDir", VIRTUALBOX_DEFAULT_DIR); - properties.put(VIRTUALBOX_WORKINGDIR, workingDir); + String ram = System.getProperty(VIRTUALBOX_GUEST_MEMORY, "1024"); + properties.put(VIRTUALBOX_GUEST_MEMORY, ram); + String yamlDescriptor = System.getProperty("test.virtualbox.image.descriptor.yaml", VIRTUALBOX_WORKINGDIR + File.separator + "images.yaml"); properties.put(VIRTUALBOX_IMAGES_DESCRIPTOR, yamlDescriptor); - properties.put(VIRTUALBOX_PRECONFIGURATION_URL, "http://10.0.2.2:23232/preseed.cfg"); - properties.setProperty(TEMPLATE, "osFamily=UBUNTU,osVersionMatches=11.10,os64Bit=true,osArchMatches=x86,loginUser=toor:password,authenticateSudo=true"); + properties.setProperty(TEMPLATE, "osFamily=UBUNTU,osVersionMatches=12.04.1,os64Bit=true,osArchMatches=amd64"); return properties; } @@ -93,8 +96,8 @@ public class VirtualBoxApiMetadata extends BaseApiMetadata { .identityName("User") .credentialName("Password") .documentation(URI.create("https://www.virtualbox.org/sdkref/index.html")) - .defaultIdentity("administrator") - .defaultCredential("12345") + .defaultIdentity(System.getProperty("user.name")) + .defaultCredential("CHANGE_ME") .defaultEndpoint("http://localhost:18083/") .documentation(URI.create("https://github.com/jclouds/jclouds/tree/master/apis/byon")) // later version not in maven, yet diff --git a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/compute/VirtualBoxComputeServiceAdapter.java b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/compute/VirtualBoxComputeServiceAdapter.java index 2bba7189bd..b061582810 100644 --- a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/compute/VirtualBoxComputeServiceAdapter.java +++ b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/compute/VirtualBoxComputeServiceAdapter.java @@ -28,6 +28,7 @@ import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_NODE_ import java.util.Map; import java.util.Set; +import java.util.concurrent.TimeUnit; import javax.annotation.Resource; import javax.inject.Inject; @@ -46,6 +47,7 @@ import org.jclouds.virtualbox.domain.Master; import org.jclouds.virtualbox.domain.NodeSpec; import org.jclouds.virtualbox.domain.YamlImage; import org.jclouds.virtualbox.functions.admin.UnregisterMachineIfExistsAndForceDeleteItsMedia; +import org.jclouds.virtualbox.util.MachineController; import org.virtualbox_4_1.IMachine; import org.virtualbox_4_1.IProgress; import org.virtualbox_4_1.ISession; @@ -62,6 +64,7 @@ import com.google.common.cache.LoadingCache; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Sets; +import com.google.common.util.concurrent.Uninterruptibles; import com.google.inject.Singleton; /** @@ -82,17 +85,20 @@ public class VirtualBoxComputeServiceAdapter implements ComputeServiceAdapter mastersLoader; private final Function> cloneCreator; private final Function imachineToImage; + private final MachineController machineController; @Inject public VirtualBoxComputeServiceAdapter(Supplier manager, Supplier> imagesMapper, LoadingCache mastersLoader, Function> cloneCreator, - Function imachineToImage) { + Function imachineToImage, + MachineController machineController) { this.manager = checkNotNull(manager, "manager"); this.imagesToYamlImages = imagesMapper.get(); this.mastersLoader = mastersLoader; this.cloneCreator = cloneCreator; this.imachineToImage = imachineToImage; + this.machineController = machineController; } @Override @@ -199,7 +205,11 @@ public class VirtualBoxComputeServiceAdapter implements ComputeServiceAdapter nodeSupplier) { - return VirtualBoxManager.createInstance(nodeSupplier.get().getId()); + if(nodeSupplier.get().getId() != null) + return VirtualBoxManager.createInstance(nodeSupplier.get().getId()); + + return VirtualBoxManager.createInstance(""); } @Override @@ -233,4 +236,5 @@ public class VirtualBoxComputeServiceContextModule extends protected Map toPortableImageStatus() { return toPortableImageStatus; } + } diff --git a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/config/VirtualBoxConstants.java b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/config/VirtualBoxConstants.java index 46a6e67ac5..a3f5d8804c 100644 --- a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/config/VirtualBoxConstants.java +++ b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/config/VirtualBoxConstants.java @@ -50,6 +50,8 @@ public interface VirtualBoxConstants { public static final String VIRTUALBOX_MACHINE_CREDENTIAL = "jclouds.virtualbox.credential"; public static final String VIRTUALBOX_MACHINE_LOCATION = "jclouds.virtualbox.location"; + + public static final String VIRTUALBOX_GUEST_MEMORY = "jclouds.virtualbox.guest.memory"; public static final String VIRTUALBOX_HOST_ID = "jclouds.virtualbox.hostid"; @@ -61,5 +63,8 @@ public interface VirtualBoxConstants { + ".jclouds-vbox"; public static final String VIRTUALBOX_PROVIDER = "virtualbox"; - + + public static final String GUEST_OS_PASSWORD = "guestPassword"; + + public static final String GUEST_OS_USER = "guestUser"; } diff --git a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/domain/MasterSpec.java b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/domain/MasterSpec.java index f9b5063b1a..6574a957ea 100644 --- a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/domain/MasterSpec.java +++ b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/domain/MasterSpec.java @@ -21,6 +21,8 @@ package org.jclouds.virtualbox.domain; import static com.google.common.base.Preconditions.checkNotNull; +import org.jclouds.domain.LoginCredentials; + import com.google.common.base.Objects; /** @@ -32,6 +34,7 @@ public class MasterSpec { private VmSpec vmSpec; private IsoSpec isoSpec; private NetworkSpec networkSpec; + private LoginCredentials loginCredentials; public static Builder builder() { return new Builder(); @@ -42,6 +45,7 @@ public class MasterSpec { private VmSpec vmSpec; private IsoSpec isoSpec; private NetworkSpec networkSpec; + private LoginCredentials loginCredentials; public Builder vm(VmSpec vmSpec) { this.vmSpec = vmSpec; @@ -58,19 +62,25 @@ public class MasterSpec { return this; } + public Builder credentials(LoginCredentials loginCredentials) { + this.loginCredentials = loginCredentials; + return this; + } + public MasterSpec build() { - return new MasterSpec(vmSpec, isoSpec, networkSpec); + return new MasterSpec(vmSpec, isoSpec, networkSpec, loginCredentials); } } - private MasterSpec(VmSpec vmSpec, IsoSpec isoSpec, NetworkSpec networkSpec) { + private MasterSpec(VmSpec vmSpec, IsoSpec isoSpec, NetworkSpec networkSpec, LoginCredentials loginCredentials) { checkNotNull(vmSpec, "vmSpec"); checkNotNull(isoSpec, "isoSpec"); checkNotNull(networkSpec, "networkSpec"); this.vmSpec = vmSpec; this.isoSpec = isoSpec; this.networkSpec = networkSpec; + this.loginCredentials = loginCredentials; } public VmSpec getVmSpec() { @@ -84,6 +94,10 @@ public class MasterSpec { public NetworkSpec getNetworkSpec() { return networkSpec; } + + public LoginCredentials getLoginCredentials() { + return loginCredentials; + } @Override public boolean equals(Object o) { diff --git a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/domain/NetworkInterfaceCard.java b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/domain/NetworkInterfaceCard.java index 57f565e802..816626cf13 100644 --- a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/domain/NetworkInterfaceCard.java +++ b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/domain/NetworkInterfaceCard.java @@ -28,12 +28,13 @@ public class NetworkInterfaceCard { private final long slot; private final NetworkAdapter networkAdapter; private final String hostInterfaceName; - + private final boolean enabled; - public NetworkInterfaceCard(long slot, NetworkAdapter networkAdapter, String hostInterfaceName) { + public NetworkInterfaceCard(long slot, NetworkAdapter networkAdapter, String hostInterfaceName, boolean enabled) { this.slot = checkNotNull(slot, "slot"); this.networkAdapter = checkNotNull(networkAdapter, "networkAdapter"); this.hostInterfaceName = hostInterfaceName; + this.enabled = enabled; } public static Builder builder() { @@ -45,6 +46,7 @@ public class NetworkInterfaceCard { private long slot = 0L; private NetworkAdapter networkAdapter; private String hostInterfaceName; + private boolean enabled = true; public Builder slot(long slot) { checkArgument(slot >= 0 && slot < 4, "must be 0, 1, 2, 3: %s", slot); @@ -62,10 +64,16 @@ public class NetworkInterfaceCard { String hostInterfaceName) { this.hostInterfaceName = hostInterfaceName; return this; - } + } + + public Builder enabled( + boolean enabled) { + this.enabled = enabled; + return this; + } public NetworkInterfaceCard build() { - return new NetworkInterfaceCard(slot, networkAdapter, hostInterfaceName); + return new NetworkInterfaceCard(slot, networkAdapter, hostInterfaceName, enabled); } } @@ -79,7 +87,11 @@ public class NetworkInterfaceCard { public String getHostInterfaceName() { return hostInterfaceName; - } + } + + public boolean isEnabled() { + return enabled; + } @Override public boolean equals(Object o) { @@ -89,14 +101,15 @@ public class NetworkInterfaceCard { NetworkInterfaceCard other = (NetworkInterfaceCard) o; return Objects.equal(slot, other.slot) && - Objects.equal(networkAdapter, other.networkAdapter); + Objects.equal(networkAdapter, other.networkAdapter) + && Objects.equal(enabled, other.enabled); } return false; } @Override public int hashCode() { - return Objects.hashCode(slot, networkAdapter); + return Objects.hashCode(slot, networkAdapter, enabled); } @Override @@ -104,6 +117,7 @@ public class NetworkInterfaceCard { return "NetworkInterfaceCard{slot="+ slot + ", networkAdapter=" + networkAdapter + + ", enabled=" + enabled + '}'; } diff --git a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/domain/VmSpec.java b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/domain/VmSpec.java index 102fb76d3e..7ae072600b 100644 --- a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/domain/VmSpec.java +++ b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/domain/VmSpec.java @@ -42,7 +42,7 @@ public class VmSpec { private final Set controllers; private final CleanupMode cleanupMode; - public VmSpec(String vmId, String vmName, String osTypeId, long memory, boolean forceOverwrite, + public VmSpec(String vmId, String vmName, String osTypeId, long memory, String guestUser, String guestPassword, boolean forceOverwrite, Set controllers, CleanupMode cleanupMode) { this.vmId = checkNotNull(vmId, "vmId"); this.vmName = checkNotNull(vmName, "vmName"); @@ -67,6 +67,8 @@ public class VmSpec { private String osTypeId = ""; private boolean forceOverwrite = true; private long memory; + private String guestUser; + private String guestPassword; private CleanupMode cleanUpMode; public Builder controller(StorageController controller) { @@ -103,13 +105,24 @@ public class VmSpec { this.cleanUpMode = cleanupMode; return this; } + + public Builder guestUser(String guestUser) { + this.guestUser = guestUser; + return this; + } + + public Builder guestPassword(String guestPassword) { + this.guestPassword = guestPassword; + return this; + } public VmSpec build() { checkNotNull(name, "name"); checkNotNull(id, "id"); checkArgument(memory > 0, "Memory must be set"); - return new VmSpec(id, name, osTypeId, memory, forceOverwrite, controllers, cleanUpMode); + return new VmSpec(id, name, osTypeId, memory, guestUser, guestPassword, forceOverwrite, controllers, cleanUpMode); } + } public String getVmId() { @@ -162,7 +175,8 @@ public class VmSpec { @Override public String toString() { return "VmSpecification{" + "vmName='" + vmName + '\'' + ", osTypeId='" + osTypeId + '\'' + ", memory='" + memory - + '\'' + ", vmId='" + vmId + '\'' + ", forceOverwrite=" + forceOverwrite + ", controllers=" - + controllers + ", cleanupMode=" + cleanupMode + '}'; + + '\'' + ", vmId='" + vmId + '\'' + '\'' + + ", forceOverwrite=" + forceOverwrite + ", controllers=" + + controllers + ", cleanupMode=" + cleanupMode + '}'; } } diff --git a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/domain/YamlImage.java b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/domain/YamlImage.java index bff48a2632..b3198f846d 100644 --- a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/domain/YamlImage.java +++ b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/domain/YamlImage.java @@ -27,6 +27,7 @@ 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.domain.LoginCredentials; import com.google.common.base.Function; import com.google.common.collect.Lists; @@ -118,6 +119,7 @@ public class YamlImage { public String os_family; public String os_description; public String os_version; + public String iso_md5; public String iso; public String keystroke_sequence; public String preseed_cfg; @@ -136,13 +138,16 @@ public class YamlImage { public Image apply(YamlImage arg0) { if (arg0 == null) return null; + OsFamily family = parseOsFamilyOrUnrecognized(arg0.os_family); OperatingSystem operatingSystem = OperatingSystem.builder().description(arg0.os_description).family(family) .version(arg0.os_version).is64Bit(arg0.os_64bit).arch(arg0.os_arch).build(); return new ImageBuilder().id(arg0.id).name(arg0.name).description(arg0.description) - .operatingSystem(operatingSystem).status(Image.Status.AVAILABLE).build(); + .operatingSystem(operatingSystem).status(Image.Status.AVAILABLE) + .defaultCredentials(new LoginCredentials(arg0.username, arg0.credential, null, true)) + .build(); } }; @@ -154,7 +159,7 @@ public class YamlImage { public String toString() { return "YamlImage [id=" + id + ", name=" + name + ", description=" + description + ", hostname=" + hostname + ", location_id=" + location_id + ", os_arch=" + os_arch + ", os_family=" + os_family - + ", os_description=" + os_description + ", os_version=" + os_version + ", iso=" + iso + + ", os_description=" + os_description + ", os_version=" + os_version + ", iso=" + iso + ", keystroke_sequence=" + keystroke_sequence + ", preseed_cfg=" + preseed_cfg + ", login_port=" + login_port + ", os_64bit=" + os_64bit + ", group=" + group + ", tags=" + tags + ", metadata=" + metadata + ", username=" + username + ", credential=" + credential + ", credential_url=" diff --git a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/AttachBridgedAdapterToMachine.java b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/AttachBridgedAdapterToMachine.java index 323229f70c..aa27c7c405 100644 --- a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/AttachBridgedAdapterToMachine.java +++ b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/AttachBridgedAdapterToMachine.java @@ -46,7 +46,7 @@ public class AttachBridgedAdapterToMachine implements Function { iNetworkAdapter.setAdapterType(Am79C973); iNetworkAdapter.setMACAddress(networkInterfaceCard.getNetworkAdapter().getMacAddress()); iNetworkAdapter.setBridgedInterface(networkInterfaceCard.getHostInterfaceName()); - iNetworkAdapter.setEnabled(true); + iNetworkAdapter.setEnabled(networkInterfaceCard.isEnabled()); machine.saveSettings(); return null; } diff --git a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/AttachHostOnlyAdapter.java b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/AttachHostOnlyAdapter.java index 016b942a9f..9eb16c0ef4 100644 --- a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/AttachHostOnlyAdapter.java +++ b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/AttachHostOnlyAdapter.java @@ -45,7 +45,7 @@ public class AttachHostOnlyAdapter implements Function { iNetworkAdapter.setAdapterType(Am79C973); iNetworkAdapter.setMACAddress(networkInterfaceCard.getNetworkAdapter().getMacAddress()); iNetworkAdapter.setHostOnlyInterface(networkInterfaceCard.getHostInterfaceName()); - iNetworkAdapter.setEnabled(true); + iNetworkAdapter.setEnabled(networkInterfaceCard.isEnabled()); machine.saveSettings(); return null; } diff --git a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/AttachNATAdapterToMachineIfNotAlreadyExists.java b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/AttachNATAdapterToMachineIfNotAlreadyExists.java index 9dddd714ee..d390b14248 100644 --- a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/AttachNATAdapterToMachineIfNotAlreadyExists.java +++ b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/AttachNATAdapterToMachineIfNotAlreadyExists.java @@ -55,7 +55,7 @@ public class AttachNATAdapterToMachineIfNotAlreadyExists implements Function manager; private final String workingDir; private final MachineUtils machineUtils; - + @Inject public CloneAndRegisterMachineFromIMachineIfNotAlreadyExists(Supplier manager, @Named(VirtualBoxConstants.VIRTUALBOX_WORKINGDIR) String workingDir, MachineUtils machineUtils) { @@ -104,15 +107,13 @@ public class CloneAndRegisterMachineFromIMachineIfNotAlreadyExists implements Fu if (isLinkedClone) options.add(CloneOptions.Link); - // TODO snapshot name - ISnapshot currentSnapshot = new TakeSnapshotIfNotAlreadyAttached(manager, "snapshotName", "snapshotDesc", logger) - .apply(master); - - // clone - IProgress progress = currentSnapshot.getMachine().cloneTo(clonedMachine, CloneMode.MachineState, options); - + ISnapshot currentSnapshot = new TakeSnapshotIfNotAlreadyAttached(manager, + "snapshotName", "snapshotDesc", logger).apply(master); + IProgress progress = currentSnapshot.getMachine().cloneTo(clonedMachine, + CloneMode.MachineState, options); progress.waitForCompletion(-1); - logger.debug(String.format("Machine %s is cloned correctly", clonedMachine.getName())); + logger.debug(String.format("Machine %s is cloned correctly", + clonedMachine.getName())); // memory may not be the same as the master vm clonedMachine.setMemorySize(cloneSpec.getVmSpec().getMemory()); @@ -124,6 +125,13 @@ public class CloneAndRegisterMachineFromIMachineIfNotAlreadyExists implements Fu for (NetworkInterfaceCard networkInterfaceCard : networkSpec.getNetworkInterfaceCards()) { new AttachNicToMachine(vmSpec.getVmName(), machineUtils).apply(networkInterfaceCard); } + + // set only once the creds for this machine, same coming from its master + logger.debug(">> storing guest credentials on vm %s as extra data", clonedMachine.getName()); + String masterUsername = master.getExtraData(GUEST_OS_USER); + String masterPassword = master.getExtraData(GUEST_OS_PASSWORD); + clonedMachine.setExtraData(GUEST_OS_USER, masterUsername); + clonedMachine.setExtraData(GUEST_OS_PASSWORD, masterPassword); return clonedMachine; } diff --git a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/CreateAndInstallVm.java b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/CreateAndInstallVm.java index b359cd47ff..19535d0d6f 100644 --- a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/CreateAndInstallVm.java +++ b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/CreateAndInstallVm.java @@ -21,9 +21,12 @@ package org.jclouds.virtualbox.functions; import static com.google.common.base.Preconditions.checkState; import static com.google.common.collect.Iterables.transform; import static org.jclouds.scriptbuilder.domain.Statements.call; +import static org.jclouds.virtualbox.config.VirtualBoxConstants.GUEST_OS_PASSWORD; +import static org.jclouds.virtualbox.config.VirtualBoxConstants.GUEST_OS_USER; import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_PRECONFIGURATION_URL; import java.util.List; +import java.util.concurrent.TimeUnit; import javax.annotation.Resource; import javax.inject.Named; @@ -42,15 +45,17 @@ import org.jclouds.virtualbox.domain.VmSpec; import org.jclouds.virtualbox.statements.InstallGuestAdditions; import org.jclouds.virtualbox.util.MachineController; import org.jclouds.virtualbox.util.MachineUtils; +import org.virtualbox_4_1.DeviceType; import org.virtualbox_4_1.IMachine; +import org.virtualbox_4_1.IMediumAttachment; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.base.Splitter; -import com.google.common.base.Throwables; import com.google.common.collect.Iterables; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; +import com.google.common.util.concurrent.Uninterruptibles; import com.google.inject.Inject; @Singleton @@ -68,7 +73,7 @@ public class CreateAndInstallVm implements Function { private final MachineController machineController; private final String version; private final String preconfigurationUrl; - + @Inject public CreateAndInstallVm( CreateAndRegisterMachineFromIsoIfNotAlreadyExists CreateAndRegisterMachineFromIsoIfNotAlreadyExists, @@ -88,51 +93,62 @@ public class CreateAndInstallVm implements Function { @Override public IMachine apply(MasterSpec masterSpec) { - VmSpec vmSpec = masterSpec.getVmSpec(); IsoSpec isoSpec = masterSpec.getIsoSpec(); - String vmName = vmSpec.getVmName(); - - IMachine vm = createAndRegisterMachineFromIsoIfNotAlreadyExists.apply(masterSpec); - + String masterName = vmSpec.getVmName(); + IMachine masterMachine = createAndRegisterMachineFromIsoIfNotAlreadyExists.apply(masterSpec); // Launch machine and wait for it to come online - machineController.ensureMachineIsLaunched(vmName); - + machineController.ensureMachineIsLaunched(masterName); String installationKeySequence = isoSpec.getInstallationKeySequence().replace("PRECONFIGURATION_URL", preconfigurationUrl); + + configureOsInstallationWithKeyboardSequence(masterName, installationKeySequence); - configureOsInstallationWithKeyboardSequence(vmName, installationKeySequence); + // the OS installation is a long process: let's delay the check for ssh of 40 sec + Uninterruptibles.sleepUninterruptibly(40, TimeUnit.SECONDS); + + masterMachine.setExtraData(GUEST_OS_USER, masterSpec.getLoginCredentials().getUser()); + masterMachine.setExtraData(GUEST_OS_PASSWORD, masterSpec.getLoginCredentials().getPassword()); - // the OS installation is a long process: let's delay the check for ssh of 30 sec - try { - Thread.sleep(30000l); - } catch (InterruptedException e) { - Throwables.propagate(e); - } + SshClient client = sshClientForIMachine.apply(masterMachine); + logger.debug(">> awaiting installation to finish node(%s)", masterName); + checkState(sshResponds.apply(client), "timed out waiting for guest %s to be accessible via ssh", masterName); + NodeMetadata nodeMetadata = imachineToNodeMetadata.apply(masterMachine); - SshClient client = sshClientForIMachine.apply(vm); - - logger.debug(">> awaiting installation to finish node(%s)", vmName); - - checkState(sshResponds.apply(client), "timed out waiting for guest %s to be accessible via ssh", vmName); - - NodeMetadata nodeMetadata = imachineToNodeMetadata.apply(vm); - - logger.debug(">> awaiting post-installation actions on vm: %s", vmName); + logger.debug(">> awaiting post-installation actions on vm: %s", masterName); ListenableFuture execCleanup = machineUtils.runScriptOnNode(nodeMetadata, call("cleanupUdevIfNeeded"), RunScriptOptions.NONE); ExecResponse cleanupResponse = Futures.getUnchecked(execCleanup); checkState(cleanupResponse.getExitStatus() == 0); - logger.debug(">> awaiting installation of guest additions on vm: %s", vmName); + logger.debug(">> awaiting installation of guest additions on vm: %s", masterName); ListenableFuture execInstallGA = machineUtils.runScriptOnNode(nodeMetadata, new InstallGuestAdditions(vmSpec, version), RunScriptOptions.NONE); ExecResponse gaInstallationResponse = Futures.getUnchecked(execInstallGA); checkState(gaInstallationResponse.getExitStatus() == 0); + + machineController.ensureMachineIsShutdown(masterName); - machineController.ensureMachineIsShutdown(vmName); - - return vm; + // detach DVD and ISOs, if needed + Iterable mediumAttachments = Iterables.filter( + masterMachine.getMediumAttachmentsOfController("IDE Controller"), + new Predicate() { + public boolean apply(IMediumAttachment in) { + return in.getMedium() != null + && in.getMedium().getDeviceType() + .equals(DeviceType.DVD); + } + }); + for (IMediumAttachment iMediumAttachment : mediumAttachments) { + logger.debug("Detach %s from (%s)", iMediumAttachment.getMedium() + .getName(), masterMachine.getName()); + machineUtils.writeLockMachineAndApply( + masterMachine.getName(), + new DetachDistroMediumFromMachine(iMediumAttachment + .getController(), iMediumAttachment.getPort(), + iMediumAttachment.getDevice())); + } + return masterMachine; } private void configureOsInstallationWithKeyboardSequence(String vmName, String installationKeySequence) { diff --git a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/CreateAndRegisterMachineFromIsoIfNotAlreadyExists.java b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/CreateAndRegisterMachineFromIsoIfNotAlreadyExists.java index fb8dc97e7b..bd710c4a82 100644 --- a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/CreateAndRegisterMachineFromIsoIfNotAlreadyExists.java +++ b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/CreateAndRegisterMachineFromIsoIfNotAlreadyExists.java @@ -77,30 +77,31 @@ public class CreateAndRegisterMachineFromIsoIfNotAlreadyExists implements Functi } @Override - public IMachine apply(MasterSpec launchSpecification) { + public IMachine apply(MasterSpec masterSpec) { final IVirtualBox vBox = manager.get().getVBox(); - String vmName = launchSpecification.getVmSpec().getVmName(); - String vmId = launchSpecification.getVmSpec().getVmId(); + String vmName = masterSpec.getVmSpec().getVmName(); + String vmId = masterSpec.getVmSpec().getVmId(); try { vBox.findMachine(vmId); throw new IllegalStateException("Machine " + vmName + " is already registered."); } catch (VBoxException e) { if (machineNotFoundException(e)) - return createMachine(vBox, launchSpecification); + return createMachine(vBox, masterSpec); else throw e; } } - private IMachine createMachine(IVirtualBox vBox, MasterSpec machineSpec) { - VmSpec vmSpec = machineSpec.getVmSpec(); + private IMachine createMachine(IVirtualBox vBox, MasterSpec masterSpec) { + VmSpec vmSpec = masterSpec.getVmSpec(); String settingsFile = vBox.composeMachineFilename(vmSpec.getVmName(), workingDir); IMachine newMachine = vBox.createMachine(settingsFile, vmSpec.getVmName(), vmSpec.getOsTypeId(), vmSpec.getVmId(), vmSpec.isForceOverwrite()); + manager.get().getVBox().registerMachine(newMachine); - ensureConfiguration(machineSpec); + ensureConfiguration(masterSpec); return newMachine; } diff --git a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/HardcodedHostToHostNodeMetadata.java b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/HardcodedHostToHostNodeMetadata.java new file mode 100644 index 0000000000..8f09c67d22 --- /dev/null +++ b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/HardcodedHostToHostNodeMetadata.java @@ -0,0 +1,83 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.virtualbox.functions; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.net.URI; + +import javax.annotation.Resource; +import javax.inject.Named; + +import org.jclouds.compute.domain.NodeMetadata; +import org.jclouds.compute.domain.NodeMetadataBuilder; +import org.jclouds.compute.reference.ComputeServiceConstants; +import org.jclouds.domain.LoginCredentials; +import org.jclouds.javax.annotation.Nullable; +import org.jclouds.location.Provider; +import org.jclouds.logging.Logger; +import org.jclouds.rest.annotations.Credential; +import org.jclouds.rest.annotations.Identity; + +import com.google.common.base.Function; +import com.google.common.base.Supplier; +import com.google.common.collect.ImmutableList; +import com.google.inject.Inject; +import com.google.inject.Singleton; + +@Singleton +public class HardcodedHostToHostNodeMetadata implements + Function { + + @Resource + @Named(ComputeServiceConstants.COMPUTE_LOGGER) + protected Logger logger = Logger.NULL; + + private final Supplier providerSupplier; + private final String username; + private final String password; + + @Inject + public HardcodedHostToHostNodeMetadata( + @Provider Supplier providerSupplier, + @Nullable @Identity String identity, + @Nullable @Credential String credential) { + this.providerSupplier = checkNotNull(providerSupplier, + "endpoint to virtualbox websrvd is needed"); + this.username = identity; + this.password = credential.equals("CHANGE_ME") ? "" : credential; + } + + @Override + public NodeMetadata apply(NodeMetadata host) { + + LoginCredentials.Builder credentialsBuilder = LoginCredentials.builder( + host.getCredentials()).user(username); + if (!password.isEmpty()) + credentialsBuilder.password(password); + + return NodeMetadataBuilder + .fromNodeMetadata(host) + .credentials(credentialsBuilder.build()) + .publicAddresses(ImmutableList.of(providerSupplier.get().getHost())) + .build(); + } + +} diff --git a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToNodeMetadata.java b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToNodeMetadata.java index d985d050cd..f1a4c09cad 100644 --- a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToNodeMetadata.java +++ b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToNodeMetadata.java @@ -19,9 +19,12 @@ package org.jclouds.virtualbox.functions; +import static org.jclouds.virtualbox.config.VirtualBoxConstants.GUEST_OS_PASSWORD; +import static org.jclouds.virtualbox.config.VirtualBoxConstants.GUEST_OS_USER; import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_NODE_NAME_SEPARATOR; import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_NODE_PREFIX; +import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -37,8 +40,7 @@ import org.jclouds.domain.LocationScope; import org.jclouds.domain.LoginCredentials; import org.jclouds.javax.annotation.Nullable; import org.jclouds.logging.Logger; -import org.jclouds.virtualbox.util.MachineUtils; -import org.testng.collections.Lists; +import org.jclouds.virtualbox.util.NetworkUtils; import org.virtualbox_4_1.IMachine; import org.virtualbox_4_1.INetworkAdapter; import org.virtualbox_4_1.MachineState; @@ -46,7 +48,6 @@ import org.virtualbox_4_1.NetworkAttachmentType; import com.google.common.base.Function; import com.google.common.base.Splitter; -import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.inject.Inject; import com.google.inject.Singleton; @@ -59,12 +60,13 @@ public class IMachineToNodeMetadata implements Function protected Logger logger = Logger.NULL; private final Map toPortableNodeStatus; - private final MachineUtils machineUtils; + private final NetworkUtils networkUtils; @Inject - public IMachineToNodeMetadata(Map toPortableNodeStatus, MachineUtils machineUtils) { + public IMachineToNodeMetadata(Map toPortableNodeStatus, + NetworkUtils networkUtils) { this.toPortableNodeStatus = toPortableNodeStatus; - this.machineUtils = machineUtils; + this.networkUtils = networkUtils; } @Override @@ -82,7 +84,6 @@ public class IMachineToNodeMetadata implements Function NodeMetadataBuilder nodeMetadataBuilder = new NodeMetadataBuilder(); nodeMetadataBuilder.name(name).ids(vm.getName()).group(group); - // TODO Set up location properly LocationBuilder locationBuilder = new LocationBuilder(); locationBuilder.description(""); @@ -96,55 +97,26 @@ public class IMachineToNodeMetadata implements Function if (nodeState == null) nodeState = Status.UNRECOGNIZED; nodeMetadataBuilder.status(nodeState); - - /* - // nat adapter - INetworkAdapter natAdapter = vm.getNetworkAdapter(0l); - checkNotNull(natAdapter, "slot 0 networkadapter"); - checkState(natAdapter.getAttachmentType() == NetworkAttachmentType.NAT, - "expecting slot 0 to be a NAT attachment type (was: " + natAdapter.getAttachmentType() + ")"); - - int ipTermination = 0; - int inPort = 0; - String hostAddress = ""; - - nodeMetadataBuilder.publicAddresses(ImmutableSet.of(natAdapter.getNatDriver().getHostIP())); - for (String nameProtocolnumberAddressInboudportGuestTargetport : natAdapter.getNatDriver().getRedirects()) { - Iterable stuff = Splitter.on(',').split(nameProtocolnumberAddressInboudportGuestTargetport); - String protocolNumber = Iterables.get(stuff, 1); - hostAddress = Iterables.get(stuff, 2); - String inboundPort = Iterables.get(stuff, 3); - String targetPort = Iterables.get(stuff, 5); - if ("1".equals(protocolNumber) && "22".equals(targetPort)) { - inPort = Integer.parseInt(inboundPort); - ipTermination = inPort % NodeCreator.NODE_PORT_INIT + 2; - } - } - - // only masters use 2222 port - if (inPort == MastersLoadingCache.MASTER_PORT) { - nodeMetadataBuilder.publicAddresses(ImmutableSet.of(hostAddress)).loginPort(inPort); - } else { - nodeMetadataBuilder.privateAddresses(ImmutableSet.of((NodeCreator.VMS_NETWORK + ipTermination) + "")); - nodeMetadataBuilder.publicAddresses(ImmutableSet.of((NodeCreator.VMS_NETWORK + ipTermination) + "")); - } - */ - nodeMetadataBuilder = getIpAddresses(vm, nodeMetadataBuilder); - LoginCredentials loginCredentials = new LoginCredentials("toor", "password", null, true); + + String guestOsUser = vm.getExtraData(GUEST_OS_USER); + String guestOsPassword = vm.getExtraData(GUEST_OS_PASSWORD); + LoginCredentials loginCredentials = new LoginCredentials(guestOsUser, guestOsPassword, null, true); nodeMetadataBuilder.credentials(loginCredentials); return nodeMetadataBuilder.build(); } private NodeMetadataBuilder getIpAddresses(IMachine vm, NodeMetadataBuilder nodeMetadataBuilder) { - List publicIpAddresses = Lists.newArrayList(); - + List publicIpAddresses = new ArrayList(); + List privateIpAddresses = new ArrayList(); for(long slot = 0; slot < 4; slot ++) { INetworkAdapter adapter = vm.getNetworkAdapter(slot); if(adapter != null) { if (adapter.getAttachmentType() == NetworkAttachmentType.NAT) { - publicIpAddresses.add(adapter.getNatDriver().getHostIP()); + String hostIP = adapter.getNatDriver().getHostIP(); + if(!hostIP.isEmpty()) + publicIpAddresses.add(hostIP); for (String nameProtocolnumberAddressInboudportGuestTargetport : adapter.getNatDriver().getRedirects()) { Iterable stuff = Splitter.on(',').split(nameProtocolnumberAddressInboudportGuestTargetport); String protocolNumber = Iterables.get(stuff, 1); @@ -153,26 +125,24 @@ public class IMachineToNodeMetadata implements Function String targetPort = Iterables.get(stuff, 5); if ("1".equals(protocolNumber) && "22".equals(targetPort)) { int inPort = Integer.parseInt(inboundPort); - nodeMetadataBuilder.publicAddresses(ImmutableSet.of(hostAddress)).loginPort(inPort); + publicIpAddresses.add(hostAddress); + nodeMetadataBuilder.loginPort(inPort); } - //privateIpAddresses.add((NodeCreator.VMS_NETWORK + ipTermination) + ""); } - // TODO this could be a public and private address } else if (adapter.getAttachmentType() == NetworkAttachmentType.Bridged) { - String clientIpAddress = machineUtils.getIpAddressFromBridgedNIC(vm.getName()); - //privateIpAddresses.add(clientIpAddress); - publicIpAddresses.add(clientIpAddress); + // TODO quick test first + String clientIpAddress = networkUtils.getIpAddressFromNicSlot(vm.getName(), adapter.getSlot()); + privateIpAddresses.add(clientIpAddress); } else if (adapter.getAttachmentType() == NetworkAttachmentType.HostOnly) { - String clientIpAddress = machineUtils.getIpAddressFromHostOnlyNIC(vm.getName()); + // TODO quick test first + String clientIpAddress = networkUtils.getIpAddressFromNicSlot(vm.getName(), adapter.getSlot()); publicIpAddresses.add(clientIpAddress); - } } } nodeMetadataBuilder.publicAddresses(publicIpAddresses); nodeMetadataBuilder.privateAddresses(publicIpAddresses); - return nodeMetadataBuilder; } diff --git a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToSshClient.java b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToSshClient.java index 3c684152b6..0b25dbbe2a 100644 --- a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToSshClient.java +++ b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IMachineToSshClient.java @@ -19,33 +19,24 @@ package org.jclouds.virtualbox.functions; import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Preconditions.checkState; - -import java.util.List; +import static org.jclouds.virtualbox.config.VirtualBoxConstants.GUEST_OS_PASSWORD; +import static org.jclouds.virtualbox.config.VirtualBoxConstants.GUEST_OS_USER; import javax.annotation.Resource; import javax.inject.Named; import javax.inject.Singleton; -import org.jclouds.compute.callables.RunScriptOnNode; -import org.jclouds.compute.domain.ExecResponse; -import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.options.RunScriptOptions; import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.domain.LoginCredentials; import org.jclouds.logging.Logger; import org.jclouds.ssh.SshClient; -import org.jclouds.virtualbox.domain.BridgedIf; -import org.jclouds.virtualbox.statements.GetIPAddressFromMAC; -import org.jclouds.virtualbox.statements.ScanNetworkWithPing; -import org.jclouds.virtualbox.util.MachineUtils; +import org.jclouds.virtualbox.util.NetworkUtils; import org.virtualbox_4_1.IMachine; import org.virtualbox_4_1.INetworkAdapter; import org.virtualbox_4_1.NetworkAttachmentType; import com.google.common.base.Function; import com.google.common.base.Splitter; -import com.google.common.base.Supplier; import com.google.common.collect.Iterables; import com.google.common.net.HostAndPort; import com.google.inject.Inject; @@ -58,35 +49,30 @@ public class IMachineToSshClient implements Function { protected Logger logger = Logger.NULL; private final SshClient.Factory sshClientFactory; - private final RunScriptOnNode.Factory scriptRunnerFactory; - private final Supplier hostSupplier; - private final MachineUtils machineUtils; - + private final NetworkUtils networkUtils; + @Inject public IMachineToSshClient(SshClient.Factory sshClientFactory, - RunScriptOnNode.Factory scriptRunnerFactory, - Supplier hostSupplier, MachineUtils machineUtils) { + NetworkUtils networkUtils) { this.sshClientFactory = sshClientFactory; - this.scriptRunnerFactory = scriptRunnerFactory; - this.hostSupplier = hostSupplier; - this.machineUtils = machineUtils; + this.networkUtils = networkUtils; } @Override - public SshClient apply(final IMachine vm) { - INetworkAdapter networkAdapter = vm.getNetworkAdapter(0L); + public SshClient apply(final IMachine vm) { + INetworkAdapter networkAdapter = vm.getNetworkAdapter(0L); - SshClient client = null; - checkNotNull(networkAdapter); + SshClient client = null; + checkNotNull(networkAdapter); - String clientIpAddress = null; - String sshPort = "22"; + String clientIpAddress = null; + String sshPort = "22"; + String guestIdentity = vm.getExtraData(GUEST_OS_USER); + String guestCredential = vm.getExtraData(GUEST_OS_PASSWORD); - // TODO: we need a way to align the default login credentials - // from the iso with the vmspec -> IMachineToNodeMetadata using YamlImage ? - LoginCredentials loginCredentials = LoginCredentials.builder() - .user("toor").password("password").authenticateSudo(true) - .build(); + LoginCredentials loginCredentials = LoginCredentials.builder() + .user(guestIdentity).password(guestCredential) + .authenticateSudo(true).build(); if (networkAdapter.getAttachmentType() .equals(NetworkAttachmentType.NAT)) { @@ -105,11 +91,10 @@ public class IMachineToSshClient implements Function { } } else if (networkAdapter.getAttachmentType().equals( NetworkAttachmentType.Bridged)) { - String network = "1.1.1.1"; - clientIpAddress = getIpAddressFromBridgedNIC(networkAdapter, network); + clientIpAddress = networkUtils.getIpAddressFromNicSlot(vm.getName(), networkAdapter.getSlot()); } else if (networkAdapter.getAttachmentType().equals( NetworkAttachmentType.HostOnly)) { - clientIpAddress = machineUtils.getIpAddressFromHostOnlyNIC(vm.getName()); + clientIpAddress = networkUtils.getIpAddressFromNicSlot(vm.getName(), networkAdapter.getSlot()); } checkNotNull(clientIpAddress, "clientIpAddress"); @@ -120,28 +105,4 @@ public class IMachineToSshClient implements Function { return client; } - private String getIpAddressFromBridgedNIC(INetworkAdapter networkAdapter, - String network) { - // RetrieveActiveBridgedInterfaces - List activeBridgedInterfaces = new RetrieveActiveBridgedInterfaces(scriptRunnerFactory).apply(hostSupplier.get()); - BridgedIf activeBridgedIf = checkNotNull(Iterables.get(activeBridgedInterfaces, 0), "activeBridgedInterfaces"); - network = activeBridgedIf.getIpAddress(); - - // scan ip - RunScriptOnNode ipScanRunScript = scriptRunnerFactory.create( - hostSupplier.get(), new ScanNetworkWithPing(network), - RunScriptOptions.NONE); - ExecResponse execResponse = ipScanRunScript.init().call(); - checkState(execResponse.getExitStatus() == 0); - - // retrieve ip from mac - RunScriptOnNode getIpFromMACAddressRunScript = scriptRunnerFactory - .create(hostSupplier.get(), new GetIPAddressFromMAC( - networkAdapter.getMACAddress()), - RunScriptOptions.NONE); - ExecResponse ipExecResponse = getIpFromMACAddressRunScript.init() - .call(); - checkState(ipExecResponse.getExitStatus() == 0); - return checkNotNull(ipExecResponse.getOutput(), "ipAddress"); - } } \ No newline at end of file diff --git a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IpAddressesLoadingCache.java b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IpAddressesLoadingCache.java new file mode 100644 index 0000000000..03781f85b1 --- /dev/null +++ b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/IpAddressesLoadingCache.java @@ -0,0 +1,100 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.jclouds.virtualbox.functions; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.Map; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; + +import javax.annotation.Resource; +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; + +import org.jclouds.compute.reference.ComputeServiceConstants; +import org.jclouds.logging.Logger; +import org.jclouds.virtualbox.util.MachineNameOrIdAndNicSlot; +import org.jclouds.virtualbox.util.NetworkUtils; +import org.virtualbox_4_1.VirtualBoxManager; + +import com.google.common.base.Strings; +import com.google.common.base.Supplier; +import com.google.common.cache.AbstractLoadingCache; +import com.google.common.cache.LoadingCache; +import com.google.common.collect.Maps; +import com.google.common.util.concurrent.Uninterruptibles; + +/** + * A {@link LoadingCache} for ip addresses. If the requested ip address has been + * previously extracted this returns it, if not it calls vbox api. + * + * @author Andrea Turli + * + */ +@Singleton +public class IpAddressesLoadingCache extends + AbstractLoadingCache { + + @Resource + @Named(ComputeServiceConstants.COMPUTE_LOGGER) + protected Logger logger = Logger.NULL; + + private final Map masters = Maps.newHashMap(); + private final Supplier manager; + + @Inject + public IpAddressesLoadingCache(Supplier manager) { + this.manager = checkNotNull(manager, "vboxmanager"); + } + + @Override + public synchronized String get(MachineNameOrIdAndNicSlot machineNameOrIdAndNicPort) throws ExecutionException { + if (masters.containsKey(machineNameOrIdAndNicPort)) { + return masters.get(machineNameOrIdAndNicPort); + } + String query = String.format("/VirtualBox/GuestInfo/Net/%s/V4/IP", machineNameOrIdAndNicPort.getSlotText()); + String currentIp = ""; + while (!NetworkUtils.isIpv4(currentIp)) { + currentIp = manager.get().getVBox().findMachine(machineNameOrIdAndNicPort.getMachineNameOrId()) + .getGuestPropertyValue(query); + if(!Strings.nullToEmpty(currentIp).isEmpty()) + logger.debug("Found IP address %s for '%s' at slot %s", currentIp, + machineNameOrIdAndNicPort.getMachineNameOrId(), + machineNameOrIdAndNicPort.getSlotText()); + Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); + } + + masters.put(machineNameOrIdAndNicPort, currentIp); + return currentIp; + } + + @Override + public String getIfPresent(Object key) { + return masters.get((String) key); + } + + @Override + public void invalidate(Object key) { + masters.remove(key); + } + +} diff --git a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/LaunchMachineIfNotAlreadyRunning.java b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/LaunchMachineIfNotAlreadyRunning.java index d6445370b2..751afbbf4b 100644 --- a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/LaunchMachineIfNotAlreadyRunning.java +++ b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/LaunchMachineIfNotAlreadyRunning.java @@ -75,11 +75,6 @@ public class LaunchMachineIfNotAlreadyRunning implements Function { - // TODO parameterize - public static final int MASTER_PORT = 2222; - public static final String HOST_ONLY_IFACE_NAME = "vboxnet0"; + @Resource + @Named(ComputeServiceConstants.COMPUTE_LOGGER) + protected Logger logger = Logger.NULL; - @Resource - @Named(ComputeServiceConstants.COMPUTE_LOGGER) - protected Logger logger = Logger.NULL; + private final Map masters = Maps.newHashMap(); + private final Function masterCreatorAndInstaller; + private final Map imageMapping; + private final String workingDir; + private final String installationKeySequence; + private final String isosDir; + private final Supplier manager; + private final String version; + private final String preconfigurationUrl; - private final Map masters = Maps.newHashMap(); - private final Function masterCreatorAndInstaller; - private final Map imageMapping; - private final String workingDir; - private final String installationKeySequence; - private final String isosDir; - private final Supplier manager; - private final Function isoDownloader; - private final String version; - private final String preconfigurationUrl; + private final Factory runScriptOnNodeFactory; + private final RetryIfSocketNotYetOpen socketTester; + private final Supplier host; + private final Supplier providerSupplier; + private final HardcodedHostToHostNodeMetadata hardcodedHostToHostNodeMetadata; - @Inject - public MastersLoadingCache(@BuildVersion String version, - @Named(VIRTUALBOX_INSTALLATION_KEY_SEQUENCE) String installationKeySequence, - @Named(VIRTUALBOX_PRECONFIGURATION_URL) String preconfigurationUrl, - @Named(VIRTUALBOX_WORKINGDIR) String workingDir, Function masterLoader, - Supplier> yamlMapper, Supplier manager, - Function isoDownloader) { - checkNotNull(version, "version"); - checkNotNull(installationKeySequence, "installationKeySequence"); - checkNotNull(manager, "vboxmanager"); - this.manager = manager; - this.masterCreatorAndInstaller = masterLoader; - this.installationKeySequence = installationKeySequence; - this.workingDir = workingDir == null ? VIRTUALBOX_DEFAULT_DIR : workingDir; - this.isosDir = workingDir + File.separator + "isos"; - this.imageMapping = Maps.newLinkedHashMap(); - for (Entry entry : yamlMapper.get().entrySet()) { - this.imageMapping.put(entry.getKey().getId(), entry.getValue()); - } - this.version = Iterables.get(Splitter.on('r').split(version), 0); - this.isoDownloader = isoDownloader; - this.preconfigurationUrl = preconfigurationUrl; - } + @Inject + public MastersLoadingCache( + @BuildVersion String version, + @Named(VIRTUALBOX_INSTALLATION_KEY_SEQUENCE) String installationKeySequence, + @Named(VIRTUALBOX_PRECONFIGURATION_URL) String preconfigurationUrl, + @Named(VIRTUALBOX_WORKINGDIR) String workingDir, + Function masterLoader, + Supplier> yamlMapper, + Supplier manager, + Factory runScriptOnNodeFactory, + RetryIfSocketNotYetOpen socketTester, Supplier host, + @Provider Supplier providerSupplier, + HardcodedHostToHostNodeMetadata hardcodedHostToHostNodeMetadata) { + checkNotNull(version, "version"); + checkNotNull(installationKeySequence, "installationKeySequence"); + checkNotNull(manager, "vboxmanager"); + this.manager = manager; + this.masterCreatorAndInstaller = masterLoader; + this.installationKeySequence = installationKeySequence; + this.workingDir = workingDir == null ? VIRTUALBOX_DEFAULT_DIR + : workingDir; + this.isosDir = workingDir + File.separator + "isos"; + this.imageMapping = Maps.newLinkedHashMap(); + for (Entry entry : yamlMapper.get().entrySet()) { + this.imageMapping.put(entry.getKey().getId(), entry.getValue()); + } + this.version = Iterables.get(Splitter.on('r').split(version), 0); + this.preconfigurationUrl = preconfigurationUrl; - @PostConstruct - public void createCacheDirStructure() { - if (!new File(workingDir).exists()) { - new File(workingDir, "isos").mkdirs(); - } - } + this.runScriptOnNodeFactory = checkNotNull(runScriptOnNodeFactory, + "runScriptOnNodeFactory"); + this.socketTester = checkNotNull(socketTester, "socketTester"); + this.socketTester.seconds(3L); + this.host = checkNotNull(host, "host"); + this.providerSupplier = checkNotNull(providerSupplier, + "endpoint to virtualbox websrvd is needed"); + this.hardcodedHostToHostNodeMetadata = hardcodedHostToHostNodeMetadata; + } + + @PostConstruct + public void createCacheDirStructure() { + if (!new File(workingDir).exists()) { + new File(workingDir, "isos").mkdirs(); + } + } + + @Override + public synchronized Master get(Image key) throws ExecutionException { + // check if we have loaded this machine before + if (masters.containsKey(key.getId())) { + return masters.get(key.getId()); + } + checkState(!key.getId().contains(VIRTUALBOX_NODE_NAME_SEPARATOR), + "master image names cannot contain \"" + + VIRTUALBOX_NODE_NAME_SEPARATOR + "\""); + String vmName = VIRTUALBOX_IMAGE_PREFIX + key.getId(); + IMachine masterMachine; + Master master; + // ready the preseed file server + PreseedCfgServer server = new PreseedCfgServer(); + try { + // try and find a master machine in vbox + masterMachine = manager.get().getVBox().findMachine(vmName); + master = Master.builder().machine(masterMachine).build(); + } catch (VBoxException e) { + if (machineNotFoundException(e)) { + // machine was not found try to build one from a yaml file + YamlImage currentImage = checkNotNull(imageMapping.get(key.getId()), "currentImage"); + URI preseedServer; + try { + preseedServer = new URI(preconfigurationUrl); + if (!socketTester.apply(HostAndPort.fromParts(preseedServer.getHost(), + preseedServer.getPort()))) { + server.start(preconfigurationUrl, currentImage.preseed_cfg); + } + } catch (URISyntaxException e1) { + logger.error("Cannot start the preseed server", e); + throw e; + } + + MasterSpec masterSpec = buildMasterSpecFromYaml(currentImage, + vmName); + masterMachine = masterCreatorAndInstaller.apply(masterSpec); + master = Master.builder().machine(masterMachine) + .spec(masterSpec).build(); + } else { + logger.error("Problem during master creation", e); + throw e; + } + } finally { + server.stop(); + } + + masters.put(key.getId(), master); + return master; + } + + private MasterSpec buildMasterSpecFromYaml(YamlImage currentImage, + String vmName) throws ExecutionException { + String guestAdditionsFileName = String.format( + "VBoxGuestAdditions_%s.iso", version); + String guestAdditionsIso = String.format("%s/%s", isosDir, + guestAdditionsFileName); + String guestAdditionsUri = "http://download.virtualbox.org/virtualbox/" + + version + "/" + guestAdditionsFileName; + if (!new File(guestAdditionsIso).exists()) { + getFilePathOrDownload(guestAdditionsUri, null); + } + // check if the iso is here, download if not + String localIsoUrl = checkNotNull(getFilePathOrDownload(currentImage.iso, currentImage.iso_md5), "distro iso"); + String adminDisk = workingDir + File.separator + vmName + ".vdi"; + HardDisk hardDisk = HardDisk.builder().diskpath(adminDisk) + .autoDelete(true).controllerPort(0).deviceSlot(1).build(); + + StorageController ideController = StorageController.builder() + .name("IDE Controller").bus(StorageBus.IDE) + .attachISO(0, 0, localIsoUrl).attachHardDisk(hardDisk) + .attachISO(1, 0, guestAdditionsIso).build(); + + VmSpec vmSpecification = VmSpec.builder().id(currentImage.id) + .name(vmName).memoryMB(512).osTypeId(getOsTypeId(currentImage.os_family, currentImage.os_64bit)) + .controller(ideController).forceOverwrite(true) + .guestUser(currentImage.username).guestPassword(currentImage.credential) + .cleanUpMode(CleanupMode.Full).build(); + + NetworkAdapter networkAdapter = NetworkAdapter + .builder() + .networkAttachmentType(NetworkAttachmentType.NAT) + .tcpRedirectRule(providerSupplier.get().getHost(), NetworkUtils.MASTER_PORT, + "", 22).build(); + + NetworkInterfaceCard networkInterfaceCard = NetworkInterfaceCard + .builder().addNetworkAdapter(networkAdapter).slot(0L).build(); + + NetworkSpec networkSpec = NetworkSpec.builder() + .addNIC(networkInterfaceCard).build(); + + return MasterSpec + .builder() + .vm(vmSpecification) + .iso(IsoSpec + .builder() + .sourcePath(localIsoUrl) + .installationScript( + installationKeySequence.replace("HOSTNAME", + vmSpecification.getVmName())).build()) + .network(networkSpec) + .credentials(new LoginCredentials(currentImage.username, currentImage.credential, null, true)) + .build(); + } @Override - public synchronized Master get(Image key) throws ExecutionException { - // check if we have loaded this machine before - if (masters.containsKey(key.getId())) { - return masters.get(key.getId()); + public synchronized Master getIfPresent(Object key) { + checkArgument(key instanceof Image, + "this cache is for entries who's keys are Images"); + Image image = Image.class.cast(key); + if (masters.containsKey(image.getId())) { + return masters.get(image.getId()); + } + return null; + } + + private String getFilePathOrDownload(String httpUrl, String md5) + throws ExecutionException { + String fileName = httpUrl.substring(httpUrl.lastIndexOf('/') + 1, + httpUrl.length()); + URI provider = providerSupplier.get(); + if (!socketTester.apply(HostAndPort.fromParts(provider.getHost(), + provider.getPort()))) { + throw new RuntimeException("could not connect to virtualbox"); } + File file = new File(isosDir, fileName); + List statements = new ArrayList(); + statements.add(Statements.saveHttpResponseTo(URI.create(httpUrl), + isosDir, fileName)); + StatementList statementList = new StatementList(statements); + NodeMetadata hostNodeMetadata = hardcodedHostToHostNodeMetadata + .apply(host.get()); + runScriptOnNodeFactory + .create(hostNodeMetadata, statementList, runAsRoot(false)).init() + .call(); - checkState(!key.getId().contains(VIRTUALBOX_NODE_NAME_SEPARATOR), "master image names cannot contain \"" - + VIRTUALBOX_NODE_NAME_SEPARATOR + "\""); - - String vmName = VIRTUALBOX_IMAGE_PREFIX + key.getId(); - - IMachine masterMachine; - - Master master; - - // ready the preseed file server - PreseedCfgServer server = new PreseedCfgServer(); - try { - // try and find a master machine in vbox - masterMachine = manager.get().getVBox().findMachine(vmName); - master = Master.builder().machine(masterMachine).build(); - - } catch (VBoxException e) { - if (machineNotFoundException(e)) { - // machine was not found try to build one from a yaml file - YamlImage currentImage = imageMapping.get(key.getId()); - - checkNotNull(currentImage); - - server.start(preconfigurationUrl, currentImage.preseed_cfg); - - MasterSpec masterSpec = buildMasterSpecFromYaml(currentImage, vmName); - - // create the master machine if it can't be found - masterMachine = masterCreatorAndInstaller.apply(masterSpec); - - // build the master - master = Master.builder().machine(masterMachine).spec(masterSpec).build(); - } else { - throw e; - } - } finally { - server.stop(); + ExecResponse response = runScriptOnNodeFactory + .create( + hostNodeMetadata, + Statements.exec("md5 " + isosDir + File.separator + fileName), + runAsRoot(false)).init().call(); + if (md5 != null) { + if (!Iterables.get( + Splitter.on("=").trimResults().split(response.getOutput()), 1) + .equals(md5)) + return null; } - - masters.put(key.getId(), master); - return master; + return file.getAbsolutePath(); } - private MasterSpec buildMasterSpecFromYaml(YamlImage currentImage, String vmName) throws ExecutionException { - - String guestAdditionsFileName = String.format("VBoxGuestAdditions_%s.iso", version); - String guestAdditionsIso = String.format("%s/%s", isosDir, guestAdditionsFileName); - String guestAdditionsUri = "http://download.virtualbox.org/virtualbox/" + version + "/" + guestAdditionsFileName; - if (!new File(guestAdditionsIso).exists()) { - getFilePathOrDownload(guestAdditionsUri); - } - checkState(new File(guestAdditionsIso).exists(), "guest additions iso does not exist at: " + guestAdditionsIso); - - // check if the iso is here, download if not - String localIsoUrl = getFilePathOrDownload(currentImage.iso); - - String adminDisk = workingDir + File.separator + vmName + ".vdi"; - - HardDisk hardDisk = HardDisk.builder().diskpath(adminDisk).autoDelete(true).controllerPort(0).deviceSlot(1) - .build(); - - StorageController ideController = StorageController.builder().name("IDE Controller").bus(StorageBus.IDE) - .attachISO(0, 0, localIsoUrl).attachHardDisk(hardDisk).attachISO(1, 0, guestAdditionsIso).build(); - - VmSpec vmSpecification = VmSpec.builder().id(currentImage.id).name(vmName).memoryMB(512).osTypeId("") - .controller(ideController).forceOverwrite(true).cleanUpMode(CleanupMode.Full).build(); - - NetworkAdapter networkAdapter = NetworkAdapter.builder().networkAttachmentType(NetworkAttachmentType.NAT) - .tcpRedirectRule("127.0.0.1", MASTER_PORT, "", 22).build(); - - NetworkInterfaceCard networkInterfaceCard = NetworkInterfaceCard.builder().addNetworkAdapter(networkAdapter) - .slot(0L).build(); - - NetworkSpec networkSpec = NetworkSpec.builder().addNIC(networkInterfaceCard).build(); - - return MasterSpec - .builder() - .vm(vmSpecification) - .iso(IsoSpec.builder().sourcePath(localIsoUrl) - .installationScript(installationKeySequence.replace("HOSTNAME", vmSpecification.getVmName())) - .build()).network(networkSpec).build(); + private String getOsTypeId(String os_family, boolean os_64bit) { + String osFamily = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, os_family); + return os_64bit ? osFamily + "_64" : osFamily; } - - @Override - public synchronized Master getIfPresent(Object key) { - checkArgument(key instanceof Image, "this cache is for entries who's keys are Images"); - Image image = Image.class.cast(key); - if (masters.containsKey(image.getId())) { - return masters.get(image.getId()); - } - return null; - } - - private String getFilePathOrDownload(String httpUrl) throws ExecutionException { - String fileName = httpUrl.substring(httpUrl.lastIndexOf('/') + 1, httpUrl.length()); - File localFile = new File(isosDir, fileName); - if (!localFile.exists()) { - logger.debug("iso not found in cache, downloading: %s", httpUrl); - localFile = isoDownloader.apply(URI.create(httpUrl)); - } - checkState(localFile.exists(), "iso file has not been downloaded: " + fileName); - return localFile.getAbsolutePath(); - } - } diff --git a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/NodeCreator.java b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/NodeCreator.java index d417afbfee..748bee31fe 100644 --- a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/NodeCreator.java +++ b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/NodeCreator.java @@ -21,48 +21,47 @@ package org.jclouds.virtualbox.functions; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; -import static org.jclouds.compute.options.RunScriptOptions.Builder.runAsRoot; +import static org.jclouds.virtualbox.config.VirtualBoxConstants.GUEST_OS_PASSWORD; +import static org.jclouds.virtualbox.config.VirtualBoxConstants.GUEST_OS_USER; +import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_GUEST_MEMORY; import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_IMAGE_PREFIX; import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_NODE_NAME_SEPARATOR; import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_NODE_PREFIX; -import java.util.List; - +import javax.annotation.Resource; import javax.inject.Inject; +import javax.inject.Named; import javax.inject.Singleton; import org.jclouds.compute.ComputeServiceAdapter.NodeAndInitialCredentials; import org.jclouds.compute.callables.RunScriptOnNode; -import org.jclouds.compute.callables.RunScriptOnNode.Factory; -import org.jclouds.compute.domain.ExecResponse; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadataBuilder; import org.jclouds.compute.options.RunScriptOptions; +import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.domain.LoginCredentials; -import org.jclouds.scriptbuilder.domain.Statements; +import org.jclouds.logging.Logger; import org.jclouds.virtualbox.config.VirtualBoxComputeServiceContextModule; import org.jclouds.virtualbox.domain.CloneSpec; import org.jclouds.virtualbox.domain.Master; -import org.jclouds.virtualbox.domain.NetworkAdapter; import org.jclouds.virtualbox.domain.NetworkInterfaceCard; import org.jclouds.virtualbox.domain.NetworkSpec; import org.jclouds.virtualbox.domain.NodeSpec; import org.jclouds.virtualbox.domain.VmSpec; import org.jclouds.virtualbox.statements.DeleteGShadowLock; -import org.jclouds.virtualbox.statements.EnableNetworkInterface; import org.jclouds.virtualbox.util.MachineController; import org.jclouds.virtualbox.util.MachineUtils; +import org.jclouds.virtualbox.util.NetworkUtils; import org.virtualbox_4_1.CleanupMode; -import org.virtualbox_4_1.HostNetworkInterfaceType; -import org.virtualbox_4_1.IDHCPServer; -import org.virtualbox_4_1.IHostNetworkInterface; import org.virtualbox_4_1.IMachine; import org.virtualbox_4_1.IProgress; import org.virtualbox_4_1.ISession; +import org.virtualbox_4_1.LockType; import org.virtualbox_4_1.NetworkAttachmentType; import org.virtualbox_4_1.VirtualBoxManager; import com.google.common.base.Function; +import com.google.common.base.Optional; import com.google.common.base.Predicate; import com.google.common.base.Supplier; import com.google.common.collect.ImmutableSet; @@ -77,207 +76,121 @@ import com.google.common.collect.Iterables; */ @Singleton public class NodeCreator implements Function> { - + + @Resource + @Named(ComputeServiceConstants.COMPUTE_LOGGER) + protected Logger logger = Logger.NULL; + private final Supplier manager; private final Function cloner; private final MachineUtils machineUtils; private final MachineController machineController; - private final Factory runScriptOnNodeFactory; - private final Supplier host; - - + private final NetworkUtils networkUtils; + private final int ram; + + @Inject - public NodeCreator(Supplier manager, Function cloner, Factory runScriptOnNodeFactory, - Supplier host, - MachineUtils machineUtils, RunScriptOnNode.Factory scriptRunnerFactory, MachineController machineController) { + public NodeCreator(Supplier manager, Function cloner, + MachineUtils machineUtils, RunScriptOnNode.Factory scriptRunnerFactory, MachineController machineController, + NetworkUtils networkUtils, + @Named(VIRTUALBOX_GUEST_MEMORY) String ram) { this.manager = manager; this.cloner = cloner; - this.runScriptOnNodeFactory = checkNotNull(runScriptOnNodeFactory, "runScriptOnNodeFactory"); - this.host = checkNotNull(host, "host"); - + this.networkUtils = networkUtils; this.machineUtils = machineUtils; this.machineController = machineController; + this.ram = Integer.valueOf(ram); } @Override public synchronized NodeAndInitialCredentials apply(NodeSpec nodeSpec) { - checkNotNull(nodeSpec, "NodeSpec"); - - Master master = nodeSpec.getMaster(); - checkNotNull(master, "Master"); - + Master master = checkNotNull(nodeSpec.getMaster(), "Master"); + if (master.getMachine().getCurrentSnapshot() != null) { ISession session; try { - session = manager.get().openMachineSession(master.getMachine()); + session = manager.get().getSessionObject(); + master.getMachine().lockMachine(session, LockType.Write); + IProgress progress = session.getConsole().deleteSnapshot(master.getMachine().getCurrentSnapshot().getId()); + progress.waitForCompletion(-1); + session.unlockMachine(); } catch (Exception e) { throw new RuntimeException("error opening vbox machine session: " + e.getMessage(), e); } - IProgress progress = session.getConsole().deleteSnapshot(master.getMachine().getCurrentSnapshot().getId()); - progress.waitForCompletion(-1); - session.unlockMachine(); + logger.debug("Deleted an existing snapshot from %s", master.getMachine().getName()); } String masterNameWithoutPrefix = master.getMachine().getName().replace(VIRTUALBOX_IMAGE_PREFIX, ""); - String cloneName = VIRTUALBOX_NODE_PREFIX + masterNameWithoutPrefix + VIRTUALBOX_NODE_NAME_SEPARATOR + nodeSpec.getTag() + VIRTUALBOX_NODE_NAME_SEPARATOR + nodeSpec.getName(); - - int ram = 512; - if (nodeSpec.getTemplate() != null && nodeSpec.getTemplate().getHardware() != null - && nodeSpec.getTemplate().getHardware().getRam() > 0) { - ram = nodeSpec.getTemplate().getHardware().getRam(); - } - VmSpec cloneVmSpec = VmSpec.builder().id(cloneName).name(cloneName).memoryMB(ram).cleanUpMode(CleanupMode.Full) - .forceOverwrite(true).build(); - - // CASE NAT + HOST-ONLY - NetworkAdapter natAdapter = NetworkAdapter.builder().networkAttachmentType(NetworkAttachmentType.NAT) - .build(); - NetworkInterfaceCard natIfaceCard = NetworkInterfaceCard.builder().addNetworkAdapter(natAdapter).slot(1L).build(); - - NetworkAdapter hostOnlyAdapter = NetworkAdapter.builder().networkAttachmentType(NetworkAttachmentType.HostOnly) - .build(); - - // create new hostOnly interface if needed, otherwise use the one already there with dhcp enabled ... - String hostOnlyIfName = getHostOnlyIfOrCreate(); + IMachine masterMachine = master.getMachine(); + String username = masterMachine.getExtraData(GUEST_OS_USER); + String password = masterMachine.getExtraData(GUEST_OS_PASSWORD); - NetworkInterfaceCard hostOnlyIfaceCard = NetworkInterfaceCard.builder().addNetworkAdapter(hostOnlyAdapter) - .addHostInterfaceName(hostOnlyIfName).slot(0L).build(); - - NetworkSpec networkSpec = createNetworkSpecForHostOnlyNATNICs(natIfaceCard, hostOnlyIfaceCard); + VmSpec cloneVmSpec = VmSpec.builder().id(cloneName).name(cloneName).memoryMB(ram) + .guestUser(username).guestPassword(password) + .cleanUpMode(CleanupMode.Full) + .forceOverwrite(true).build(); + + // case 'vbox host is localhost': NAT + HOST-ONLY + NetworkSpec networkSpec = networkUtils.createNetworkSpecWhenVboxIsLocalhost(); + Optional optionalNatIfaceCard = Iterables.tryFind( + networkSpec.getNetworkInterfaceCards(), + new Predicate() { + @Override + public boolean apply(NetworkInterfaceCard nic) { + return nic.getNetworkAdapter().getNetworkAttachmentType() + .equals(NetworkAttachmentType.NAT); + } + }); CloneSpec cloneSpec = CloneSpec.builder().linked(true).master(master.getMachine()).network(networkSpec) .vm(cloneVmSpec).build(); + logger.debug("Cloning a new guest an existing snapshot from %s ...", master.getMachine().getName()); IMachine cloned = cloner.apply(cloneSpec); - machineController.ensureMachineIsLaunched(cloneVmSpec.getVmName()); - + // IMachineToNodeMetadata produces the final ip's but these need to be set before so we build a // NodeMetadata just for the sake of running the gshadow and setip scripts NodeMetadata partialNodeMetadata = buildPartialNodeMetadata(cloned); // see DeleteGShadowLock for a detailed explanation - machineUtils.runScriptOnNode(partialNodeMetadata, new DeleteGShadowLock(), RunScriptOptions.NONE); + machineUtils.runScriptOnNode(partialNodeMetadata, new DeleteGShadowLock(), RunScriptOptions.NONE); - // CASE NAT + HOST-ONLY - machineUtils.runScriptOnNode(partialNodeMetadata, new EnableNetworkInterface(natIfaceCard), RunScriptOptions.NONE); + if(optionalNatIfaceCard.isPresent()) + checkState(networkUtils.enableNetworkInterface(partialNodeMetadata, optionalNatIfaceCard.get()) == true, + "cannot enable Nat Interface"); - - // TODO get credentials from somewhere else (they are also HC in - // IMachineToSshClient) - NodeAndInitialCredentials nodeAndInitialCredentials = new NodeAndInitialCredentials(cloned, - cloneName, LoginCredentials.builder().user("toor").password("password").authenticateSudo(true).build()); - - return nodeAndInitialCredentials; + LoginCredentials credentials = partialNodeMetadata.getCredentials(); + return new NodeAndInitialCredentials(cloned, + cloneName, credentials); } - + private NodeMetadata buildPartialNodeMetadata(IMachine clone) { NodeMetadataBuilder nodeMetadataBuilder = new NodeMetadataBuilder(); nodeMetadataBuilder.id(clone.getName()); nodeMetadataBuilder.status(VirtualBoxComputeServiceContextModule.toPortableNodeStatus.get(clone.getState())); - nodeMetadataBuilder.publicAddresses(ImmutableSet.of(machineUtils.getIpAddressFromHostOnlyNIC(clone.getName()))); - - LoginCredentials loginCredentials = new LoginCredentials("toor", "password", null, true); - nodeMetadataBuilder.credentials(loginCredentials); - + long slot = findSlotForNetworkAttachment(clone, NetworkAttachmentType.HostOnly); + nodeMetadataBuilder.publicAddresses(ImmutableSet.of(networkUtils.getIpAddressFromNicSlot(clone.getName(), slot))); + String guestOsUser = clone.getExtraData(GUEST_OS_USER); + String guestOsPassword = clone.getExtraData(GUEST_OS_PASSWORD); + LoginCredentials loginCredentials = new LoginCredentials(guestOsUser, guestOsPassword, null, true); + nodeMetadataBuilder.credentials(loginCredentials); return nodeMetadataBuilder.build(); } - private NetworkSpec createNetworkSpecForHostOnlyNATNICs(NetworkInterfaceCard natIfaceCard, - NetworkInterfaceCard hostOnlyIfaceCard) { - return NetworkSpec.builder().addNIC(natIfaceCard).addNIC(hostOnlyIfaceCard).build(); - } - - /** - * @return - */ - private String getHostOnlyIfOrCreate() { - - IHostNetworkInterface availableHostInterfaceIf = returnExistingHostNetworkInterfaceWithDHCPenabledOrNull(manager - .get().getVBox().getHost().getNetworkInterfaces()); - if (availableHostInterfaceIf==null) { - final String hostOnlyIfName = createHostOnlyIf(); - assignDHCPtoHostOnlyInterface(hostOnlyIfName); - return hostOnlyIfName; - } else { - return availableHostInterfaceIf.getName(); + private long findSlotForNetworkAttachment(IMachine clone, NetworkAttachmentType networkAttachmentType) { + long slot = -1, i = 0; + while (slot == -1 && i < 4) { + if(clone.getNetworkAdapter(i).getAttachmentType().equals(networkAttachmentType)) + slot = i; + i++; } - + checkState(slot!=-1); + return slot; } - private void assignDHCPtoHostOnlyInterface(final String hostOnlyIfName) { - List availableNetworkInterfaces = manager.get().getVBox().getHost() - .getNetworkInterfaces(); - - IHostNetworkInterface iHostNetworkInterfaceWithHostOnlyIfName = Iterables.getOnlyElement(Iterables.filter(availableNetworkInterfaces, new Predicate() { - - @Override - public boolean apply(IHostNetworkInterface iHostNetworkInterface) { - return iHostNetworkInterface.getName().equals(hostOnlyIfName); - } - })); - - String hostOnlyIfIpAddress = iHostNetworkInterfaceWithHostOnlyIfName.getIPAddress(); - String dhcpIpAddress = hostOnlyIfIpAddress.substring(0, hostOnlyIfIpAddress.lastIndexOf(".")) + ".254"; - String dhcpNetmask = "255.255.255.0"; - String dhcpLowerIp = hostOnlyIfIpAddress.substring(0, hostOnlyIfIpAddress.lastIndexOf(".")) + ".2"; - String dhcpUpperIp = hostOnlyIfIpAddress.substring(0, hostOnlyIfIpAddress.lastIndexOf(".")) + ".253"; - - ExecResponse response = runScriptOnNodeFactory - .create(host.get(), - Statements.exec(String - .format("VBoxManage dhcpserver add --ifname %s --ip %s --netmask %s --lowerip %s --upperip %s --enable", - hostOnlyIfName, dhcpIpAddress, dhcpNetmask, dhcpLowerIp, dhcpUpperIp)), runAsRoot(false).wrapInInitScript(false)).init().call(); - checkState(response.getExitStatus()==0); - /* - runScriptOnNodeFactory - .create(host.get(), - Statements.exec(String.format("VBoxManage hostonlyif ipconfig %s --ip %s", - hostOnlyIfName, hostOnlyIfIpAddress)), runAsRoot(false).wrapInInitScript(false)).init().call(); - */ - } - - private String createHostOnlyIf() { - final String hostOnlyIfName; - ExecResponse createHostOnlyResponse = runScriptOnNodeFactory - .create(host.get(), Statements.exec("VBoxManage hostonlyif create"), - runAsRoot(false).wrapInInitScript(false)).init().call(); - String output = createHostOnlyResponse.getOutput(); - checkState(createHostOnlyResponse.getExitStatus()==0); - checkState(output.contains("'"), "cannot create hostonlyif"); - hostOnlyIfName = output.substring(output.indexOf("'") + 1, output.lastIndexOf("'")); - return hostOnlyIfName; - } - - private IHostNetworkInterface returnExistingHostNetworkInterfaceWithDHCPenabledOrNull(Iterable availableNetworkInterfaces) { - checkNotNull(availableNetworkInterfaces); - return Iterables.getFirst(filterAvailableNetworkInterfaceByHostOnlyAndDHCPenabled(availableNetworkInterfaces), null); - } - - /** - * @param availableNetworkInterfaces - * @param hostOnlyIfIpAddress - * @return - */ - private Iterable filterAvailableNetworkInterfaceByHostOnlyAndDHCPenabled(Iterable availableNetworkInterfaces) { - Iterable filteredNetworkInterfaces = Iterables.filter(availableNetworkInterfaces, new Predicate() { - @Override - public boolean apply(IHostNetworkInterface iHostNetworkInterface) { - // this is an horrible workaround cause iHostNetworkInterface.getDhcpEnabled is working only for windows host - boolean match = false; - List availableDHCPservers = manager.get().getVBox().getDHCPServers(); - for (IDHCPServer idhcpServer : availableDHCPservers) { - if(idhcpServer.getEnabled() && idhcpServer.getNetworkName().equals(iHostNetworkInterface.getNetworkName())) - match = true; - } - return iHostNetworkInterface.getInterfaceType().equals(HostNetworkInterfaceType.HostOnly) && - match; - } - }); - return filteredNetworkInterfaces; - } } diff --git a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/SendScancodes.java b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/SendScancodes.java index fa6a71e0d7..824a795c38 100644 --- a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/SendScancodes.java +++ b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/SendScancodes.java @@ -19,13 +19,13 @@ package org.jclouds.virtualbox.functions; import static com.google.common.base.Predicates.in; -import static com.google.common.base.Throwables.propagate; import static com.google.common.collect.Iterables.any; import static com.google.common.collect.Lists.partition; import static org.jclouds.compute.reference.ComputeServiceConstants.COMPUTE_LOGGER; import static org.jclouds.virtualbox.settings.KeyboardScancodes.SPECIAL_KEYBOARD_BUTTON_MAP_LIST; import java.util.List; +import java.util.concurrent.TimeUnit; import javax.annotation.Resource; import javax.inject.Named; @@ -34,6 +34,7 @@ import org.jclouds.logging.Logger; import org.virtualbox_4_1.ISession; import com.google.common.base.Function; +import com.google.common.util.concurrent.Uninterruptibles; class SendScancodes implements Function { @@ -56,9 +57,9 @@ class SendScancodes implements Function { logger.debug("List of scancodes sent: ", maxOrLess); assert (codesSent == maxOrLess.size()); if (any(maxOrLess, in(SPECIAL_KEYBOARD_BUTTON_MAP_LIST.values()))) { - sleepOrPropagateInterrupt(300); + Uninterruptibles.sleepUninterruptibly(300, TimeUnit.MILLISECONDS); } else { - sleepOrPropagateInterrupt(50); + Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS); } } return null; @@ -68,12 +69,4 @@ class SendScancodes implements Function { public String toString() { return "sendScancodes(" + scancodes + ")"; } - - public void sleepOrPropagateInterrupt(long ms) { - try { - Thread.sleep(ms); - } catch (InterruptedException e) { - throw propagate(e); - } - } } \ No newline at end of file diff --git a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/TakeSnapshotIfNotAlreadyAttached.java b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/TakeSnapshotIfNotAlreadyAttached.java index 218bd6664d..15480cdfa6 100644 --- a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/TakeSnapshotIfNotAlreadyAttached.java +++ b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/TakeSnapshotIfNotAlreadyAttached.java @@ -19,6 +19,8 @@ package org.jclouds.virtualbox.functions; +import java.util.concurrent.TimeUnit; + import org.jclouds.logging.Logger; import org.virtualbox_4_1.IMachine; import org.virtualbox_4_1.IProgress; @@ -30,6 +32,7 @@ import org.virtualbox_4_1.VirtualBoxManager; import com.google.common.base.Function; import com.google.common.base.Supplier; import com.google.common.base.Throwables; +import com.google.common.util.concurrent.Uninterruptibles; /** * @author Andrea Turli @@ -93,7 +96,7 @@ public class TakeSnapshotIfNotAlreadyAttached implements Function { if (!yamlFile.exists()) { yamlDesc = IOUtils.toString(new InputStreamReader(getClass().getResourceAsStream("/default-images.yaml"))); } else { - yamlDesc = IOUtils.toString(new FileInputStream(yamlFile)); + yamlDesc = Files.toString(yamlFile, Charsets.UTF_8); } checkNotNull(yamlDesc, "yaml descriptor"); return yamlDesc; diff --git a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/admin/StartVBoxIfNotAlreadyRunning.java b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/admin/StartVBoxIfNotAlreadyRunning.java index 4b5eeba584..d92cc71439 100644 --- a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/admin/StartVBoxIfNotAlreadyRunning.java +++ b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/admin/StartVBoxIfNotAlreadyRunning.java @@ -24,18 +24,25 @@ import static com.google.common.base.Preconditions.checkState; import static org.jclouds.compute.options.RunScriptOptions.Builder.runAsRoot; import java.net.URI; +import java.util.ArrayList; +import java.util.List; +import javax.annotation.PostConstruct; import javax.annotation.Resource; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Singleton; import org.jclouds.compute.callables.RunScriptOnNode.Factory; +import org.jclouds.compute.domain.ExecResponse; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.location.Provider; import org.jclouds.logging.Logger; +import org.jclouds.scriptbuilder.domain.Statement; +import org.jclouds.scriptbuilder.domain.StatementList; import org.jclouds.scriptbuilder.domain.Statements; +import org.jclouds.virtualbox.functions.HardcodedHostToHostNodeMetadata; import org.jclouds.virtualbox.predicates.RetryIfSocketNotYetOpen; import org.virtualbox_4_1.SessionState; import org.virtualbox_4_1.VirtualBoxManager; @@ -57,43 +64,78 @@ public class StartVBoxIfNotAlreadyRunning implements Supplier private final Supplier providerSupplier; private final Function, VirtualBoxManager> managerForNode; private transient VirtualBoxManager manager; + private final HardcodedHostToHostNodeMetadata hardcodedHostToHostNodeMetadata; // the functions and suppliers here are to ensure we don't do heavy i/o in injection @Inject public StartVBoxIfNotAlreadyRunning(Function, VirtualBoxManager> managerForNode, Factory runScriptOnNodeFactory, RetryIfSocketNotYetOpen socketTester, Supplier host, - @Provider Supplier providerSupplier) { + @Provider Supplier providerSupplier, + HardcodedHostToHostNodeMetadata hardcodedHostToHostNodeMetadata) { this.runScriptOnNodeFactory = checkNotNull(runScriptOnNodeFactory, "runScriptOnNodeFactory"); this.socketTester = checkNotNull(socketTester, "socketTester"); this.socketTester.seconds(3L); this.host = checkNotNull(host, "host"); this.providerSupplier = checkNotNull(providerSupplier, "endpoint to virtualbox websrvd is needed"); this.managerForNode = checkNotNull(managerForNode, "managerForNode"); - start(); + this.hardcodedHostToHostNodeMetadata = hardcodedHostToHostNodeMetadata; } + @PostConstruct public synchronized void start() { URI provider = providerSupplier.get(); - if (!socketTester.apply(HostAndPort.fromParts(provider.getHost(), provider.getPort()))) { - logger.debug("disabling password access"); - runScriptOnNodeFactory.create(host.get(), Statements.exec("VBoxManage setproperty websrvauthlibrary null"), + NodeMetadata hostNodeMetadata = hardcodedHostToHostNodeMetadata.apply(host.get()); + cleanUpHost(provider, hostNodeMetadata); + + logger.debug("disabling password access"); + runScriptOnNodeFactory + .create( + hostNodeMetadata, + Statements + .exec("VBoxManage setproperty websrvauthlibrary null"), runAsRoot(false).wrapInInitScript(false)).init().call(); - logger.debug(">> starting vboxwebsrv"); - String vboxwebsrv = "vboxwebsrv -t 10000 -v -b"; - runScriptOnNodeFactory.create(host.get(), Statements.exec(vboxwebsrv), - runAsRoot(false).wrapInInitScript(false).blockOnComplete(false).nameTask("vboxwebsrv")).init().call(); - - if (!socketTester.apply(HostAndPort.fromParts(provider.getHost(), provider.getPort()))){ - throw new RuntimeException("could not connect to virtualbox"); - } + logger.debug(">> starting vboxwebsrv"); + String vboxwebsrv = "vboxwebsrv -t0 -v -b -H " + + providerSupplier.get().getHost(); + runScriptOnNodeFactory + .create( + hostNodeMetadata, + Statements.exec(vboxwebsrv), + runAsRoot(false).wrapInInitScript(false) + .blockOnComplete(false).nameTask("vboxwebsrv")).init() + .call(); + + if (!socketTester.apply(HostAndPort.fromParts(provider.getHost(), + provider.getPort()))) { + throw new RuntimeException("could not connect to virtualbox"); } + manager = managerForNode.apply(host); manager.connect(provider.toASCIIString(), "", ""); if (logger.isDebugEnabled()) if (manager.getSessionObject().getState() != SessionState.Unlocked) - logger.warn("manager is not in unlocked state " + manager.getSessionObject().getState()); + logger.warn("manager is not in unlocked state " + + manager.getSessionObject().getState()); } + private void cleanUpHost(URI provider, NodeMetadata hostNodeMetadata) { + // kill previously started vboxwebsrv (possibly dirty session) + List statements = new ArrayList(); + statements.add(Statements.findPid("vboxwebsrv")); + statements.add(Statements.kill()); + StatementList statementList = new StatementList(statements); + + if (socketTester.apply(HostAndPort.fromParts(provider.getHost(), + provider.getPort()))) { + logger.debug(String.format("shutting down previously started vboxwewbsrv at %s", provider)); + ExecResponse execResponse = runScriptOnNodeFactory + .create(hostNodeMetadata, statementList, runAsRoot(false)) + .init().call(); + if(execResponse.getExitStatus()!=0) + throw new RuntimeException("Cannot execute jclouds"); + } + } + @Override public VirtualBoxManager get() { checkState(manager != null, "start not called"); diff --git a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/admin/UnregisterMachineIfExistsAndDeleteItsMedia.java b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/admin/UnregisterMachineIfExistsAndDeleteItsMedia.java index bc3dde9430..d530058a87 100644 --- a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/admin/UnregisterMachineIfExistsAndDeleteItsMedia.java +++ b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/admin/UnregisterMachineIfExistsAndDeleteItsMedia.java @@ -41,7 +41,6 @@ import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.Iterables.filter; import static com.google.common.collect.Iterables.transform; -import java.util.Collections; import java.util.List; import javax.annotation.Resource; @@ -62,6 +61,7 @@ import org.virtualbox_4_1.VBoxException; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.base.Throwables; +import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; @Singleton @@ -79,7 +79,7 @@ public class UnregisterMachineIfExistsAndDeleteItsMedia implements Function mediaToBeDeleted = Collections.emptyList(); + List mediaToBeDeleted = ImmutableList.of(); try { mediaToBeDeleted = machine.unregister(vmSpec.getCleanupMode()); } catch (VBoxException e) { diff --git a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/admin/UnregisterMachineIfExistsAndForceDeleteItsMedia.java b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/admin/UnregisterMachineIfExistsAndForceDeleteItsMedia.java index db2761c3c4..c0616ac121 100644 --- a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/admin/UnregisterMachineIfExistsAndForceDeleteItsMedia.java +++ b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/functions/admin/UnregisterMachineIfExistsAndForceDeleteItsMedia.java @@ -40,7 +40,6 @@ package org.jclouds.virtualbox.functions.admin; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.Iterables.transform; -import java.util.Collections; import java.util.List; import javax.annotation.Resource; @@ -59,6 +58,7 @@ import org.virtualbox_4_1.VBoxException; import com.google.common.base.Function; import com.google.common.base.Throwables; +import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; @Singleton @@ -70,7 +70,7 @@ public class UnregisterMachineIfExistsAndForceDeleteItsMedia implements Function @Override public Void apply(IMachine machine) { - List mediaToBeDeleted = Collections.emptyList(); + List mediaToBeDeleted = ImmutableList.of(); try { mediaToBeDeleted = machine.unregister(CleanupMode.Full); } catch (VBoxException e) { @@ -89,7 +89,7 @@ public class UnregisterMachineIfExistsAndForceDeleteItsMedia implements Function if (!filteredMediaToBeDeleted.isEmpty()) { try { IProgress deletion = machine.delete(filteredMediaToBeDeleted); - deletion.waitForCompletion(-1); + deletion.waitForCompletion(100); } catch (Exception e) { logger.error(e, "Problem in deleting the media attached to %s", machine.getName()); Throwables.propagate(e); diff --git a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/statements/EnableNetworkInterface.java b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/statements/EnableNetworkInterface.java index 224fd2f7f8..8a9523af99 100644 --- a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/statements/EnableNetworkInterface.java +++ b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/statements/EnableNetworkInterface.java @@ -22,13 +22,13 @@ package org.jclouds.virtualbox.statements; import static com.google.common.base.Preconditions.checkNotNull; import static org.jclouds.scriptbuilder.domain.Statements.exec; +import java.util.ArrayList; import java.util.List; import org.jclouds.scriptbuilder.domain.OsFamily; import org.jclouds.scriptbuilder.domain.Statement; import org.jclouds.scriptbuilder.domain.StatementList; import org.jclouds.virtualbox.domain.NetworkInterfaceCard; -import org.testng.collections.Lists; /** * Up the network interface chosen @@ -63,10 +63,7 @@ public class EnableNetworkInterface implements Statement { } private List getStatements(String iface) { - /* - * auto eth0 - */ - List statements = Lists.newArrayList(); + List statements = new ArrayList(); statements.add(exec(String.format("echo auto %s >> /etc/network/interfaces", iface))); // statements.add(exec(String.format("echo iface %s inet dhcp >> /etc/network/interfaces", iface))); // statements.add(exec("/etc/init.d/networking restart")); diff --git a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/statements/InstallGuestAdditions.java b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/statements/InstallGuestAdditions.java index 16861ebbf3..8c770ab81a 100644 --- a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/statements/InstallGuestAdditions.java +++ b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/statements/InstallGuestAdditions.java @@ -25,6 +25,7 @@ import static org.jclouds.scriptbuilder.domain.Statements.exec; import static org.jclouds.scriptbuilder.domain.Statements.saveHttpResponseTo; import java.net.URI; +import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; @@ -38,7 +39,6 @@ import org.jclouds.scriptbuilder.domain.StatementList; import org.jclouds.virtualbox.domain.IsoImage; import org.jclouds.virtualbox.domain.StorageController; import org.jclouds.virtualbox.domain.VmSpec; -import org.testng.collections.Lists; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; @@ -62,7 +62,7 @@ public class InstallGuestAdditions implements Statement { } private List getStatements(VmSpec vmSpecification, String vboxVersion) { - List statements = Lists.newArrayList(); + List statements = new ArrayList(); statements.add(call("installModuleAssistantIfNeeded")); String mountPoint = "/mnt"; if (Iterables.tryFind(vmSpecification.getControllers(), new Predicate() { @@ -87,12 +87,7 @@ public class InstallGuestAdditions implements Statement { statements.add(saveHttpResponseTo(download, "{tmp}{fs}", vboxGuestAdditionsIso));// statements.add(exec(String.format("mount -o loop {tmp}{fs}%s %s", vboxGuestAdditionsIso, mountPoint))); } - statements.add(exec(String.format("%s%s", mountPoint, "/VBoxLinuxAdditions.run"))); // - statements.add(exec("service vboxadd setup")); // - statements.add(exec("VBoxService")); // - statements.add(exec(String.format("echo VBoxService > /etc/rc.local"))); // - statements.add(exec(String.format("echo exit 0 >> /etc/rc.local"))); // - statements.add(exec(String.format("umount %s", mountPoint))); + statements.add(exec(String.format("%s%s", mountPoint, "/VBoxLinuxAdditions.run --nox11"))); // return statements; } diff --git a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/util/MachineController.java b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/util/MachineController.java index 3a59f68f18..5983a9e0dc 100644 --- a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/util/MachineController.java +++ b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/util/MachineController.java @@ -20,6 +20,9 @@ package org.jclouds.virtualbox.util; import static com.google.common.base.Preconditions.checkNotNull; +import java.util.List; +import java.util.concurrent.TimeUnit; + import javax.annotation.Resource; import javax.inject.Named; import javax.inject.Singleton; @@ -28,15 +31,25 @@ import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.logging.Logger; import org.jclouds.virtualbox.domain.ExecutionType; import org.jclouds.virtualbox.functions.LaunchMachineIfNotAlreadyRunning; +import org.virtualbox_4_1.AdditionsFacilityStatus; +import org.virtualbox_4_1.AdditionsFacilityType; +import org.virtualbox_4_1.AdditionsRunLevelType; +import org.virtualbox_4_1.IAdditionsFacility; +import org.virtualbox_4_1.IMachine; import org.virtualbox_4_1.IProgress; import org.virtualbox_4_1.ISession; import org.virtualbox_4_1.LockType; import org.virtualbox_4_1.MachineState; +import org.virtualbox_4_1.SessionState; import org.virtualbox_4_1.VirtualBoxManager; import com.google.common.base.Function; +import com.google.common.base.Optional; +import com.google.common.base.Predicate; +import com.google.common.base.Strings; import com.google.common.base.Supplier; -import com.google.common.base.Throwables; +import com.google.common.collect.Iterables; +import com.google.common.util.concurrent.Uninterruptibles; import com.google.inject.Inject; /** @@ -65,27 +78,57 @@ public class MachineController { public ISession ensureMachineIsLaunched(String vmName) { ISession session = null; - while (!manager.get().getVBox().findMachine(vmName).getState().equals(MachineState.Running)) { + IMachine machine = manager.get().getVBox().findMachine(vmName); + while (!machine.getState().equals(MachineState.Running)) { try { - session = machineUtils.applyForMachine(vmName, new LaunchMachineIfNotAlreadyRunning(manager.get(), - executionType, "")); + session = machineUtils.applyForMachine(vmName, + new LaunchMachineIfNotAlreadyRunning(manager.get(), + executionType, "")); } catch (RuntimeException e) { - if (e.getMessage().contains( - "org.virtualbox_4_1.VBoxException: VirtualBox error: The given session is busy (0x80BB0007)")) { + if (e.getMessage() + .contains( + "org.virtualbox_4_1.VBoxException: VirtualBox error: The given session is busy (0x80BB0007)")) { throw e; - } else if (e.getMessage().contains("VirtualBox error: The object is not ready")) { + } else if (e.getMessage().contains( + "VirtualBox error: The object is not ready")) { continue; } else { throw e; } } } + // for scancode + Uninterruptibles.sleepUninterruptibly(5, TimeUnit.SECONDS); + + String guestAdditionsInstalled = machineUtils.sharedLockMachineAndApplyToSession(vmName, + new Function() { + + @Override + public String apply(ISession session) { + int attempts = 0; + String guestAdditionsInstalled = null; + while (!!session.getConsole().getGuest() + .getAdditionsVersion().isEmpty() && attempts < 3) { + Uninterruptibles.sleepUninterruptibly(2, TimeUnit.SECONDS); + guestAdditionsInstalled = session.getConsole().getGuest() + .getAdditionsVersion(); + attempts++; + } + return guestAdditionsInstalled; + } + + }); + if(!Strings.nullToEmpty(guestAdditionsInstalled).isEmpty()) { + waitVBoxServiceIsActive(vmName); + } + return checkNotNull(session, "session"); } public ISession ensureMachineHasPowerDown(String vmName) { ISession session = manager.get().getSessionObject(); - while (!manager.get().getVBox().findMachine(vmName).getState().equals(MachineState.PoweredOff)) { + IMachine machine = manager.get().getVBox().findMachine(vmName); + while (!machine.getState().equals(MachineState.PoweredOff)) { try { session = machineUtils.lockSessionOnMachineAndApply(vmName, LockType.Shared, new Function() { @@ -97,9 +140,6 @@ public class MachineController { } }); } catch (RuntimeException e) { - // sometimes the machine might be powered of between the while - // test and the call to - // lockSessionOnMachineAndApply if (e.getMessage().contains("Invalid machine state: PoweredOff")) { throw e; } else if (e.getMessage().contains("VirtualBox error: The object is not ready")) { @@ -109,6 +149,7 @@ public class MachineController { } } } + safeCheckMachineIsUnlocked(machine); return checkNotNull(session, "session"); } @@ -117,6 +158,7 @@ public class MachineController { * http://askubuntu.com/questions/82015/shutting-down-ubuntu-server-running-in-headless-virtualbox */ public ISession ensureMachineIsShutdown(String vmName) { + IMachine machine = manager.get().getVBox().findMachine(vmName); ISession session = machineUtils.lockSessionOnMachineAndApply(vmName, LockType.Shared, new Function() { @Override @@ -125,19 +167,12 @@ public class MachineController { return session; } }); - int count = 0; - while (!manager.get().getVBox().findMachine(vmName).getState().equals(MachineState.PoweredOff) && count < 10) { - try { - Thread.sleep(500l * count); - } catch (InterruptedException e) { - Throwables.propagate(e); - } - count++; - } + safeCheckMachineIsUnlocked(machine); return checkNotNull(session, "session"); } public void ensureMachineIsPaused(String vmName) { + IMachine machine = manager.get().getVBox().findMachine(vmName); while (!manager.get().getVBox().findMachine(vmName).getState().equals(MachineState.Paused)) { try { machineUtils.lockSessionOnMachineAndApply(vmName, LockType.Shared, new Function() { @@ -160,9 +195,11 @@ public class MachineController { } } } + safeCheckMachineIsUnlocked(machine); } public void ensureMachineIsResumed(String vmName) { + IMachine machine = manager.get().getVBox().findMachine(vmName); while (!manager.get().getVBox().findMachine(vmName).getState().equals(MachineState.Running)) { try { machineUtils.lockSessionOnMachineAndApply(vmName, LockType.Shared, new Function() { @@ -185,6 +222,58 @@ public class MachineController { } } } + safeCheckMachineIsUnlocked(machine); + } + + private void safeCheckMachineIsUnlocked(IMachine machine) { + int guard = 0; + while (!machine.getSessionState().equals(SessionState.Unlocked)) { + if(guard >= 5) { + logger.warn("Machine session (%s) possibly still unlocked!!!", machine.getName()); + break; + } + logger.debug("Machine session (%s) not unlocked - wait ...", machine.getName()); + Uninterruptibles.sleepUninterruptibly(3, TimeUnit.SECONDS); + guard++; + } + logger.debug("Machine session (%s) is %s", machine.getName(), machine.getSessionState()); + } + + private void waitVBoxServiceIsActive(String vmName) { + machineUtils.sharedLockMachineAndApplyToSession(vmName, new Function() { + + @Override + public Void apply(ISession session) { + session.getConsole().getGuest().setStatisticsUpdateInterval(1l); + while (!session.getConsole().getGuest().getAdditionsStatus(AdditionsRunLevelType.Userland)) { + Uninterruptibles.sleepUninterruptibly(200, TimeUnit.MILLISECONDS); + } + + List facilities = session.getConsole().getGuest().getFacilities(); + while (facilities.size() != 4) { + Uninterruptibles.sleepUninterruptibly(200, TimeUnit.MILLISECONDS); + facilities = session.getConsole().getGuest().getFacilities(); + } + facilities = session.getConsole().getGuest().getFacilities(); + + Optional vboxServiceFacility = Optional.absent(); + while (!vboxServiceFacility.isPresent()) { + vboxServiceFacility = Iterables.tryFind(session.getConsole().getGuest().getFacilities(), + new Predicate() { + @Override + public boolean apply(IAdditionsFacility additionsFacility) { + return additionsFacility.getType().equals(AdditionsFacilityType.VBoxService); + }; + }); + } + + while(!vboxServiceFacility.get().getStatus().equals(AdditionsFacilityStatus.Active)) { + Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); + } + Uninterruptibles.sleepUninterruptibly(3, TimeUnit.SECONDS); + return null; + } + }); } } diff --git a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/util/MachineNameOrIdAndNicSlot.java b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/util/MachineNameOrIdAndNicSlot.java new file mode 100644 index 0000000000..360f08350b --- /dev/null +++ b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/util/MachineNameOrIdAndNicSlot.java @@ -0,0 +1,132 @@ +package org.jclouds.virtualbox.util; + +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 java.io.Serializable; + +import com.google.common.base.Objects; +import com.google.common.base.Splitter; +import com.google.common.collect.Iterables; + + +/** + * An immutable representation of a MachineNameOrId and NIC port. + * + *

Example usage: + *

+ * MachineNameOrIdAndNicSlot mp = MachineNameOrIdAndNicSlot.fromString("myMachine:1");
+ * hp.getMachineNameOrId();  // returns "myMachine"
+ * hp.getSlot();      // returns 1
+ * hp.toString();     // returns "myMachine:1"
+ * 
+ * + * @author Andrea Turli + */ +public final class MachineNameOrIdAndNicSlot implements Serializable { + + private static final String SEPARATOR = ":"; + +/** IMachine name or id*/ + private final String machineNameOrId; + + /** Validated NIC slot number in the range [0..3] */ + private final long slot; + + private MachineNameOrIdAndNicSlot(String machineNameOrId, long slot) { + this.machineNameOrId = machineNameOrId; + this.slot = slot; + } + + public String getMachineNameOrId() { + return machineNameOrId; + } + + public boolean hasSlot() { + return slot >= 0; + } + + public long getSlot() { + checkState(hasSlot()); + return slot; + } + + public String getSlotText() { + checkState(hasSlot()); + return String.valueOf(slot); + } + + public static MachineNameOrIdAndNicSlot fromParts(String machineNameOrId, long slot) { + checkArgument(isValidSlot(slot)); + return new MachineNameOrIdAndNicSlot(checkNotNull(machineNameOrId, "machineNameOrId"), slot); + } + + public static MachineNameOrIdAndNicSlot fromString( + String machineNameOrIdAndNicSlotString) { + checkNotNull(machineNameOrIdAndNicSlotString); + String machineNameOrId = null; + String nicSlotString = null; + + Iterable splittedString = Splitter.on(SEPARATOR).split( + machineNameOrIdAndNicSlotString); + checkState(Iterables.size(splittedString) == 2); + machineNameOrId = Iterables.get(splittedString, 0); + nicSlotString = Iterables.get(splittedString, 1); + + long slot = -1; + if (nicSlotString != null) { + checkArgument(!nicSlotString.startsWith("+"), + "Unparseable slot number: %s", nicSlotString); + try { + slot = Long.parseLong(nicSlotString); + } catch (NumberFormatException e) { + throw new IllegalArgumentException("Unparseable slot number: " + + nicSlotString); + } + checkArgument(isValidSlot(slot), "Slot number out of range: %s", + nicSlotString); + } + return new MachineNameOrIdAndNicSlot(machineNameOrId, slot); + } + + public MachineNameOrIdAndNicSlot withDefaultSlot(int defaultSlot) { + checkArgument(isValidSlot(defaultSlot)); + if (hasSlot() || slot == defaultSlot) { + return this; + } + return new MachineNameOrIdAndNicSlot(machineNameOrId, defaultSlot); + } + + @Override + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (other instanceof MachineNameOrIdAndNicSlot) { + MachineNameOrIdAndNicSlot that = (MachineNameOrIdAndNicSlot) other; + return Objects.equal(this.machineNameOrId, that.machineNameOrId) + && this.slot == that.slot; + } + return false; + } + + @Override + public int hashCode() { + return Objects.hashCode(machineNameOrId, slot); + } + + @Override + public String toString() { + return Objects.toStringHelper(this) + .add("machineNameOrId", machineNameOrId) + .add("nicSlot", slot) + .toString(); + } + + private static boolean isValidSlot(long slot) { + return slot >= 0l && slot <= 3l; + } + + private static final long serialVersionUID = 0; +} diff --git a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/util/MachineUtils.java b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/util/MachineUtils.java index 11e627949b..768ff7e501 100644 --- a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/util/MachineUtils.java +++ b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/util/MachineUtils.java @@ -21,8 +21,7 @@ package org.jclouds.virtualbox.util; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; -import java.util.regex.Matcher; -import java.util.regex.Pattern; +import java.util.concurrent.TimeUnit; import javax.annotation.Resource; import javax.inject.Named; @@ -37,6 +36,7 @@ import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.logging.Logger; import org.jclouds.scriptbuilder.domain.Statement; import org.jclouds.util.Throwables2; +import org.jclouds.virtualbox.functions.IpAddressesLoadingCache; import org.virtualbox_4_1.IMachine; import org.virtualbox_4_1.ISession; import org.virtualbox_4_1.LockType; @@ -46,8 +46,8 @@ import org.virtualbox_4_1.VirtualBoxManager; import com.google.common.base.Function; import com.google.common.base.Supplier; -import com.google.common.base.Throwables; import com.google.common.util.concurrent.ListenableFuture; +import com.google.common.util.concurrent.Uninterruptibles; import com.google.inject.Inject; /** @@ -59,6 +59,8 @@ import com.google.inject.Inject; @Singleton public class MachineUtils { + + public final String IP_V4_ADDRESS_PATTERN = "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"; @@ -69,10 +71,11 @@ public class MachineUtils { private final Supplier manager; private final Factory scriptRunner; + @Inject - public MachineUtils(Supplier manager, RunScriptOnNode.Factory scriptRunner) { - super(); + public MachineUtils(Supplier manager, RunScriptOnNode.Factory scriptRunner, + IpAddressesLoadingCache ipAddressesLoadingCache) { this.manager = manager; this.scriptRunner = scriptRunner; } @@ -179,7 +182,7 @@ public class MachineUtils { *

* Unlocks the machine before returning. * - * Tries to obtain a lock 5 times before giving up waiting 1 sec between tries. When no machine + * Tries to obtain a lock 15 times before giving up waiting 1 sec between tries. When no machine * is found null is returned. * * @param type @@ -192,24 +195,30 @@ public class MachineUtils { */ protected T lockSessionOnMachineAndApply(String machineId, LockType type, Function function) { int retries = 15; - ISession session = lockSession(machineId, type, retries); + ISession session = checkNotNull(lockSession(machineId, type, retries), "session"); try { return function.apply(session); } catch (VBoxException e) { throw new RuntimeException(String.format("error applying %s to %s with %s lock: %s", function, machineId, type, e.getMessage()), e); } finally { - if (session != null && session.getState().equals(SessionState.Locked)) - session.unlockMachine(); + if (session.getState().equals(SessionState.Locked)) { + session.unlockMachine(); + while (!session.getState().equals(SessionState.Unlocked)) { + logger.debug("Session not unlocked - wait ..."); + Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); + } + } } } private ISession lockSession(String machineId, LockType type, int retries) { int count = 0; - ISession session; + IMachine immutableMachine = manager.get().getVBox().findMachine(machineId); + ISession session = null; + while (true) { try { - IMachine immutableMachine = manager.get().getVBox().findMachine(machineId); session = manager.get().getSessionObject(); immutableMachine.lockMachine(session, type); break; @@ -219,15 +228,12 @@ public class MachineUtils { return null; } count++; - logger.warn(e, "Could not lock machine (try %d of %d). Error: %s", count, retries, e.getMessage()); + logger.debug("Could not lock machine (try %d of %d). Error: %s", count, retries, e.getMessage()); if (count == retries) { throw new RuntimeException(String.format("error locking %s with %s lock: %s", machineId, type, e.getMessage()), e); } - try { - Thread.sleep(1000L); - } catch (InterruptedException e1) { - } + Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); } } checkState(session.getState().equals(SessionState.Locked)); @@ -265,70 +271,4 @@ public class MachineUtils { || e.getMessage().contains("Could not find a registered machine with UUID {"); } - public String getIpAddressFromBridgedNIC(String machineName) { - String ip = ""; - int attempt = 0; - while (!isIpv4(ip) && attempt < 10) { - ip = this.lockSessionOnMachineAndApply(machineName, LockType.Shared, new Function() { - @Override - public String apply(ISession session) { - String ip = session.getMachine().getGuestPropertyValue("/VirtualBox/GuestInfo/Net/0/V4/IP"); - return ip; - } - }); - attempt++; - long sleepTime = 1000 * attempt; - logger.debug("Instance %s is still not ready. Attempt n:%d. Sleeping for %d millisec", machineName, attempt, - sleepTime); - try { - Thread.sleep(sleepTime); - } catch (InterruptedException e) { - Throwables.propagate(e); - } - } - return ip; - } - - private boolean isIpv4(String s) { - Pattern pattern = Pattern.compile(this.IP_V4_ADDRESS_PATTERN); - Matcher matcher = pattern.matcher(s); - return matcher.matches(); - } - - public String getIpAddressFromHostOnlyNIC(String machineName) { - // TODO using a caching mechanism to avoid to call every time this vboxmanage api call - String currentIp = "", previousIp = "1.1.1.1"; - int attempt = 0, count = 0; - while(count < 5) { - currentIp = ""; - attempt = 0; - while (!isIpv4(currentIp) && attempt < 5) { - currentIp = this.lockSessionOnMachineAndApply(machineName, LockType.Shared, new Function() { - @Override - public String apply(ISession session) { - return session.getMachine().getGuestPropertyValue("/VirtualBox/GuestInfo/Net/0/V4/IP"); - } - }); - attempt++; - } - if(previousIp.equals(currentIp)) { - count++; - delayer(500l * (count + 1)); - } else { - count = 0; - delayer(5000l); - } - previousIp = currentIp; - } - return currentIp; - } - - private void delayer(long millisec) { - try { - Thread.sleep(millisec); - } catch (InterruptedException e) { - Throwables.propagate(e); - } - } - } diff --git a/labs/virtualbox/src/main/java/org/jclouds/virtualbox/util/NetworkUtils.java b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/util/NetworkUtils.java new file mode 100644 index 0000000000..73ddb4e247 --- /dev/null +++ b/labs/virtualbox/src/main/java/org/jclouds/virtualbox/util/NetworkUtils.java @@ -0,0 +1,339 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.virtualbox.util; + +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkState; +import static org.jclouds.compute.options.RunScriptOptions.Builder.runAsRoot; + +import java.net.URI; +import java.util.List; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.annotation.Resource; +import javax.inject.Named; +import javax.inject.Singleton; + +import org.jclouds.compute.callables.RunScriptOnNode; +import org.jclouds.compute.domain.ExecResponse; +import org.jclouds.compute.domain.NodeMetadata; +import org.jclouds.compute.domain.NodeMetadataBuilder; +import org.jclouds.compute.options.RunScriptOptions; +import org.jclouds.compute.reference.ComputeServiceConstants; +import org.jclouds.location.Provider; +import org.jclouds.logging.Logger; +import org.jclouds.scriptbuilder.domain.Statements; +import org.jclouds.virtualbox.domain.BridgedIf; +import org.jclouds.virtualbox.domain.NetworkAdapter; +import org.jclouds.virtualbox.domain.NetworkInterfaceCard; +import org.jclouds.virtualbox.domain.NetworkSpec; +import org.jclouds.virtualbox.functions.IpAddressesLoadingCache; +import org.jclouds.virtualbox.functions.RetrieveActiveBridgedInterfaces; +import org.jclouds.virtualbox.statements.EnableNetworkInterface; +import org.jclouds.virtualbox.statements.GetIPAddressFromMAC; +import org.jclouds.virtualbox.statements.ScanNetworkWithPing; +import org.virtualbox_4_1.HostNetworkInterfaceType; +import org.virtualbox_4_1.IDHCPServer; +import org.virtualbox_4_1.IHostNetworkInterface; +import org.virtualbox_4_1.IMachine; +import org.virtualbox_4_1.INetworkAdapter; +import org.virtualbox_4_1.ISession; +import org.virtualbox_4_1.LockType; +import org.virtualbox_4_1.NetworkAttachmentType; +import org.virtualbox_4_1.VirtualBoxManager; + +import com.google.common.base.Function; +import com.google.common.base.Predicate; +import com.google.common.base.Supplier; +import com.google.common.base.Throwables; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Iterables; +import com.google.common.util.concurrent.Uninterruptibles; +import com.google.inject.Inject; + +/** + * Utilities to manage VirtualBox networks on guests + * + * @author Andrea Turli + */ + +@Singleton +public class NetworkUtils { + + // TODO parameterize + public static final int MASTER_PORT = 2222; + private static final String VIRTUALBOX_HOST_GATEWAY = "10.0.2.15"; + + @Resource + @Named(ComputeServiceConstants.COMPUTE_LOGGER) + protected Logger logger = Logger.NULL; + + private final Supplier manager; + private final MachineUtils machineUtils; + private final Supplier host; + private final Supplier providerSupplier; + private final IpAddressesLoadingCache ipAddressesLoadingCache; + private final RunScriptOnNode.Factory scriptRunnerFactory; + private final Supplier hostSupplier; + + @Inject + public NetworkUtils(Supplier manager, MachineUtils machineUtils, + MachineController machineController, + Supplier host, + @Provider Supplier providerSupplier, + IpAddressesLoadingCache ipAddressesLoadingCache, + Supplier hostSupplier, + RunScriptOnNode.Factory scriptRunnerFactory) { + this.manager = manager; + this.machineUtils = machineUtils; + this.host = checkNotNull(host, "host"); + this.providerSupplier = checkNotNull(providerSupplier, + "endpoint to virtualbox websrvd is needed"); + this.ipAddressesLoadingCache = ipAddressesLoadingCache; + this.scriptRunnerFactory = scriptRunnerFactory; + this.hostSupplier = hostSupplier; + } + + public NetworkSpec createNetworkSpecWhenVboxIsLocalhost() { + NetworkAdapter natAdapter = NetworkAdapter.builder() + .networkAttachmentType(NetworkAttachmentType.NAT) + .build(); + + NetworkInterfaceCard natIfaceCard = NetworkInterfaceCard.builder() + .addNetworkAdapter(natAdapter) + .slot(1L) + .build(); + NetworkAdapter hostOnlyAdapter = NetworkAdapter.builder() + .networkAttachmentType(NetworkAttachmentType.HostOnly) + .build(); + // create new hostOnly interface if needed, otherwise use the one already there with dhcp enabled ... + String hostOnlyIfName = getHostOnlyIfOrCreate(); + NetworkInterfaceCard hostOnlyIfaceCard = NetworkInterfaceCard.builder().addNetworkAdapter(hostOnlyAdapter) + .addHostInterfaceName(hostOnlyIfName).slot(0L).build(); + return createNetworkSpecForHostOnlyNATNICs(natIfaceCard, hostOnlyIfaceCard); + } + + public boolean enableNetworkInterface(NodeMetadata nodeMetadata, NetworkInterfaceCard networkInterfaceCard) { + ExecResponse execResponse = null; + try { + execResponse = machineUtils.runScriptOnNode(nodeMetadata, + new EnableNetworkInterface(networkInterfaceCard), RunScriptOptions.NONE).get(); + } catch (InterruptedException e) { + logger.error(e.getMessage()); + } catch (ExecutionException e) { + logger.error(e.getMessage()); + } + if(execResponse == null) + return false; + return execResponse.getExitStatus() == 0; + } + + private NetworkSpec createNetworkSpecForHostOnlyNATNICs(NetworkInterfaceCard natIfaceCard, + NetworkInterfaceCard hostOnlyIfaceCard) { + return NetworkSpec.builder() + .addNIC(hostOnlyIfaceCard) + .addNIC(natIfaceCard) + .build(); + } + + public String getHostOnlyIfOrCreate() { + IHostNetworkInterface availableHostInterfaceIf = returnExistingHostNetworkInterfaceWithDHCPenabledOrNull(manager + .get().getVBox().getHost().getNetworkInterfaces()); + if (availableHostInterfaceIf==null) { + final String hostOnlyIfName = createHostOnlyIf(); + assignDHCPtoHostOnlyInterface(hostOnlyIfName); + return hostOnlyIfName; + } else { + return availableHostInterfaceIf.getName(); + } + } + + private void assignDHCPtoHostOnlyInterface(final String hostOnlyIfName) { + List availableNetworkInterfaces = manager.get().getVBox().getHost() + .getNetworkInterfaces(); + + IHostNetworkInterface iHostNetworkInterfaceWithHostOnlyIfName = Iterables.getOnlyElement(Iterables.filter(availableNetworkInterfaces, new Predicate() { + + @Override + public boolean apply(IHostNetworkInterface iHostNetworkInterface) { + return iHostNetworkInterface.getName().equals(hostOnlyIfName); + } + })); + + String hostOnlyIfIpAddress = iHostNetworkInterfaceWithHostOnlyIfName.getIPAddress(); + String dhcpIpAddress = hostOnlyIfIpAddress.substring(0, hostOnlyIfIpAddress.lastIndexOf(".")) + ".254"; + String dhcpNetmask = "255.255.255.0"; + String dhcpLowerIp = hostOnlyIfIpAddress.substring(0, hostOnlyIfIpAddress.lastIndexOf(".")) + ".2"; + String dhcpUpperIp = hostOnlyIfIpAddress.substring(0, hostOnlyIfIpAddress.lastIndexOf(".")) + ".253"; + NodeMetadata hostNodeMetadata = getHostNodeMetadata(); + + ExecResponse response = scriptRunnerFactory + .create(hostNodeMetadata, + Statements.exec(String + .format("VBoxManage dhcpserver add --ifname %s --ip %s --netmask %s --lowerip %s --upperip %s --enable", + hostOnlyIfName, dhcpIpAddress, dhcpNetmask, dhcpLowerIp, dhcpUpperIp)), runAsRoot(false).wrapInInitScript(false)).init().call(); + checkState(response.getExitStatus()==0); + } + + private String createHostOnlyIf() { + final String hostOnlyIfName; + NodeMetadata hostNodeMetadata = getHostNodeMetadata(); + ExecResponse createHostOnlyResponse = scriptRunnerFactory + .create(hostNodeMetadata, Statements.exec("VBoxManage hostonlyif create"), + runAsRoot(false).wrapInInitScript(false)).init().call(); + String output = createHostOnlyResponse.getOutput(); + checkState(createHostOnlyResponse.getExitStatus()==0); + checkState(output.contains("'"), "cannot create hostonlyif"); + hostOnlyIfName = output.substring(output.indexOf("'") + 1, output.lastIndexOf("'")); + return hostOnlyIfName; + } + + private NodeMetadata getHostNodeMetadata() { + NodeMetadata hostNodeMetadata = NodeMetadataBuilder + .fromNodeMetadata(host.get()) + .publicAddresses( + ImmutableList.of(providerSupplier.get().getHost())) + .build(); + return hostNodeMetadata; + } + + private IHostNetworkInterface returnExistingHostNetworkInterfaceWithDHCPenabledOrNull(Iterable availableNetworkInterfaces) { + checkNotNull(availableNetworkInterfaces); + return Iterables.getFirst(filterAvailableNetworkInterfaceByHostOnlyAndDHCPenabled(availableNetworkInterfaces), null); + } + + /** + * @param availableNetworkInterfaces + * @param hostOnlyIfIpAddress + * @return + */ + private Iterable filterAvailableNetworkInterfaceByHostOnlyAndDHCPenabled(Iterable availableNetworkInterfaces) { + Iterable filteredNetworkInterfaces = Iterables.filter(availableNetworkInterfaces, new Predicate() { + @Override + public boolean apply(IHostNetworkInterface iHostNetworkInterface) { + // this is an horrible workaround cause iHostNetworkInterface.getDhcpEnabled is working only for windows host + boolean match = false; + List availableDHCPservers = manager.get().getVBox().getDHCPServers(); + for (IDHCPServer idhcpServer : availableDHCPservers) { + if(idhcpServer.getEnabled() && idhcpServer.getNetworkName().equals(iHostNetworkInterface.getNetworkName())) + match = true; + } + return iHostNetworkInterface.getInterfaceType().equals(HostNetworkInterfaceType.HostOnly) && + match; + } + }); + return filteredNetworkInterfaces; + } + + + public String getIpAddressFromNicSlot(String machineNameOrId, long nicSlot) { + MachineNameOrIdAndNicSlot machineNameOrIdAndNicSlot = + MachineNameOrIdAndNicSlot.fromParts(machineNameOrId, nicSlot); + logger.debug("Looking for an available IP address for %s at slot %s ...", + machineNameOrIdAndNicSlot.getMachineNameOrId(), + machineNameOrIdAndNicSlot.getSlotText()); + try { + String ipAddress = ipAddressesLoadingCache.get(machineNameOrIdAndNicSlot); + while(!isValidIpForHostOnly(machineNameOrIdAndNicSlot, ipAddress)) { + ipAddressesLoadingCache.invalidate(machineNameOrIdAndNicSlot); + ipAddress = ipAddressesLoadingCache.get(machineNameOrIdAndNicSlot); + } + logger.debug("Found an available IP address %s for guest: %s at slot: %s", + ipAddress, + machineNameOrIdAndNicSlot.getMachineNameOrId(), + machineNameOrIdAndNicSlot.getSlotText()); + return ipAddress; + } catch (ExecutionException e) { + logger.error("Problem in using the ipAddressCache", e.getCause()); + throw Throwables.propagate(e); + } + } + + public static boolean isIpv4(String s) { + String IP_V4_ADDRESS_PATTERN = "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." + + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"; + Pattern pattern = Pattern.compile(IP_V4_ADDRESS_PATTERN); + Matcher matcher = pattern.matcher(s); + return matcher.matches(); + } + + public boolean isValidIpForHostOnly(MachineNameOrIdAndNicSlot machineNameOrIdAndNicSlot, String ip) { + final String vmNameOrId = machineNameOrIdAndNicSlot.getMachineNameOrId(); + IMachine machine = manager.get().getVBox().findMachine(vmNameOrId); + long slot = machineNameOrIdAndNicSlot.getSlot(); + + if(ip.equals(VIRTUALBOX_HOST_GATEWAY) || !isValidHostOnlyIpAddress(ip, slot, machine)) { + // restart vm + logger.debug("reset node (%s) to refresh guest properties.", vmNameOrId); + machineUtils.lockSessionOnMachineAndApply(vmNameOrId, LockType.Shared, + new Function() { + @Override + public Void apply(ISession session) { + session.getConsole().reset(); + long time = 15; + logger.debug("Waiting %s secs for the reset of (%s) ...", time, vmNameOrId); + Uninterruptibles.sleepUninterruptibly(time, TimeUnit.SECONDS); + return null; + } + }); + return false; + } + return true; + } + + public static boolean isValidHostOnlyIpAddress(String ip, long slot, + IMachine machine) { + boolean result = isIpv4(ip) && machine.getNetworkAdapter(slot).getAttachmentType().equals(NetworkAttachmentType.HostOnly) + && !ipBelongsToNatRange(ip); + return result; + } + + private static boolean ipBelongsToNatRange(String ip) { + return ip.startsWith("10.0.3"); + } + + protected String getIpAddressFromBridgedNIC(INetworkAdapter networkAdapter, + String network) { + // RetrieveActiveBridgedInterfaces + List activeBridgedInterfaces = new RetrieveActiveBridgedInterfaces(scriptRunnerFactory).apply(hostSupplier.get()); + BridgedIf activeBridgedIf = checkNotNull(Iterables.get(activeBridgedInterfaces, 0), "activeBridgedInterfaces"); + network = activeBridgedIf.getIpAddress(); + + // scan ip + RunScriptOnNode ipScanRunScript = scriptRunnerFactory.create( + hostSupplier.get(), new ScanNetworkWithPing(network), + RunScriptOptions.NONE); + ExecResponse execResponse = ipScanRunScript.init().call(); + checkState(execResponse.getExitStatus() == 0); + + // retrieve ip from mac + RunScriptOnNode getIpFromMACAddressRunScript = scriptRunnerFactory + .create(hostSupplier.get(), new GetIPAddressFromMAC( + networkAdapter.getMACAddress()), + RunScriptOptions.NONE); + ExecResponse ipExecResponse = getIpFromMACAddressRunScript.init() + .call(); + checkState(ipExecResponse.getExitStatus() == 0); + return checkNotNull(ipExecResponse.getOutput(), "ipAddress"); + } +} diff --git a/labs/virtualbox/src/main/resources/default-images.yaml b/labs/virtualbox/src/main/resources/default-images.yaml index 84380c2b1f..fe4c0c82d3 100644 --- a/labs/virtualbox/src/main/resources/default-images.yaml +++ b/labs/virtualbox/src/main/resources/default-images.yaml @@ -1,4 +1,139 @@ images: + - id: ubuntu-10.04.4-server-i386 + name: ubuntu-10.04-server-i386 + description: ubuntu 10.04.4 server (i386) + os_arch: x86 + os_family: ubuntu + os_description: ubuntu + os_version: 10.04.4 + iso: http://releases.ubuntu.com/10.04.4/ubuntu-10.04.4-server-i386.iso + iso_md5: fc08a01e78348e3918180ea91a6883bb + username: toor + credential: password + keystroke_sequence: | + + /install/vmlinuz noapic preseed/url=http://10.0.2.2:8080/src/test/resources/preseed.cfg + debian-installer=en_US auto locale=en_US kbd-chooser/method=us + hostname=vmName + fb=false debconf/frontend=noninteractive + console-setup/ask_detect=false console-setup/modelcode=pc105 console-setup/layoutcode=us + initrd=/install/initrd.gz -- + preseed_cfg: | + ## Options to set on the command line + d-i debian-installer/locale string en_US + d-i console-setup/ask_detect boolean false + d-i console-setup/layoutcode string us + d-i netcfg/get_hostname string unassigned-hostname + d-i netcfg/get_domain string unassigned-domain + d-i time/zone string UTC + d-i clock-setup/utc-auto boolean true + d-i clock-setup/utc boolean true + d-i kbd-chooser/method select American English + d-i netcfg/wireless_wep string + d-i base-installer/kernel/override-image string linux-server + d-i debconf debconf/frontend select Noninteractive + d-i pkgsel/install-language-support boolean false + tasksel tasksel/first multiselect standard, ubuntu-server + d-i partman-auto/method string lvm + #d-i partman-auto/purge_lvm_from_device boolean true + d-i partman-lvm/confirm boolean true + d-i partman-lvm/device_remove_lvm boolean true + d-i partman-auto/choose_recipe select atomic + d-i partman/confirm_write_new_label boolean true + d-i partman/confirm_nooverwrite boolean true + d-i partman/choose_partition select finish + d-i partman/confirm boolean true + # Write the changes to disks and configure LVM? + d-i partman-lvm/confirm boolean true + d-i partman-lvm/confirm_nooverwrite boolean true + d-i partman-auto-lvm/guided_size string max + ## Default user, we can get away with a recipe to change this + d-i passwd/user-fullname string toor + d-i passwd/username string toor + d-i passwd/user-password password password + d-i passwd/user-password-again password password + d-i user-setup/encrypt-home boolean false + d-i user-setup/allow-password-weak boolean true + d-i pkgsel/include string openssh-server ntp + # Whether to upgrade packages after debootstrap. + # Allowed values: none, safe-upgrade, full-upgrade + d-i pkgsel/upgrade select full-upgrade + d-i grub-installer/only_debian boolean true + d-i grub-installer/with_other_os boolean true + d-i finish-install/reboot_in_progress note + #For the update + d-i pkgsel/update-policy select none + # debconf-get-selections --install + #Use mirror + choose-mirror-bin mirror/http/proxy string + - id: ubuntu-10.04.4-server-amd64 + name: ubuntu-10.04-server-amd64 + description: ubuntu 10.04.4 server (amd64) + os_arch: amd64 + os_family: ubuntu + os_description: ubuntu + os_version: 10.04.4 + os_64bit: true + iso: http://releases.ubuntu.com/10.04.4/ubuntu-10.04.4-server-amd64.iso + iso_md5: 9b218654cdcdf9722171648c52f8a088 + username: toor + credential: password + keystroke_sequence: | + + /install/vmlinuz noapic preseed/url=http://10.0.2.2:8080/src/test/resources/preseed.cfg + debian-installer=en_US auto locale=en_US kbd-chooser/method=us + hostname=vmName + fb=false debconf/frontend=noninteractive + console-setup/ask_detect=false console-setup/modelcode=pc105 console-setup/layoutcode=us + initrd=/install/initrd.gz -- + preseed_cfg: | + ## Options to set on the command line + d-i debian-installer/locale string en_US + d-i console-setup/ask_detect boolean false + d-i console-setup/layoutcode string us + d-i netcfg/get_hostname string unassigned-hostname + d-i netcfg/get_domain string unassigned-domain + d-i time/zone string UTC + d-i clock-setup/utc-auto boolean true + d-i clock-setup/utc boolean true + d-i kbd-chooser/method select American English + d-i netcfg/wireless_wep string + d-i base-installer/kernel/override-image string linux-server + d-i debconf debconf/frontend select Noninteractive + d-i pkgsel/install-language-support boolean false + tasksel tasksel/first multiselect standard, ubuntu-server + d-i partman-auto/method string lvm + #d-i partman-auto/purge_lvm_from_device boolean true + d-i partman-lvm/confirm boolean true + d-i partman-lvm/device_remove_lvm boolean true + d-i partman-auto/choose_recipe select atomic + d-i partman/confirm_write_new_label boolean true + d-i partman/confirm_nooverwrite boolean true + d-i partman/choose_partition select finish + d-i partman/confirm boolean true + # Write the changes to disks and configure LVM? + d-i partman-lvm/confirm boolean true + d-i partman-lvm/confirm_nooverwrite boolean true + d-i partman-auto-lvm/guided_size string max + ## Default user, we can get away with a recipe to change this + d-i passwd/user-fullname string toor + d-i passwd/username string toor + d-i passwd/user-password password password + d-i passwd/user-password-again password password + d-i user-setup/encrypt-home boolean false + d-i user-setup/allow-password-weak boolean true + d-i pkgsel/include string openssh-server ntp + # Whether to upgrade packages after debootstrap. + # Allowed values: none, safe-upgrade, full-upgrade + d-i pkgsel/upgrade select full-upgrade + d-i grub-installer/only_debian boolean true + d-i grub-installer/with_other_os boolean true + d-i finish-install/reboot_in_progress note + #For the update + d-i pkgsel/update-policy select none + # debconf-get-selections --install + #Use mirror + choose-mirror-bin mirror/http/proxy string - id: ubuntu-11.04-i386 name: ubuntu-11.04-server-i386 description: ubuntu 11.04 server (i386) @@ -15,7 +150,7 @@ images: fb=false debconf/frontend=noninteractive keyboard-configuration/layout=USA keyboard-configuration/variant=USA console-setup/ask_detect=false initrd=/install/initrd.gz -- - preseed_cfg: | + preseed_cfg: | ## Options to set on the command line d-i debian-installer/locale string en_US.utf8 d-i console-setup/ask_detect boolean false @@ -27,7 +162,7 @@ images: d-i time/zone string UTC d-i clock-setup/utc-auto boolean true d-i clock-setup/utc boolean true - d-i kbd-chooser/method select American English + d-i kbd-chooser/method select American English d-i netcfg/wireless_wep string d-i base-installer/kernel/override-image string linux-server # Choices: Dialog, Readline, Gnome, Kde, Editor, Noninteractive @@ -132,4 +267,92 @@ images: d-i pkgsel/update-policy select none # debconf-get-selections --install #Use mirror + choose-mirror-bin mirror/http/proxy string + - id: ubuntu-12.04.1-amd64 + name: ubuntu-12.04.1-server-amd64 + description: ubuntu 12.04.1 server (amd64) + os_arch: amd64 + os_family: ubuntu + os_description: ubuntu + os_version: 12.04.1 + os_64bit: true + iso: http://releases.ubuntu.com/12.04/ubuntu-12.04.1-server-amd64.iso + iso_md5: a8c667e871f48f3a662f3fbf1c3ddb17 + username: toor + credential: password + keystroke_sequence: | + + /install/vmlinuz noapic preseed/url=http://10.0.2.2:8080/src/test/resources/preseed.cfg + debian-installer=en_US auto locale=en_US kbd-chooser/method=us + hostname=vmName + fb=false debconf/frontend=noninteractive + keyboard-configuration/layout=USA keyboard-configuration/variant=USA console-setup/ask_detect=false + initrd=/install/initrd.gz -- + preseed_cfg: | + ## Options to set on the command line + d-i debian-installer/locale string en_US.utf8 + d-i console-setup/ask_detect boolean false + d-i console-setup/layout string USA + #d-i netcfg/get_hostname string dummy + d-i netcfg/get_hostname string unassigned-hostname + d-i netcfg/get_domain string unassigned-domain + # Continue without a default route + # Not working , specify a dummy in the DHCP + #d-i netcfg/no_default_route boolean + d-i time/zone string UTC + d-i clock-setup/utc-auto boolean true + d-i clock-setup/utc boolean true + d-i kbd-chooser/method select American English + d-i netcfg/wireless_wep string + d-i base-installer/kernel/override-image string linux-server + #d-i base-installer/kernel/override-image string linux-image-2.6.32-21-generic + # Choices: Dialog, Readline, Gnome, Kde, Editor, Noninteractive + d-i debconf debconf/frontend select Noninteractive + d-i pkgsel/install-language-support boolean false + tasksel tasksel/first multiselect standard, ubuntu-server + #d-i partman-auto/method string regular + d-i partman-auto/method string lvm + #d-i partman-auto/purge_lvm_from_device boolean true + d-i partman-lvm/confirm boolean true + d-i partman-lvm/device_remove_lvm boolean true + d-i partman-auto/choose_recipe select atomic + d-i partman/confirm_write_new_label boolean true + d-i partman/confirm_nooverwrite boolean true + d-i partman/choose_partition select finish + d-i partman/confirm boolean true + #http://ubuntu-virginia.ubuntuforums.org/showthread.php?p=9626883 + #Message: "write the changes to disk and configure lvm preseed" + #http://serverfault.com/questions/189328/ubuntu-kickstart-installation-using-lvm-waits-for-input + #preseed partman-lvm/confirm_nooverwrite boolean true + # Write the changes to disks and configure LVM? + d-i partman-lvm/confirm boolean true + d-i partman-lvm/confirm_nooverwrite boolean true + d-i partman-auto-lvm/guided_size string max + ## Default user, we can get away with a recipe to change this + d-i passwd/user-fullname string toor + d-i passwd/username string toor + d-i passwd/user-password password password + d-i passwd/user-password-again password password + d-i user-setup/encrypt-home boolean false + d-i user-setup/allow-password-weak boolean true + ## minimum is ssh and ntp + # Individual additional packages to install + d-i pkgsel/include string openssh-server ntp + # Whether to upgrade packages after debootstrap. + # Allowed values: none, safe-upgrade, full-upgrade + d-i pkgsel/upgrade select full-upgrade + d-i grub-installer/only_debian boolean true + d-i grub-installer/with_other_os boolean true + d-i finish-install/reboot_in_progress note + #For the update + d-i pkgsel/update-policy select none + # debconf-get-selections --install + #Use mirror + #d-i apt-setup/use_mirror boolean true + #d-i mirror/country string manual + #choose-mirror-bin mirror/protocol string http + #choose-mirror-bin mirror/http/hostname string 192.168.4.150 + #choose-mirror-bin mirror/http/directory string /ubuntu + #choose-mirror-bin mirror/suite select maverick + #d-i debian-installer/allow_unauthenticated string true choose-mirror-bin mirror/http/proxy string \ No newline at end of file diff --git a/labs/virtualbox/src/test/java/org/jclouds/virtualbox/BaseVirtualBoxClientLiveTest.java b/labs/virtualbox/src/test/java/org/jclouds/virtualbox/BaseVirtualBoxClientLiveTest.java index b2c2c45213..9ab564dfc2 100644 --- a/labs/virtualbox/src/test/java/org/jclouds/virtualbox/BaseVirtualBoxClientLiveTest.java +++ b/labs/virtualbox/src/test/java/org/jclouds/virtualbox/BaseVirtualBoxClientLiveTest.java @@ -25,6 +25,7 @@ import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_INSTA import java.io.File; import java.util.concurrent.ExecutorService; +import java.util.concurrent.TimeUnit; import javax.inject.Inject; import javax.inject.Named; @@ -53,6 +54,7 @@ import org.jclouds.virtualbox.functions.IMachineToVmSpec; import org.jclouds.virtualbox.functions.admin.UnregisterMachineIfExistsAndDeleteItsMedia; import org.jclouds.virtualbox.util.MachineController; import org.jclouds.virtualbox.util.MachineUtils; +import org.jclouds.virtualbox.util.NetworkUtils; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeClass; @@ -71,6 +73,7 @@ import com.google.common.base.Supplier; import com.google.common.cache.LoadingCache; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; +import com.google.common.util.concurrent.Uninterruptibles; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.Module; @@ -103,6 +106,9 @@ public class BaseVirtualBoxClientLiveTest extends BaseComputeServiceContextLiveT @Inject protected MachineUtils machineUtils; + + @Inject + protected NetworkUtils networkUtils; protected String hostVersion; protected String operatingSystemIso; @@ -119,7 +125,7 @@ public class BaseVirtualBoxClientLiveTest extends BaseComputeServiceContextLiveT protected LoadingCache mastersCache; private final ExecutorService singleThreadExec = MoreExecutors.sameThreadExecutor(); - private String masterVmName; + private String masterName; @Override @@ -133,13 +139,13 @@ public class BaseVirtualBoxClientLiveTest extends BaseComputeServiceContextLiveT public void setupContext() { super.setupContext(); view.utils().injector().injectMembers(this); - + // try and get a master from the cache, this will initialize the config/download isos and // prepare everything IF a master is not available, subsequent calls should be pretty fast Template template = view.getComputeService().templateBuilder().build(); checkNotNull(mastersCache.apply(template.getImage())); - masterVmName = VIRTUALBOX_IMAGE_PREFIX + template.getImage().getId(); + masterName = VIRTUALBOX_IMAGE_PREFIX + template.getImage().getId(); isosDir = workingDir + File.separator + "isos"; hostVersion = Iterables.get(Splitter.on('r').split(view.utils().injector().getInstance(Key.get(String.class, BuildVersion.class))), 0); @@ -155,10 +161,7 @@ public class BaseVirtualBoxClientLiveTest extends BaseComputeServiceContextLiveT int attempts = 0; while (attempts < 10 && !vm.getSessionState().equals(SessionState.Unlocked)) { attempts++; - try { - Thread.sleep(200l); - } catch (InterruptedException e) { - } + Uninterruptibles.sleepUninterruptibly(200, TimeUnit.MILLISECONDS); } machineUtils.applyForMachine(vmNameOrId, new UnregisterMachineIfExistsAndDeleteItsMedia(vmSpec)); @@ -173,8 +176,6 @@ public class BaseVirtualBoxClientLiveTest extends BaseComputeServiceContextLiveT } public MasterSpec getMasterSpecForTest() { - String masterName = "jclouds-image-0x0-" + template.getImageId(); - StorageController ideController = StorageController .builder() .name("IDE Controller") @@ -220,7 +221,7 @@ public class BaseVirtualBoxClientLiveTest extends BaseComputeServiceContextLiveT protected void destroyMaster() { if (System.getProperty(DONT_DESTROY_MASTER) == null || !Boolean.parseBoolean(System.getProperty(DONT_DESTROY_MASTER))) { - undoVm(masterVmName); + undoVm(masterName); } } diff --git a/labs/virtualbox/src/test/java/org/jclouds/virtualbox/PreseedCfgServerTest.java b/labs/virtualbox/src/test/java/org/jclouds/virtualbox/PreseedCfgServerTest.java index 28c6001f9e..ad71c22e3f 100644 --- a/labs/virtualbox/src/test/java/org/jclouds/virtualbox/PreseedCfgServerTest.java +++ b/labs/virtualbox/src/test/java/org/jclouds/virtualbox/PreseedCfgServerTest.java @@ -20,7 +20,6 @@ package org.jclouds.virtualbox; import static org.testng.Assert.assertEquals; -import java.io.File; import java.net.URI; import java.net.URL; import java.util.Map; diff --git a/labs/virtualbox/src/test/java/org/jclouds/virtualbox/compute/VirtualBoxComputeServiceAdapterLiveTest.java b/labs/virtualbox/src/test/java/org/jclouds/virtualbox/compute/VirtualBoxComputeServiceAdapterLiveTest.java index cf3969d5bd..7cdee2d010 100644 --- a/labs/virtualbox/src/test/java/org/jclouds/virtualbox/compute/VirtualBoxComputeServiceAdapterLiveTest.java +++ b/labs/virtualbox/src/test/java/org/jclouds/virtualbox/compute/VirtualBoxComputeServiceAdapterLiveTest.java @@ -51,7 +51,7 @@ public class VirtualBoxComputeServiceAdapterLiveTest extends BaseVirtualBoxClien @Test public void testCreatedNodeHasExpectedNameAndWeCanConnectViaSsh() { String group = "foo"; - String name = "foo-ef4"; + String name = "foo-ef9"; Template template = view.getComputeService().templateBuilder().build(); machine = adapter.createNodeWithGroupEncodedIntoName(group, name, template); assertTrue(machine.getNode().getName().contains(group)); @@ -60,7 +60,7 @@ public class VirtualBoxComputeServiceAdapterLiveTest extends BaseVirtualBoxClien doConnectViaSsh(machine.getNode(), prioritizeCredentialsFromTemplate.apply(template, machine.getCredentials())); } - protected void doConnectViaSsh(IMachine machine, LoginCredentials creds) { + protected void doConnectViaSsh(IMachine machine, LoginCredentials creds) { SshClient ssh = view.utils().injector().getInstance(IMachineToSshClient.class).apply(machine); try { ssh.connect(); diff --git a/labs/virtualbox/src/test/java/org/jclouds/virtualbox/compute/VirtualBoxExperimentLiveTest.java b/labs/virtualbox/src/test/java/org/jclouds/virtualbox/compute/VirtualBoxExperimentLiveTest.java index b2929b4a09..8a06eee51c 100644 --- a/labs/virtualbox/src/test/java/org/jclouds/virtualbox/compute/VirtualBoxExperimentLiveTest.java +++ b/labs/virtualbox/src/test/java/org/jclouds/virtualbox/compute/VirtualBoxExperimentLiveTest.java @@ -51,7 +51,7 @@ import com.google.inject.Module; * * @author Adrian Cole */ -@Test(groups = "live", singleThreaded = true, testName = "VirtualBoxExperimentLiveTest") +@Test(groups = "live", testName = "VirtualBoxExperimentLiveTest") public class VirtualBoxExperimentLiveTest extends BaseVirtualBoxClientLiveTest { @Resource @@ -69,10 +69,10 @@ public class VirtualBoxExperimentLiveTest extends BaseVirtualBoxClientLiveTest { @Test public void testLaunchCluster() throws RunNodesException { - int numNodes = 2; + int numNodes = 3; final String clusterName = "test-launch-cluster"; Set nodes = context.getComputeService().createNodesInGroup(clusterName, numNodes, - TemplateOptions.Builder.runScript(AdminAccess.standard())); + TemplateOptions.Builder.overrideLoginUser("toor").runScript(AdminAccess.standard())); assertEquals(numNodes, nodes.size(), "wrong number of nodes"); for (NodeMetadata node : nodes) { assertTrue(node.getGroup().equals("test-launch-cluster")); diff --git a/labs/virtualbox/src/test/java/org/jclouds/virtualbox/compute/extensions/VirtualBoxImageExtensionLiveTest.java b/labs/virtualbox/src/test/java/org/jclouds/virtualbox/compute/extensions/VirtualBoxImageExtensionLiveTest.java index 31a416b4a7..575a182944 100644 --- a/labs/virtualbox/src/test/java/org/jclouds/virtualbox/compute/extensions/VirtualBoxImageExtensionLiveTest.java +++ b/labs/virtualbox/src/test/java/org/jclouds/virtualbox/compute/extensions/VirtualBoxImageExtensionLiveTest.java @@ -19,6 +19,9 @@ package org.jclouds.virtualbox.compute.extensions; +import java.util.concurrent.ExecutionException; + +import org.jclouds.compute.RunNodesException; import org.jclouds.compute.extensions.internal.BaseImageExtensionLiveTest; import org.jclouds.sshj.config.SshjSshClientModule; import org.testng.annotations.Test; @@ -28,6 +31,22 @@ import com.google.inject.Module; @Test(groups = "live", singleThreaded = true, testName = "VirtualBoxImageExtensionLiveTest") public class VirtualBoxImageExtensionLiveTest extends BaseImageExtensionLiveTest { + @Override + public void testDeleteImage() { + // TODO + } + + @Override + public void testCreateImage() throws RunNodesException, + InterruptedException, ExecutionException { + // TODO + } + + @Override + public void testSpawnNodeFromImage() throws RunNodesException { + // TODO + } + public VirtualBoxImageExtensionLiveTest() { provider = "virtualbox"; } diff --git a/labs/virtualbox/src/test/java/org/jclouds/virtualbox/domain/ExportIpAddressForVMNamedTest.java b/labs/virtualbox/src/test/java/org/jclouds/virtualbox/domain/ExportIpAddressForVMNamedTest.java index 33843e9c13..b8082b174a 100644 --- a/labs/virtualbox/src/test/java/org/jclouds/virtualbox/domain/ExportIpAddressForVMNamedTest.java +++ b/labs/virtualbox/src/test/java/org/jclouds/virtualbox/domain/ExportIpAddressForVMNamedTest.java @@ -30,7 +30,6 @@ import org.jclouds.scriptbuilder.domain.ShellToken; import org.testng.annotations.Test; import com.google.common.base.Charsets; -import com.google.common.io.CharStreams; import com.google.common.io.Resources; /** @@ -44,7 +43,7 @@ public class ExportIpAddressForVMNamedTest { .addStatement(interpret("echo {varl}FOUND_IP_ADDRESS{varr}{lf}")); public void testUNIX() throws IOException { - assertEquals(exportIpAddressForVMNamedBuilder.render(OsFamily.UNIX), CharStreams.toString(Resources.newReaderSupplier(Resources - .getResource("test_export_ip_address_from_vm_named." + ShellToken.SH.to(OsFamily.UNIX)), Charsets.UTF_8))); + assertEquals(exportIpAddressForVMNamedBuilder.render(OsFamily.UNIX), Resources.toString(Resources.getResource( + "test_export_ip_address_from_vm_named." + ShellToken.SH.to(OsFamily.UNIX)), Charsets.UTF_8)); } -} \ No newline at end of file +} diff --git a/labs/virtualbox/src/test/java/org/jclouds/virtualbox/functions/CreateAndInstallVmLiveTest.java b/labs/virtualbox/src/test/java/org/jclouds/virtualbox/functions/CreateAndInstallVmLiveTest.java index c5576209d3..bd25a24cff 100644 --- a/labs/virtualbox/src/test/java/org/jclouds/virtualbox/functions/CreateAndInstallVmLiveTest.java +++ b/labs/virtualbox/src/test/java/org/jclouds/virtualbox/functions/CreateAndInstallVmLiveTest.java @@ -24,14 +24,18 @@ import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_IMAGE import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_INSTALLATION_KEY_SEQUENCE; import static org.testng.Assert.assertTrue; +import java.net.URI; import java.util.Map; +import javax.inject.Inject; + import org.jclouds.compute.config.BaseComputeServiceContextModule; import org.jclouds.compute.domain.OsFamily; import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.config.ValueOfConfigurationKeyOrNull; import org.jclouds.json.Json; import org.jclouds.json.config.GsonModule; +import org.jclouds.location.Provider; import org.jclouds.ssh.SshClient; import org.jclouds.virtualbox.BaseVirtualBoxClientLiveTest; import org.jclouds.virtualbox.domain.CloneSpec; @@ -49,13 +53,13 @@ import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.virtualbox_4_1.CleanupMode; import org.virtualbox_4_1.IMachine; -import org.virtualbox_4_1.ISession; import org.virtualbox_4_1.NetworkAttachmentType; import org.virtualbox_4_1.StorageBus; import com.google.common.base.CaseFormat; import com.google.common.base.Function; import com.google.common.base.Predicate; +import com.google.common.base.Supplier; import com.google.common.collect.ImmutableSet; import com.google.inject.Guice; import com.google.inject.Injector; @@ -76,44 +80,11 @@ public class CreateAndInstallVmLiveTest extends BaseVirtualBoxClientLiveTest { private MasterSpec machineSpec; private String instanceName; - - /* - @Override - @BeforeClass(groups = "live") - public void setupClient() { - super.setupClient(); - this.vmName = VIRTUALBOX_IMAGE_PREFIX - + CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, getClass().getSimpleName()); - - HardDisk hardDisk = HardDisk.builder().diskpath(adminDisk(vmName)).autoDelete(true).controllerPort(0) - .deviceSlot(1).build(); - StorageController ideController = StorageController.builder().name("IDE Controller").bus(StorageBus.IDE) - .attachISO(0, 0, operatingSystemIso).attachHardDisk(hardDisk).attachISO(1, 1, guestAdditionsIso).build(); - vmSpecification = VmSpec.builder().id(vmName).name(vmName).memoryMB(512).osTypeId("").controller(ideController) - .forceOverwrite(true).cleanUpMode(CleanupMode.Full).build(); - - injector = context.utils().injector(); - Function configProperties = injector.getInstance(ValueOfConfigurationKeyOrNull.class); - - NetworkAdapter natAdapter = NetworkAdapter.builder().networkAttachmentType(NetworkAttachmentType.NAT) - .tcpRedirectRule("127.0.0.1", 2222, "", 22).build(); - - NetworkInterfaceCard networkInterfaceCard1 = NetworkInterfaceCard.builder().slot(0l) - .addNetworkAdapter(natAdapter).build(); - - NetworkSpec networkSpec = NetworkSpec.builder().addNIC(networkInterfaceCard1).build(); - - masterSpec = MasterSpec - .builder() - .vm(vmSpecification) - .iso(IsoSpec - .builder() - .sourcePath(operatingSystemIso) - .installationScript( - configProperties.apply(VIRTUALBOX_INSTALLATION_KEY_SEQUENCE).replace("HOSTNAME", - vmSpecification.getVmName())).build()).network(networkSpec).build(); - }*/ + @Inject + @Provider + protected Supplier providerSupplier; + @Override @BeforeClass(groups = "live") public void setupContext() { @@ -142,11 +113,10 @@ public class CreateAndInstallVmLiveTest extends BaseVirtualBoxClientLiveTest { configProperties.apply(VIRTUALBOX_INSTALLATION_KEY_SEQUENCE).replace("HOSTNAME", instanceVmSpec.getVmName())).build(); - NetworkAdapter networkAdapter = NetworkAdapter.builder().networkAttachmentType(NetworkAttachmentType.NAT) - .tcpRedirectRule("127.0.0.1", 2222, "", 22).build(); - NetworkInterfaceCard networkInterfaceCard = NetworkInterfaceCard.builder().addNetworkAdapter(networkAdapter) + NetworkAdapter networkAdapter = NetworkAdapter.builder().networkAttachmentType(NetworkAttachmentType.HostOnly) .build(); - + NetworkInterfaceCard networkInterfaceCard = NetworkInterfaceCard.builder().addNetworkAdapter(networkAdapter) + .addHostInterfaceName("vboxnet0").slot(0L).build(); NetworkSpec networkSpec = NetworkSpec.builder().addNIC(networkInterfaceCard).build(); machineSpec = MasterSpec.builder().iso(isoSpec).vm(instanceVmSpec).network(networkSpec).build(); } @@ -164,12 +134,7 @@ public class CreateAndInstallVmLiveTest extends BaseVirtualBoxClientLiveTest { checkState(sshResponds.apply(client), "timed out waiting for guest %s to be accessible via ssh", machine.getName()); - String version = machineUtils.sharedLockMachineAndApplyToSession(machine.getName(), new Function() { - @Override - public String apply(ISession session) { - return session.getMachine().getGuestPropertyValue("/VirtualBox/GuestAdd/Version"); - } - }); + String version = machine.getGuestPropertyValue("/VirtualBox/GuestAdd/Version"); assertTrue(version != null && !version.isEmpty()); } finally { @@ -193,7 +158,6 @@ public class CreateAndInstallVmLiveTest extends BaseVirtualBoxClientLiveTest { Injector injector = view.utils().injector(); return injector.getInstance(CreateAndInstallVm.class).apply(masterSpecForTest); } catch (IllegalStateException e) { - // already created return manager.get().getVBox().findMachine(masterSpecForTest.getVmSpec().getVmId()); } } diff --git a/labs/virtualbox/src/test/java/org/jclouds/virtualbox/functions/IMachineToNodeMetadataTest.java b/labs/virtualbox/src/test/java/org/jclouds/virtualbox/functions/IMachineToNodeMetadataTest.java index 5a0167a14a..274c28c45c 100644 --- a/labs/virtualbox/src/test/java/org/jclouds/virtualbox/functions/IMachineToNodeMetadataTest.java +++ b/labs/virtualbox/src/test/java/org/jclouds/virtualbox/functions/IMachineToNodeMetadataTest.java @@ -30,7 +30,7 @@ import static org.testng.Assert.assertEquals; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.virtualbox.config.VirtualBoxComputeServiceContextModule; -import org.jclouds.virtualbox.util.MachineUtils; +import org.jclouds.virtualbox.util.NetworkUtils; import org.testng.annotations.Test; import org.virtualbox_4_1.IMachine; import org.virtualbox_4_1.INATEngine; @@ -64,18 +64,18 @@ public class IMachineToNodeMetadataTest { expect(natEng.getRedirects()).andReturn(ImmutableList.of("0,1,127.0.0.1,2222,,22")); INetworkAdapter hostOnly = createNiceMock(INetworkAdapter.class); - MachineUtils machineUtils = createNiceMock(MachineUtils.class); + NetworkUtils networkUtils = createNiceMock(NetworkUtils.class); - replay(vm, nat, natEng, hostOnly, machineUtils); + replay(vm, nat, natEng, hostOnly, networkUtils); NodeMetadata node = new IMachineToNodeMetadata(VirtualBoxComputeServiceContextModule.toPortableNodeStatus, - machineUtils).apply(vm); + networkUtils).apply(vm); assertEquals(MASTER_NAME, node.getName()); assertEquals(1, node.getPrivateAddresses().size()); assertEquals(1, node.getPublicAddresses().size()); assertEquals("127.0.0.1", Iterables.get(node.getPublicAddresses(), 0)); - assertEquals(MastersLoadingCache.MASTER_PORT, node.getLoginPort()); + assertEquals(NetworkUtils.MASTER_PORT, node.getLoginPort()); assertEquals("", node.getGroup()); } @@ -103,12 +103,12 @@ public class IMachineToNodeMetadataTest { expect(nat.getNatDriver()).andReturn(natEng).anyTimes(); expect(natEng.getHostIP()).andReturn("127.0.0.1").once(); expect(natEng.getRedirects()).andReturn(ImmutableList.of("0,1,127.0.0.1,3000,,22")); - MachineUtils machineUtils = createNiceMock(MachineUtils.class); + NetworkUtils networkUtils = createNiceMock(NetworkUtils.class); - replay(vm, nat, natEng, hostOnly, machineUtils); + replay(vm, nat, natEng, hostOnly, networkUtils); NodeMetadata node = new IMachineToNodeMetadata(VirtualBoxComputeServiceContextModule.toPortableNodeStatus, - machineUtils).apply(vm); + networkUtils).apply(vm); assertEquals(name, node.getName()); assertEquals(group, node.getGroup()); diff --git a/labs/virtualbox/src/test/java/org/jclouds/virtualbox/functions/admin/ImageFromYamlStringTest.java b/labs/virtualbox/src/test/java/org/jclouds/virtualbox/functions/admin/ImageFromYamlStringTest.java index 843071ad80..0e4b3ef2f8 100644 --- a/labs/virtualbox/src/test/java/org/jclouds/virtualbox/functions/admin/ImageFromYamlStringTest.java +++ b/labs/virtualbox/src/test/java/org/jclouds/virtualbox/functions/admin/ImageFromYamlStringTest.java @@ -41,11 +41,11 @@ import com.google.common.collect.Iterables; public class ImageFromYamlStringTest { public static final Image TEST1 = new ImageBuilder() - .id("ubuntu-11.04-i386") - .name("ubuntu-11.04-server-i386") - .description("ubuntu 11.04 server (i386)") + .id("ubuntu-10.04.4-server-i386") + .name("ubuntu-10.04-server-i386") + .description("ubuntu") .operatingSystem( - OperatingSystem.builder().description("ubuntu").family(OsFamily.UBUNTU).version("11.04") + OperatingSystem.builder().description("ubuntu").family(OsFamily.UBUNTU).version("10.04.4") .arch("x86").build()) .status(Image.Status.AVAILABLE).build(); diff --git a/labs/virtualbox/src/test/java/org/jclouds/virtualbox/functions/admin/StartVBoxIfNotAlreadyRunningLiveTest.java b/labs/virtualbox/src/test/java/org/jclouds/virtualbox/functions/admin/StartVBoxIfNotAlreadyRunningLiveTest.java index b3b31da7d1..22016b2c20 100644 --- a/labs/virtualbox/src/test/java/org/jclouds/virtualbox/functions/admin/StartVBoxIfNotAlreadyRunningLiveTest.java +++ b/labs/virtualbox/src/test/java/org/jclouds/virtualbox/functions/admin/StartVBoxIfNotAlreadyRunningLiveTest.java @@ -64,7 +64,7 @@ public class StartVBoxIfNotAlreadyRunningLiveTest { replay(manager, runScriptOnNodeFactory, client); new StartVBoxIfNotAlreadyRunning((Function) Functions.constant(manager), runScriptOnNodeFactory, client, - Suppliers.ofInstance(host), Suppliers.ofInstance(provider)).start(); + Suppliers.ofInstance(host), Suppliers.ofInstance(provider), null).start(); verify(manager, runScriptOnNodeFactory, client); @@ -84,26 +84,26 @@ public class StartVBoxIfNotAlreadyRunningLiveTest { expect(client.seconds(3)).andReturn(client); expect(client.apply(HostAndPort.fromParts(provider.getHost(), provider.getPort()))).andReturn(false).once().andReturn(true).once(); - expect( - runScriptOnNodeFactory.create(host, Statements.exec("VBoxManage setproperty websrvauthlibrary null"), + expect(runScriptOnNodeFactory.create(host, + Statements.exec("VBoxManage setproperty websrvauthlibrary null"), runAsRoot(false).wrapInInitScript(false))).andReturn(runScriptOnNode); expect(runScriptOnNode.init()).andReturn(runScriptOnNode); expect(runScriptOnNode.call()).andReturn(new ExecResponse("", "", 0)); - expect( - runScriptOnNodeFactory.create(host, Statements.exec("vboxwebsrv -t 10000 -v -b"), runAsRoot(false) - .wrapInInitScript(false).blockOnComplete(false).nameTask("vboxwebsrv"))).andReturn( - runScriptOnNode); + expect(runScriptOnNodeFactory.create(host, + Statements.exec("vboxwebsrv -t 10000 -v -b -H localhost"), runAsRoot(false) + .wrapInInitScript(false).blockOnComplete(false).nameTask("vboxwebsrv"))) + .andReturn(runScriptOnNode); expect(runScriptOnNode.init()).andReturn(runScriptOnNode); expect(runScriptOnNode.call()).andReturn(new ExecResponse("", "", 0)); - manager.connect(provider.toASCIIString(), "", ""); + expectLastCall().anyTimes(); replay(manager, runScriptOnNodeFactory, runScriptOnNode, client); new StartVBoxIfNotAlreadyRunning((Function) Functions.constant(manager), runScriptOnNodeFactory, client, - Suppliers.ofInstance(host), Suppliers.ofInstance(provider)); + Suppliers.ofInstance(host), Suppliers.ofInstance(provider), null); + verify(manager, runScriptOnNodeFactory, runScriptOnNode, client); - } } \ No newline at end of file diff --git a/labs/virtualbox/src/test/java/org/jclouds/virtualbox/predicates/GuestAdditionsInstallerLiveTest.java b/labs/virtualbox/src/test/java/org/jclouds/virtualbox/predicates/GuestAdditionsInstallerLiveTest.java index 8c79df17fb..13514c8af3 100644 --- a/labs/virtualbox/src/test/java/org/jclouds/virtualbox/predicates/GuestAdditionsInstallerLiveTest.java +++ b/labs/virtualbox/src/test/java/org/jclouds/virtualbox/predicates/GuestAdditionsInstallerLiveTest.java @@ -24,9 +24,6 @@ import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_IMAGE import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_INSTALLATION_KEY_SEQUENCE; import static org.testng.Assert.assertTrue; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - import org.jclouds.config.ValueOfConfigurationKeyOrNull; import org.jclouds.ssh.SshClient; import org.jclouds.virtualbox.BaseVirtualBoxClientLiveTest; @@ -42,11 +39,11 @@ import org.jclouds.virtualbox.domain.VmSpec; import org.jclouds.virtualbox.functions.CloneAndRegisterMachineFromIMachineIfNotAlreadyExists; import org.jclouds.virtualbox.functions.CreateAndInstallVm; import org.jclouds.virtualbox.functions.IMachineToSshClient; +import org.jclouds.virtualbox.util.NetworkUtils; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.virtualbox_4_1.CleanupMode; import org.virtualbox_4_1.IMachine; -import org.virtualbox_4_1.ISession; import org.virtualbox_4_1.NetworkAttachmentType; import org.virtualbox_4_1.StorageBus; @@ -59,7 +56,7 @@ import com.google.inject.Injector; /** * @author Andrea Turli */ -@Test(groups = "live", singleThreaded = true, testName = "GuestAdditionsInstallerLiveTest") +@Test(groups = "live", singleThreaded = true, testName = "GuestAdditionsInstallerLiveTest", enabled=false) public class GuestAdditionsInstallerLiveTest extends BaseVirtualBoxClientLiveTest { private Injector injector; @@ -118,21 +115,9 @@ public class GuestAdditionsInstallerLiveTest extends BaseVirtualBoxClientLiveTes sshResponds = injector.getInstance(SshResponds.class); checkState(sshResponds.apply(client), "timed out waiting for guest %s to be accessible via ssh", machine.getName()); + + assertTrue(NetworkUtils.isIpv4(networkUtils.getIpAddressFromNicSlot(machine.getName(), 0l))); - assertTrue(machineUtils.sharedLockMachineAndApplyToSession(machine.getName(), - new Function() { - @Override - public Boolean apply(ISession session) { - String s = session.getMachine().getGuestPropertyValue("/VirtualBox/GuestInfo/Net/0/V4/IP"); - return isIpv4(s); - } - - private boolean isIpv4(String s) { - Pattern pattern = Pattern.compile(machineUtils.IP_V4_ADDRESS_PATTERN); - Matcher matcher = pattern.matcher(s); - return matcher.matches(); - } - })); } finally { for (String vmNameOrId : ImmutableSet.of(machine.getName())) { machineController.ensureMachineHasPowerDown(vmNameOrId); diff --git a/labs/virtualbox/src/test/java/org/jclouds/virtualbox/statements/InstallGuestAdditionsLiveTest.java b/labs/virtualbox/src/test/java/org/jclouds/virtualbox/statements/InstallGuestAdditionsLiveTest.java index dff4c41464..e9993057a0 100644 --- a/labs/virtualbox/src/test/java/org/jclouds/virtualbox/statements/InstallGuestAdditionsLiveTest.java +++ b/labs/virtualbox/src/test/java/org/jclouds/virtualbox/statements/InstallGuestAdditionsLiveTest.java @@ -45,13 +45,7 @@ public class InstallGuestAdditionsLiveTest extends BaseVirtualBoxClientLiveTest InstallGuestAdditions installer = new InstallGuestAdditions(vmSpecification, "4.1.8"); String scripts = installer.render(OsFamily.UNIX); assertEquals("installModuleAssistantIfNeeded || return 1\n" + "mount -t iso9660 /dev/sr1 /mnt\n" - + "/mnt/VBoxLinuxAdditions.run\n" - + "service vboxadd setup\n" - + "VBoxService\n" - + "echo VBoxService > /etc/rc.local\n" - + "echo exit 0 >> /etc/rc.local\n" - + "umount /mnt\n" - , scripts); + + "/mnt/VBoxLinuxAdditions.run --nox11\n", scripts); } public void testIsoNotPresent() { @@ -67,12 +61,7 @@ public class InstallGuestAdditionsLiveTest extends BaseVirtualBoxClientLiveTest + "setupPublicCurl || return 1\n" + "(mkdir -p /tmp/ && cd /tmp/ && [ ! -f VBoxGuestAdditions_4.1.8.iso ] && curl -q -s -S -L --connect-timeout 10 --max-time 600 --retry 20 -C - -X GET http://download.virtualbox.org/virtualbox/4.1.8/VBoxGuestAdditions_4.1.8.iso >VBoxGuestAdditions_4.1.8.iso)\n" + "mount -o loop /tmp/VBoxGuestAdditions_4.1.8.iso /mnt\n" - + "/mnt/VBoxLinuxAdditions.run\n" - + "service vboxadd setup\n" - + "VBoxService\n" - + "echo VBoxService > /etc/rc.local\n" - + "echo exit 0 >> /etc/rc.local\n" - + "umount /mnt\n", scripts); + + "/mnt/VBoxLinuxAdditions.run --nox11\n", scripts); } } \ No newline at end of file diff --git a/labs/virtualbox/src/test/java/org/jclouds/virtualbox/util/MachineControllerLiveTest.java b/labs/virtualbox/src/test/java/org/jclouds/virtualbox/util/MachineControllerLiveTest.java index 2291d625c7..6b15823488 100644 --- a/labs/virtualbox/src/test/java/org/jclouds/virtualbox/util/MachineControllerLiveTest.java +++ b/labs/virtualbox/src/test/java/org/jclouds/virtualbox/util/MachineControllerLiveTest.java @@ -77,21 +77,25 @@ public class MachineControllerLiveTest extends BaseVirtualBoxClientLiveTest { .cleanUpMode(CleanupMode.Full).controller(ideController).forceOverwrite(true).build(); Injector injector = view.utils().injector(); - Function configProperties = injector.getInstance(ValueOfConfigurationKeyOrNull.class); + Function configProperties = injector + .getInstance(ValueOfConfigurationKeyOrNull.class); IsoSpec isoSpec = IsoSpec - .builder() - .sourcePath(operatingSystemIso) - .installationScript( - configProperties.apply(VIRTUALBOX_INSTALLATION_KEY_SEQUENCE).replace("HOSTNAME", - instanceVmSpec.getVmName())).build(); + .builder() + .sourcePath(operatingSystemIso) + .installationScript( + configProperties.apply(VIRTUALBOX_INSTALLATION_KEY_SEQUENCE) + .replace("HOSTNAME", instanceVmSpec.getVmName())) + .build(); - NetworkAdapter networkAdapter = NetworkAdapter.builder().networkAttachmentType(NetworkAttachmentType.NAT) - .tcpRedirectRule("127.0.0.1", 2222, "", 22).build(); - NetworkInterfaceCard networkInterfaceCard = NetworkInterfaceCard.builder().addNetworkAdapter(networkAdapter) - .build(); - - NetworkSpec networkSpec = NetworkSpec.builder().addNIC(networkInterfaceCard).build(); - machineSpec = MasterSpec.builder().iso(isoSpec).vm(instanceVmSpec).network(networkSpec).build(); + NetworkAdapter networkAdapter = NetworkAdapter.builder() + .networkAttachmentType(NetworkAttachmentType.HostOnly).build(); + NetworkInterfaceCard networkInterfaceCard = NetworkInterfaceCard + .builder().addNetworkAdapter(networkAdapter) + .addHostInterfaceName("vboxnet0").slot(0L).build(); + NetworkSpec networkSpec = NetworkSpec.builder() + .addNIC(networkInterfaceCard).build(); + machineSpec = MasterSpec.builder().iso(isoSpec).vm(instanceVmSpec) + .network(networkSpec).build(); } @Test @@ -106,8 +110,8 @@ public class MachineControllerLiveTest extends BaseVirtualBoxClientLiveTest { @Test(dependsOnMethods="testEnsureMachineisLaunchedAndSessionIsUnlocked") public void testEnsureMachineCanBePoweredOffMoreThanOneTimeAndSessionIsUnlocked() { ISession cloneMachineSession = machineController.ensureMachineHasPowerDown(instanceName); - cloneMachineSession = machineController.ensureMachineHasPowerDown(instanceName); - assertTrue(cloneMachineSession.getState() == SessionState.Unlocked); + SessionState state = cloneMachineSession.getState(); + assertTrue(state.equals(SessionState.Unlocked)); } private IMachine cloneFromMaster() { diff --git a/labs/virtualbox/src/test/java/org/jclouds/virtualbox/util/MachineUtilsLiveTest.java b/labs/virtualbox/src/test/java/org/jclouds/virtualbox/util/MachineUtilsLiveTest.java index 39bac6d52f..af69bc2732 100644 --- a/labs/virtualbox/src/test/java/org/jclouds/virtualbox/util/MachineUtilsLiveTest.java +++ b/labs/virtualbox/src/test/java/org/jclouds/virtualbox/util/MachineUtilsLiveTest.java @@ -18,9 +18,11 @@ */ package org.jclouds.virtualbox.util; + import static com.google.common.base.Preconditions.checkState; import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_IMAGE_PREFIX; import static org.jclouds.virtualbox.config.VirtualBoxConstants.VIRTUALBOX_INSTALLATION_KEY_SEQUENCE; +import static org.testng.AssertJUnit.assertTrue; import org.jclouds.config.ValueOfConfigurationKeyOrNull; import org.jclouds.virtualbox.BaseVirtualBoxClientLiveTest; @@ -35,20 +37,17 @@ import org.jclouds.virtualbox.domain.StorageController; import org.jclouds.virtualbox.domain.VmSpec; import org.jclouds.virtualbox.functions.CloneAndRegisterMachineFromIMachineIfNotAlreadyExists; import org.jclouds.virtualbox.functions.CreateAndInstallVm; -import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.virtualbox_4_1.CleanupMode; import org.virtualbox_4_1.IMachine; import org.virtualbox_4_1.ISession; -import org.virtualbox_4_1.LockType; import org.virtualbox_4_1.NetworkAttachmentType; import org.virtualbox_4_1.SessionState; import org.virtualbox_4_1.StorageBus; import com.google.common.base.CaseFormat; import com.google.common.base.Function; -import com.google.common.collect.ImmutableSet; import com.google.inject.Injector; @Test(groups = "live", testName = "MachineControllerLiveTest") @@ -62,62 +61,134 @@ public class MachineUtilsLiveTest extends BaseVirtualBoxClientLiveTest { public void setupContext() { super.setupContext(); instanceName = VIRTUALBOX_IMAGE_PREFIX - + CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, getClass().getSimpleName()); + + CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, getClass().getSimpleName()); StorageController ideController = StorageController - .builder() - .name("IDE Controller") - .bus(StorageBus.IDE) - .attachISO(0, 0, operatingSystemIso) - .attachHardDisk( - HardDisk.builder().diskpath(adminDisk(instanceName)).controllerPort(0).deviceSlot(1) - .autoDelete(true).build()).attachISO(1, 1, guestAdditionsIso).build(); + .builder() + .name("IDE Controller") + .bus(StorageBus.IDE) + .attachISO(0, 0, operatingSystemIso) + .attachHardDisk( + HardDisk.builder().diskpath(adminDisk(instanceName)).controllerPort(0).deviceSlot(1).autoDelete(true) + .build()).attachISO(1, 1, guestAdditionsIso).build(); VmSpec instanceVmSpec = VmSpec.builder().id(instanceName).name(instanceName).osTypeId("").memoryMB(512) - .cleanUpMode(CleanupMode.Full).controller(ideController).forceOverwrite(true).build(); + .cleanUpMode(CleanupMode.Full).controller(ideController).forceOverwrite(true).build(); Injector injector = view.utils().injector(); Function configProperties = injector.getInstance(ValueOfConfigurationKeyOrNull.class); IsoSpec isoSpec = IsoSpec - .builder() - .sourcePath(operatingSystemIso) - .installationScript( - configProperties.apply(VIRTUALBOX_INSTALLATION_KEY_SEQUENCE).replace("HOSTNAME", - instanceVmSpec.getVmName())).build(); + .builder() + .sourcePath(operatingSystemIso) + .installationScript( + configProperties.apply(VIRTUALBOX_INSTALLATION_KEY_SEQUENCE).replace("HOSTNAME", + instanceVmSpec.getVmName())).build(); NetworkAdapter networkAdapter = NetworkAdapter.builder().networkAttachmentType(NetworkAttachmentType.NAT) - .tcpRedirectRule("127.0.0.1", 2222, "", 22).build(); + .tcpRedirectRule("127.0.0.1", 2222, "", 22).build(); NetworkInterfaceCard networkInterfaceCard = NetworkInterfaceCard.builder().addNetworkAdapter(networkAdapter) - .build(); + .build(); NetworkSpec networkSpec = NetworkSpec.builder().addNIC(networkInterfaceCard).build(); machineSpec = MasterSpec.builder().iso(isoSpec).vm(instanceVmSpec).network(networkSpec).build(); } - @Test - public void lockSessionOnMachine() { - IMachine machine = cloneFromMaster(); - ISession session = machineUtils.lockSessionOnMachineAndApply(instanceName, LockType.Shared, - new Function() { + @Test(description = "write lock is acquired and released correctly") + public void writeLockSessionOnMachine() { + final IMachine clone = cloneFromMaster(); + ISession session = machineUtils.writeLockMachineAndApplyToSession(clone.getName(), + new Function() { + @Override + public ISession apply(ISession session) { + assertTrue(session.getMachine().getName().equals(clone.getName())); + return session; + } + }); + checkState(session.getState().equals(SessionState.Unlocked)); + undoVm(clone.getName()); + } + @Test(dependsOnMethods="writeLockSessionOnMachine", description = "shared lock is acquired and released correctly") + public void sharedLockSessionOnMachine() { + final IMachine clone = cloneFromMaster(); + ISession session = machineUtils.sharedLockMachineAndApplyToSession(clone.getName(), + new Function() { + @Override + public ISession apply(ISession session) { + assertTrue(session.getMachine().getName().equals(clone.getName())); + return session; + } + }); + checkState(session.getState().equals(SessionState.Unlocked)); + undoVm(clone.getName()); + } + + @Test(dependsOnMethods="sharedLockSessionOnMachine", description = "shared lock can be acquired after a write lock") + public void sharedLockCanBeAcquiredAfterWriteLockSessionOnMachine() { + final IMachine clone = cloneFromMaster(); + try { + ISession writeSession = machineUtils.writeLockMachineAndApplyToSession(clone.getName(), + new Function() { @Override - public ISession apply(ISession session) { - return session; + public ISession apply(ISession writeSession) { + checkState(writeSession.getState().equals(SessionState.Locked)); + //ISession sharedSession = sharedSession(clone); + return writeSession; } }); - checkState(session.getState().equals(SessionState.Unlocked)); - machine = manager.get().getVBox().findMachine(instanceName); - undoVm(instanceName); - + checkState(writeSession.getState().equals(SessionState.Unlocked)); + } finally { + undoVm(clone.getName()); + } + } + + private ISession sharedSession(final IMachine clone) { + ISession sharedSession = machineUtils.sharedLockMachineAndApplyToSession(clone.getName(), + new Function() { + @Override + public ISession apply(ISession sharedSession) { + checkState(sharedSession.getState().equals(SessionState.Locked)); + assertTrue(sharedSession.getMachine().getName().equals(clone.getName())); + return sharedSession; + } + }); + return sharedSession; + } + + @Test(dependsOnMethods="sharedLockCanBeAcquiredAfterWriteLockSessionOnMachine", description = "write lock cannot be acquired after a shared lock") + public void writeLockCannotBeAcquiredAfterSharedLockSessionOnMachine() { + final IMachine clone = cloneFromMaster(); + try { + ISession sharedSession = machineUtils.sharedLockMachineAndApplyToSession(clone.getName(), + new Function() { + @Override + public ISession apply(ISession sharedSession) { + checkState(sharedSession.getState().equals(SessionState.Locked)); + return sharedSession; + } + }); + checkState(sharedSession.getState().equals(SessionState.Unlocked)); + ISession writeSession = machineUtils.writeLockMachineAndApplyToSession(clone.getName(), + new Function() { + @Override + public ISession apply(ISession writeSession) { + checkState(writeSession.getState().equals(SessionState.Locked)); + assertTrue(writeSession.getMachine().getName().equals(clone.getName())); + return writeSession; + } + }); + checkState(writeSession.getState().equals(SessionState.Unlocked)); + } finally { + undoVm(clone.getName()); + } } - private IMachine cloneFromMaster() { IMachine source = getVmWithGuestAdditionsInstalled(); CloneSpec cloneSpec = CloneSpec.builder().vm(machineSpec.getVmSpec()).network(machineSpec.getNetworkSpec()) - .master(source).linked(true).build(); + .master(source).linked(true).build(); return new CloneAndRegisterMachineFromIMachineIfNotAlreadyExists(manager, workingDir, machineUtils) - .apply(cloneSpec); + .apply(cloneSpec); } private IMachine getVmWithGuestAdditionsInstalled() { @@ -130,13 +201,4 @@ public class MachineUtilsLiveTest extends BaseVirtualBoxClientLiveTest { return manager.get().getVBox().findMachine(masterSpecForTest.getVmSpec().getVmId()); } } - - @Override - @AfterClass(groups = "live") - protected void tearDown() throws Exception { - for (String vmName : ImmutableSet.of(instanceName)) { - undoVm(vmName); - } - super.tearDown(); - } } diff --git a/labs/virtualbox/src/test/resources/default-images.yaml b/labs/virtualbox/src/test/resources/default-images.yaml index 4efa20d277..fe4c0c82d3 100644 --- a/labs/virtualbox/src/test/resources/default-images.yaml +++ b/labs/virtualbox/src/test/resources/default-images.yaml @@ -1,4 +1,139 @@ images: + - id: ubuntu-10.04.4-server-i386 + name: ubuntu-10.04-server-i386 + description: ubuntu 10.04.4 server (i386) + os_arch: x86 + os_family: ubuntu + os_description: ubuntu + os_version: 10.04.4 + iso: http://releases.ubuntu.com/10.04.4/ubuntu-10.04.4-server-i386.iso + iso_md5: fc08a01e78348e3918180ea91a6883bb + username: toor + credential: password + keystroke_sequence: | + + /install/vmlinuz noapic preseed/url=http://10.0.2.2:8080/src/test/resources/preseed.cfg + debian-installer=en_US auto locale=en_US kbd-chooser/method=us + hostname=vmName + fb=false debconf/frontend=noninteractive + console-setup/ask_detect=false console-setup/modelcode=pc105 console-setup/layoutcode=us + initrd=/install/initrd.gz -- + preseed_cfg: | + ## Options to set on the command line + d-i debian-installer/locale string en_US + d-i console-setup/ask_detect boolean false + d-i console-setup/layoutcode string us + d-i netcfg/get_hostname string unassigned-hostname + d-i netcfg/get_domain string unassigned-domain + d-i time/zone string UTC + d-i clock-setup/utc-auto boolean true + d-i clock-setup/utc boolean true + d-i kbd-chooser/method select American English + d-i netcfg/wireless_wep string + d-i base-installer/kernel/override-image string linux-server + d-i debconf debconf/frontend select Noninteractive + d-i pkgsel/install-language-support boolean false + tasksel tasksel/first multiselect standard, ubuntu-server + d-i partman-auto/method string lvm + #d-i partman-auto/purge_lvm_from_device boolean true + d-i partman-lvm/confirm boolean true + d-i partman-lvm/device_remove_lvm boolean true + d-i partman-auto/choose_recipe select atomic + d-i partman/confirm_write_new_label boolean true + d-i partman/confirm_nooverwrite boolean true + d-i partman/choose_partition select finish + d-i partman/confirm boolean true + # Write the changes to disks and configure LVM? + d-i partman-lvm/confirm boolean true + d-i partman-lvm/confirm_nooverwrite boolean true + d-i partman-auto-lvm/guided_size string max + ## Default user, we can get away with a recipe to change this + d-i passwd/user-fullname string toor + d-i passwd/username string toor + d-i passwd/user-password password password + d-i passwd/user-password-again password password + d-i user-setup/encrypt-home boolean false + d-i user-setup/allow-password-weak boolean true + d-i pkgsel/include string openssh-server ntp + # Whether to upgrade packages after debootstrap. + # Allowed values: none, safe-upgrade, full-upgrade + d-i pkgsel/upgrade select full-upgrade + d-i grub-installer/only_debian boolean true + d-i grub-installer/with_other_os boolean true + d-i finish-install/reboot_in_progress note + #For the update + d-i pkgsel/update-policy select none + # debconf-get-selections --install + #Use mirror + choose-mirror-bin mirror/http/proxy string + - id: ubuntu-10.04.4-server-amd64 + name: ubuntu-10.04-server-amd64 + description: ubuntu 10.04.4 server (amd64) + os_arch: amd64 + os_family: ubuntu + os_description: ubuntu + os_version: 10.04.4 + os_64bit: true + iso: http://releases.ubuntu.com/10.04.4/ubuntu-10.04.4-server-amd64.iso + iso_md5: 9b218654cdcdf9722171648c52f8a088 + username: toor + credential: password + keystroke_sequence: | + + /install/vmlinuz noapic preseed/url=http://10.0.2.2:8080/src/test/resources/preseed.cfg + debian-installer=en_US auto locale=en_US kbd-chooser/method=us + hostname=vmName + fb=false debconf/frontend=noninteractive + console-setup/ask_detect=false console-setup/modelcode=pc105 console-setup/layoutcode=us + initrd=/install/initrd.gz -- + preseed_cfg: | + ## Options to set on the command line + d-i debian-installer/locale string en_US + d-i console-setup/ask_detect boolean false + d-i console-setup/layoutcode string us + d-i netcfg/get_hostname string unassigned-hostname + d-i netcfg/get_domain string unassigned-domain + d-i time/zone string UTC + d-i clock-setup/utc-auto boolean true + d-i clock-setup/utc boolean true + d-i kbd-chooser/method select American English + d-i netcfg/wireless_wep string + d-i base-installer/kernel/override-image string linux-server + d-i debconf debconf/frontend select Noninteractive + d-i pkgsel/install-language-support boolean false + tasksel tasksel/first multiselect standard, ubuntu-server + d-i partman-auto/method string lvm + #d-i partman-auto/purge_lvm_from_device boolean true + d-i partman-lvm/confirm boolean true + d-i partman-lvm/device_remove_lvm boolean true + d-i partman-auto/choose_recipe select atomic + d-i partman/confirm_write_new_label boolean true + d-i partman/confirm_nooverwrite boolean true + d-i partman/choose_partition select finish + d-i partman/confirm boolean true + # Write the changes to disks and configure LVM? + d-i partman-lvm/confirm boolean true + d-i partman-lvm/confirm_nooverwrite boolean true + d-i partman-auto-lvm/guided_size string max + ## Default user, we can get away with a recipe to change this + d-i passwd/user-fullname string toor + d-i passwd/username string toor + d-i passwd/user-password password password + d-i passwd/user-password-again password password + d-i user-setup/encrypt-home boolean false + d-i user-setup/allow-password-weak boolean true + d-i pkgsel/include string openssh-server ntp + # Whether to upgrade packages after debootstrap. + # Allowed values: none, safe-upgrade, full-upgrade + d-i pkgsel/upgrade select full-upgrade + d-i grub-installer/only_debian boolean true + d-i grub-installer/with_other_os boolean true + d-i finish-install/reboot_in_progress note + #For the update + d-i pkgsel/update-policy select none + # debconf-get-selections --install + #Use mirror + choose-mirror-bin mirror/http/proxy string - id: ubuntu-11.04-i386 name: ubuntu-11.04-server-i386 description: ubuntu 11.04 server (i386) @@ -15,7 +150,7 @@ images: fb=false debconf/frontend=noninteractive keyboard-configuration/layout=USA keyboard-configuration/variant=USA console-setup/ask_detect=false initrd=/install/initrd.gz -- - preseed_cfg: | + preseed_cfg: | ## Options to set on the command line d-i debian-installer/locale string en_US.utf8 d-i console-setup/ask_detect boolean false @@ -27,7 +162,7 @@ images: d-i time/zone string UTC d-i clock-setup/utc-auto boolean true d-i clock-setup/utc boolean true - d-i kbd-chooser/method select American English + d-i kbd-chooser/method select American English d-i netcfg/wireless_wep string d-i base-installer/kernel/override-image string linux-server # Choices: Dialog, Readline, Gnome, Kde, Editor, Noninteractive @@ -66,7 +201,7 @@ images: # debconf-get-selections --install #Use mirror choose-mirror-bin mirror/http/proxy string - - id: test-ubuntu-11.10-i386 + - id: ubuntu-11.10-i386 name: ubuntu-11.10-server-i386 description: ubuntu 11.10 server (i386) os_arch: x86 @@ -132,4 +267,92 @@ images: d-i pkgsel/update-policy select none # debconf-get-selections --install #Use mirror + choose-mirror-bin mirror/http/proxy string + - id: ubuntu-12.04.1-amd64 + name: ubuntu-12.04.1-server-amd64 + description: ubuntu 12.04.1 server (amd64) + os_arch: amd64 + os_family: ubuntu + os_description: ubuntu + os_version: 12.04.1 + os_64bit: true + iso: http://releases.ubuntu.com/12.04/ubuntu-12.04.1-server-amd64.iso + iso_md5: a8c667e871f48f3a662f3fbf1c3ddb17 + username: toor + credential: password + keystroke_sequence: | + + /install/vmlinuz noapic preseed/url=http://10.0.2.2:8080/src/test/resources/preseed.cfg + debian-installer=en_US auto locale=en_US kbd-chooser/method=us + hostname=vmName + fb=false debconf/frontend=noninteractive + keyboard-configuration/layout=USA keyboard-configuration/variant=USA console-setup/ask_detect=false + initrd=/install/initrd.gz -- + preseed_cfg: | + ## Options to set on the command line + d-i debian-installer/locale string en_US.utf8 + d-i console-setup/ask_detect boolean false + d-i console-setup/layout string USA + #d-i netcfg/get_hostname string dummy + d-i netcfg/get_hostname string unassigned-hostname + d-i netcfg/get_domain string unassigned-domain + # Continue without a default route + # Not working , specify a dummy in the DHCP + #d-i netcfg/no_default_route boolean + d-i time/zone string UTC + d-i clock-setup/utc-auto boolean true + d-i clock-setup/utc boolean true + d-i kbd-chooser/method select American English + d-i netcfg/wireless_wep string + d-i base-installer/kernel/override-image string linux-server + #d-i base-installer/kernel/override-image string linux-image-2.6.32-21-generic + # Choices: Dialog, Readline, Gnome, Kde, Editor, Noninteractive + d-i debconf debconf/frontend select Noninteractive + d-i pkgsel/install-language-support boolean false + tasksel tasksel/first multiselect standard, ubuntu-server + #d-i partman-auto/method string regular + d-i partman-auto/method string lvm + #d-i partman-auto/purge_lvm_from_device boolean true + d-i partman-lvm/confirm boolean true + d-i partman-lvm/device_remove_lvm boolean true + d-i partman-auto/choose_recipe select atomic + d-i partman/confirm_write_new_label boolean true + d-i partman/confirm_nooverwrite boolean true + d-i partman/choose_partition select finish + d-i partman/confirm boolean true + #http://ubuntu-virginia.ubuntuforums.org/showthread.php?p=9626883 + #Message: "write the changes to disk and configure lvm preseed" + #http://serverfault.com/questions/189328/ubuntu-kickstart-installation-using-lvm-waits-for-input + #preseed partman-lvm/confirm_nooverwrite boolean true + # Write the changes to disks and configure LVM? + d-i partman-lvm/confirm boolean true + d-i partman-lvm/confirm_nooverwrite boolean true + d-i partman-auto-lvm/guided_size string max + ## Default user, we can get away with a recipe to change this + d-i passwd/user-fullname string toor + d-i passwd/username string toor + d-i passwd/user-password password password + d-i passwd/user-password-again password password + d-i user-setup/encrypt-home boolean false + d-i user-setup/allow-password-weak boolean true + ## minimum is ssh and ntp + # Individual additional packages to install + d-i pkgsel/include string openssh-server ntp + # Whether to upgrade packages after debootstrap. + # Allowed values: none, safe-upgrade, full-upgrade + d-i pkgsel/upgrade select full-upgrade + d-i grub-installer/only_debian boolean true + d-i grub-installer/with_other_os boolean true + d-i finish-install/reboot_in_progress note + #For the update + d-i pkgsel/update-policy select none + # debconf-get-selections --install + #Use mirror + #d-i apt-setup/use_mirror boolean true + #d-i mirror/country string manual + #choose-mirror-bin mirror/protocol string http + #choose-mirror-bin mirror/http/hostname string 192.168.4.150 + #choose-mirror-bin mirror/http/directory string /ubuntu + #choose-mirror-bin mirror/suite select maverick + #d-i debian-installer/allow_unauthenticated string true choose-mirror-bin mirror/http/proxy string \ No newline at end of file diff --git a/labs/virtualbox/src/test/resources/logback.xml b/labs/virtualbox/src/test/resources/logback.xml index 3a5a73c80d..26f517de96 100644 --- a/labs/virtualbox/src/test/resources/logback.xml +++ b/labs/virtualbox/src/test/resources/logback.xml @@ -42,6 +42,11 @@ + + + + + diff --git a/loadbalancer/pom.xml b/loadbalancer/pom.xml index dc113b757a..62cfeef4e4 100644 --- a/loadbalancer/pom.xml +++ b/loadbalancer/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../project/pom.xml jclouds-loadbalancer diff --git a/pom.xml b/pom.xml index e14b2ff5b5..5917134254 100644 --- a/pom.xml +++ b/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT project/pom.xml jclouds-multi @@ -45,7 +45,6 @@ blobstore skeletons drivers - antcontrib scriptbuilder allcompute allblobstore diff --git a/project/pom.xml b/project/pom.xml index f9a68fbcfc..7a6e90b1f6 100644 --- a/project/pom.xml +++ b/project/pom.xml @@ -28,7 +28,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT pom jclouds Project http://www.jclouds.org diff --git a/providers/aws-cloudwatch/pom.xml b/providers/aws-cloudwatch/pom.xml index 609d63557c..a5667302ae 100644 --- a/providers/aws-cloudwatch/pom.xml +++ b/providers/aws-cloudwatch/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider diff --git a/providers/aws-ec2/pom.xml b/providers/aws-ec2/pom.xml index cd5c0b1a44..204744fe45 100644 --- a/providers/aws-ec2/pom.xml +++ b/providers/aws-ec2/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider diff --git a/providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/AWSEC2ProviderMetadata.java b/providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/AWSEC2ProviderMetadata.java index 4cffbd31ca..ef304cb991 100644 --- a/providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/AWSEC2ProviderMetadata.java +++ b/providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/AWSEC2ProviderMetadata.java @@ -69,7 +69,7 @@ public class AWSEC2ProviderMetadata extends BaseProviderMetadata { properties.setProperty(PROPERTY_EC2_AMI_QUERY, "owner-id=137112412989,801119661308,063491364108,099720109477,411009282317;state=available;image-type=machine"); // amis that work with the cluster instances - properties.setProperty(PROPERTY_EC2_CC_REGIONS, Region.US_EAST_1 + "," + Region.EU_WEST_1); + properties.setProperty(PROPERTY_EC2_CC_REGIONS, Region.US_EAST_1 + "," + Region.US_WEST_2 + ","+ Region.EU_WEST_1); properties .setProperty( PROPERTY_EC2_CC_AMI_QUERY, diff --git a/providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/domain/AWSRunningInstance.java b/providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/domain/AWSRunningInstance.java index 9cb43cb319..06605b208f 100644 --- a/providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/domain/AWSRunningInstance.java +++ b/providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/domain/AWSRunningInstance.java @@ -31,7 +31,7 @@ import org.jclouds.ec2.domain.RootDeviceType; import org.jclouds.ec2.domain.RunningInstance; import org.jclouds.javax.annotation.Nullable; -import com.google.common.base.Objects; +import com.google.common.base.Objects.ToStringHelper; import com.google.common.base.Strings; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; @@ -241,13 +241,13 @@ public class AWSRunningInstance extends RunningInstance { } @Override - public Builder groupId(String groupId) { - return Builder.class.cast(super.groupId(groupId)); + public Builder groupName(String groupName) { + return Builder.class.cast(super.groupName(groupName)); } @Override - public Builder groupIds(Iterable groupIds) { - return Builder.class.cast(super.groupIds(groupIds)); + public Builder groupNames(Iterable groupNames) { + return Builder.class.cast(super.groupNames(groupNames)); } @Override @@ -364,74 +364,10 @@ public class AWSRunningInstance extends RunningInstance { } @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + ((placementGroup == null) ? 0 : placementGroup.hashCode()); - result = prime * result + ((productCodes == null) ? 0 : productCodes.hashCode()); - result = prime * result + ((spotInstanceRequestId == null) ? 0 : spotInstanceRequestId.hashCode()); - result = prime * result + ((subnetId == null) ? 0 : subnetId.hashCode()); - result = prime * result + ((vpcId == null) ? 0 : vpcId.hashCode()); - result = prime * result + ((hypervisor == null) ? 0 : hypervisor.hashCode()); - result = prime * result + ((tags == null) ? 0 : tags.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - AWSRunningInstance other = (AWSRunningInstance) obj; - if (placementGroup == null) { - if (other.placementGroup != null) - return false; - } else if (!placementGroup.equals(other.placementGroup)) - return false; - if (productCodes == null) { - if (other.productCodes != null) - return false; - } else if (!productCodes.equals(other.productCodes)) - return false; - if (spotInstanceRequestId == null) { - if (other.spotInstanceRequestId != null) - return false; - } else if (!spotInstanceRequestId.equals(other.spotInstanceRequestId)) - return false; - if (subnetId == null) { - if (other.subnetId != null) - return false; - } else if (!subnetId.equals(other.subnetId)) - return false; - if (vpcId == null) { - if (other.vpcId != null) - return false; - } else if (!vpcId.equals(other.vpcId)) - return false; - if (tags == null) { - if (other.tags != null) - return false; - } else if (!tags.equals(other.tags)) - return false; - if (!Objects.equal(hypervisor, other.hypervisor)) - return false; - return true; - } - - @Override - public String toString() { - return "[region=" + region + ", availabilityZone=" + availabilityZone + ", instanceId=" + instanceId - + ", instanceState=" + rawState + ", instanceType=" + instanceType + ", virtualizationType=" - + virtualizationType + ", imageId=" + imageId + ", ipAddress=" + ipAddress + ", dnsName=" + dnsName - + ", privateIpAddress=" + privateIpAddress + ", privateDnsName=" + privateDnsName + ", keyName=" - + keyName + ", platform=" + platform + ", launchTime=" + launchTime + ", rootDeviceName=" - + rootDeviceName + ", rootDeviceType=" + rootDeviceType + ", ebsBlockDevices=" + ebsBlockDevices - + ", monitoringState=" + monitoringState + ", placementGroup=" + placementGroup + ", productCodes=" - + productCodes + ", spotInstanceRequestId=" + spotInstanceRequestId + ", subnetId=" + subnetId - + ", hypervisor=" + hypervisor + ", vpcId=" + vpcId + ", tags=" + tags + "]"; + protected ToStringHelper string() { + return super.string().add("monitoringState", monitoringState).add("placementGroup", placementGroup) + .add("subnetId", subnetId).add("spotInstanceRequestId", spotInstanceRequestId).add("vpcId", vpcId) + .add("hypervisor", hypervisor).add("tags", tags); } } diff --git a/providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/domain/PlacementGroup.java b/providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/domain/PlacementGroup.java index db0dfee5f9..9250fc418c 100644 --- a/providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/domain/PlacementGroup.java +++ b/providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/domain/PlacementGroup.java @@ -77,8 +77,12 @@ public class PlacementGroup implements Comparable { } /** - * @return placement groups are in a region, however the namescope is global. + * To be removed in jclouds 1.6

Warning

+ * + * Especially on EC2 clones that may not support regions, this value is fragile. Consider + * alternate means to determine context. */ + @Deprecated public String getRegion() { return region; } diff --git a/providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/domain/Spot.java b/providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/domain/Spot.java index c5b21c9964..75e2d3cbea 100644 --- a/providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/domain/Spot.java +++ b/providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/domain/Spot.java @@ -92,6 +92,13 @@ public class Spot implements Comparable { this.timestamp = checkNotNull(timestamp, "timestamp"); } + /** + * To be removed in jclouds 1.6

Warning

+ * + * Especially on EC2 clones that may not support regions, this value is fragile. Consider + * alternate means to determine context. + */ + @Deprecated public String getRegion() { return region; } diff --git a/providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/functions/SpotInstanceRequestToAWSRunningInstance.java b/providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/functions/SpotInstanceRequestToAWSRunningInstance.java index 5c7fe7d352..854000b8d1 100644 --- a/providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/functions/SpotInstanceRequestToAWSRunningInstance.java +++ b/providers/aws-ec2/src/main/java/org/jclouds/aws/ec2/functions/SpotInstanceRequestToAWSRunningInstance.java @@ -52,7 +52,7 @@ public class SpotInstanceRequestToAWSRunningInstance implements Function datapoints = monitoringContext.getApi().getMetricApiForRegion(instance.getRegion()) + GetMetricStatisticsResponse datapoints = monitoringContext.getApi().getMetricApiForRegion(instance.getRegion()) .getMetricStatistics(GetMetricStatistics.builder() .dimension(new Dimension(EC2Constants.Dimension.INSTANCE_ID, instance.getId())) .unit(Unit.PERCENT) @@ -187,7 +187,7 @@ public class AWSEC2ComputeServiceLiveTest extends EC2ComputeServiceLiveTest { } // make sure we made our dummy group and also let in the user's group - assertEquals(newTreeSet(instance.getGroupIds()), ImmutableSortedSet. of("jclouds#" + group, group)); + assertEquals(newTreeSet(instance.getGroupNames()), ImmutableSortedSet. of("jclouds#" + group, group)); // make sure our dummy group has no rules SecurityGroup secgroup = getOnlyElement(securityGroupClient.describeSecurityGroupsInRegion(instance diff --git a/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/AWSEC2TemplateBuilderLiveTest.java b/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/AWSEC2TemplateBuilderLiveTest.java index 00d3ba3e56..f6ac142c0a 100644 --- a/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/AWSEC2TemplateBuilderLiveTest.java +++ b/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/AWSEC2TemplateBuilderLiveTest.java @@ -171,7 +171,7 @@ public class AWSEC2TemplateBuilderLiveTest extends EC2TemplateBuilderLiveTest { Template defaultTemplate = view.getComputeService().templateBuilder().build(); assert (defaultTemplate.getImage().getProviderId().startsWith("ami-")) : defaultTemplate; - assertEquals(defaultTemplate.getImage().getOperatingSystem().getVersion(), "pv-2012.03.3"); + assertEquals(defaultTemplate.getImage().getOperatingSystem().getVersion(), "pv-2012.09.rc-0"); assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), true); assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), OsFamily.AMZN_LINUX); assertEquals(defaultTemplate.getImage().getUserMetadata().get("rootDeviceType"), "ebs"); @@ -186,7 +186,7 @@ public class AWSEC2TemplateBuilderLiveTest extends EC2TemplateBuilderLiveTest { Template defaultTemplate = view.getComputeService().templateBuilder().osFamily(OsFamily.AMZN_LINUX) .imageMatches(EC2ImagePredicates.rootDeviceType(RootDeviceType.INSTANCE_STORE)).build(); assert (defaultTemplate.getImage().getProviderId().startsWith("ami-")) : defaultTemplate; - assertEquals(defaultTemplate.getImage().getOperatingSystem().getVersion(), "pv-2012.03.3"); + assertEquals(defaultTemplate.getImage().getOperatingSystem().getVersion(), "pv-2012.09.rc-0"); assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), true); assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), OsFamily.AMZN_LINUX); assertEquals(defaultTemplate.getImage().getUserMetadata().get("rootDeviceType"), "instance-store"); @@ -201,7 +201,7 @@ public class AWSEC2TemplateBuilderLiveTest extends EC2TemplateBuilderLiveTest { .build(); assert (fastestTemplate.getImage().getProviderId().startsWith("ami-")) : fastestTemplate; assertEquals(fastestTemplate.getHardware().getProviderId(), InstanceType.HI1_4XLARGE); - assertEquals(fastestTemplate.getImage().getOperatingSystem().getVersion(), "pv-2012.03.3"); + assertEquals(fastestTemplate.getImage().getOperatingSystem().getVersion(), "pv-2012.09.rc-0"); assertEquals(fastestTemplate.getImage().getOperatingSystem().is64Bit(), true); assertEquals(fastestTemplate.getImage().getOperatingSystem().getFamily(), OsFamily.AMZN_LINUX); assertEquals(fastestTemplate.getImage().getUserMetadata().get("rootDeviceType"), "instance-store"); diff --git a/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/IncidentalResourcesGetCleanedUpLiveTest.java b/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/IncidentalResourcesGetCleanedUpLiveTest.java index 9d52e60397..9504701275 100644 --- a/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/IncidentalResourcesGetCleanedUpLiveTest.java +++ b/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/IncidentalResourcesGetCleanedUpLiveTest.java @@ -21,7 +21,6 @@ package org.jclouds.aws.ec2.compute; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; -import java.util.Collections; import java.util.Set; import org.jclouds.aws.ec2.AWSEC2ApiMetadata; @@ -117,8 +116,8 @@ public class IncidentalResourcesGetCleanedUpLiveTest extends BaseComputeServiceC assertNotNull(instance1.getKeyName()); assertEquals(instance1.getRegion(), instance2.getRegion(), "Nodes are not in the same region"); assertEquals(instance1.getKeyName(), instance2.getKeyName(), "Nodes do not have same key-pair name"); - assertEquals(instance1.getGroupIds(), instance2.getGroupIds(), "Nodes are not in the same group"); - assertEquals(instance1.getGroupIds(), ImmutableSet.of(expectedSecurityGroupName), "Nodes are not in the expected security group"); + assertEquals(instance1.getGroupNames(), instance2.getGroupNames(), "Nodes are not in the same group"); + assertEquals(instance1.getGroupNames(), ImmutableSet.of(expectedSecurityGroupName), "Nodes are not in the expected security group"); // Assert a single key-pair and security group has been created String expectedKeyPairName = instance1.getKeyName(); @@ -157,8 +156,8 @@ public class IncidentalResourcesGetCleanedUpLiveTest extends BaseComputeServiceC done = securityGroupsAfterDestroyAll.isEmpty() && keyPairsAfterDestroyAll.isEmpty(); } while (!done && stopwatch.elapsedMillis() < TIMEOUT_MS); - assertEquals(securityGroupsAfterDestroyAll, Collections.emptySet()); - assertEquals(keyPairsAfterDestroyAll, Collections.emptySet()); + assertEquals(securityGroupsAfterDestroyAll, ImmutableSet.of()); + assertEquals(keyPairsAfterDestroyAll, ImmutableSet.of()); } finally { view.getComputeService().destroyNodesMatching(NodePredicates.inGroup(group)); diff --git a/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/strategy/AWSEC2ReviseParsedImageTest.java b/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/strategy/AWSEC2ReviseParsedImageTest.java index 97fdffd1b3..d30818f8af 100644 --- a/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/strategy/AWSEC2ReviseParsedImageTest.java +++ b/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/compute/strategy/AWSEC2ReviseParsedImageTest.java @@ -20,7 +20,6 @@ package org.jclouds.aws.ec2.compute.strategy; import static org.testng.Assert.assertEquals; -import java.util.Collections; import java.util.Map; import org.jclouds.compute.config.BaseComputeServiceContextModule; @@ -38,6 +37,8 @@ import org.jclouds.json.config.GsonModule; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; import com.google.inject.Guice; public class AWSEC2ReviseParsedImageTest { @@ -94,13 +95,13 @@ public class AWSEC2ReviseParsedImageTest { Image.ImageState imageState = Image.ImageState.AVAILABLE; Image.ImageType imageType = Image.ImageType.MACHINE; boolean isPublic = true; - Iterable productCodes = Collections.emptySet(); + Iterable productCodes = ImmutableSet.of(); String kernelId = ""; String platform = ""; String ramdiskId = ""; RootDeviceType rootDeviceType = RootDeviceType.EBS; String rootDeviceName = ""; - Map ebsBlockDevices = Collections.emptyMap(); + Map ebsBlockDevices = ImmutableMap.of(); VirtualizationType virtualizationType = VirtualizationType.HVM; Hypervisor hypervisor = Hypervisor.XEN; Image from = new Image(region, architecture, imageName, description, imageId, imageOwnerId + "/" + imageName, imageOwnerId, imageState, "available", imageType, isPublic, productCodes, kernelId, platform, ramdiskId, rootDeviceType, rootDeviceName, ebsBlockDevices, virtualizationType, hypervisor); diff --git a/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/functions/SpotInstanceRequestToAWSRunningInstanceTest.java b/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/functions/SpotInstanceRequestToAWSRunningInstanceTest.java index 4324994036..76c1ce9df7 100644 --- a/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/functions/SpotInstanceRequestToAWSRunningInstanceTest.java +++ b/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/functions/SpotInstanceRequestToAWSRunningInstanceTest.java @@ -66,7 +66,7 @@ public class SpotInstanceRequestToAWSRunningInstanceTest { AWSRunningInstance.builder().region("us-east-1").instanceId("sir-228e6406") .spotInstanceRequestId("sir-228e6406").instanceState(InstanceState.PENDING) .rawState("open").imageId("ami-595a0a1c") - .groupId("default").instanceType("m1.large") + .groupName("default").instanceType("m1.large") .tag("foo", "bar") .tag("empty", "") .hypervisor(Hypervisor.XEN) diff --git a/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/options/AWSDescribeImagesOptionsTest.java b/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/options/AWSDescribeImagesOptionsTest.java index 8dcb4050ea..55dadedfeb 100644 --- a/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/options/AWSDescribeImagesOptionsTest.java +++ b/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/options/AWSDescribeImagesOptionsTest.java @@ -24,11 +24,10 @@ import static org.jclouds.aws.ec2.options.AWSDescribeImagesOptions.Builder.image import static org.jclouds.aws.ec2.options.AWSDescribeImagesOptions.Builder.ownedBy; import static org.testng.Assert.assertEquals; -import java.util.Collections; - import org.jclouds.http.options.HttpRequestOptions; import org.testng.annotations.Test; +import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMultimap; @@ -49,19 +48,19 @@ public class AWSDescribeImagesOptionsTest { public void testExecutableBy() { AWSDescribeImagesOptions options = new AWSDescribeImagesOptions(); options.executableBy("test"); - assertEquals(options.buildFormParameters().get("ExecutableBy"), Collections.singletonList("test")); + assertEquals(options.buildFormParameters().get("ExecutableBy"), ImmutableList.of("test")); } @Test public void testNullExecutableBy() { AWSDescribeImagesOptions options = new AWSDescribeImagesOptions(); - assertEquals(options.buildFormParameters().get("ExecutableBy"), Collections.EMPTY_LIST); + assertEquals(options.buildFormParameters().get("ExecutableBy"), ImmutableList.of()); } @Test public void testExecutableByStatic() { AWSDescribeImagesOptions options = executableBy("test"); - assertEquals(options.buildFormParameters().get("ExecutableBy"), Collections.singletonList("test")); + assertEquals(options.buildFormParameters().get("ExecutableBy"), ImmutableList.of("test")); } @Test(expectedExceptions = NullPointerException.class) @@ -73,27 +72,27 @@ public class AWSDescribeImagesOptionsTest { public void testOwners() { AWSDescribeImagesOptions options = new AWSDescribeImagesOptions(); options.ownedBy("test"); - assertEquals(options.buildFormParameters().get("Owner.1"), Collections.singletonList("test")); + assertEquals(options.buildFormParameters().get("Owner.1"), ImmutableList.of("test")); } @Test public void testMultipleOwners() { AWSDescribeImagesOptions options = new AWSDescribeImagesOptions(); options.ownedBy("test", "trouble"); - assertEquals(options.buildFormParameters().get("Owner.1"), Collections.singletonList("test")); - assertEquals(options.buildFormParameters().get("Owner.2"), Collections.singletonList("trouble")); + assertEquals(options.buildFormParameters().get("Owner.1"), ImmutableList.of("test")); + assertEquals(options.buildFormParameters().get("Owner.2"), ImmutableList.of("trouble")); } @Test public void testNullOwners() { AWSDescribeImagesOptions options = new AWSDescribeImagesOptions(); - assertEquals(options.buildFormParameters().get("Owner.1"), Collections.EMPTY_LIST); + assertEquals(options.buildFormParameters().get("Owner.1"), ImmutableList.of()); } @Test public void testOwnersStatic() { AWSDescribeImagesOptions options = ownedBy("test"); - assertEquals(options.buildFormParameters().get("Owner.1"), Collections.singletonList("test")); + assertEquals(options.buildFormParameters().get("Owner.1"), ImmutableList.of("test")); } public void testNoOwners() { @@ -104,27 +103,27 @@ public class AWSDescribeImagesOptionsTest { public void testImageIds() { AWSDescribeImagesOptions options = new AWSDescribeImagesOptions(); options.imageIds("test"); - assertEquals(options.buildFormParameters().get("ImageId.1"), Collections.singletonList("test")); + assertEquals(options.buildFormParameters().get("ImageId.1"), ImmutableList.of("test")); } @Test public void testMultipleImageIds() { AWSDescribeImagesOptions options = new AWSDescribeImagesOptions(); options.imageIds("test", "trouble"); - assertEquals(options.buildFormParameters().get("ImageId.1"), Collections.singletonList("test")); - assertEquals(options.buildFormParameters().get("ImageId.2"), Collections.singletonList("trouble")); + assertEquals(options.buildFormParameters().get("ImageId.1"), ImmutableList.of("test")); + assertEquals(options.buildFormParameters().get("ImageId.2"), ImmutableList.of("trouble")); } @Test public void testNullImageIds() { AWSDescribeImagesOptions options = new AWSDescribeImagesOptions(); - assertEquals(options.buildFormParameters().get("ImageId.1"), Collections.EMPTY_LIST); + assertEquals(options.buildFormParameters().get("ImageId.1"), ImmutableList.of()); } @Test public void testImageIdsStatic() { AWSDescribeImagesOptions options = imageIds("test"); - assertEquals(options.buildFormParameters().get("ImageId.1"), Collections.singletonList("test")); + assertEquals(options.buildFormParameters().get("ImageId.1"), ImmutableList.of("test")); } public void testNoImageIds() { @@ -139,12 +138,12 @@ public class AWSDescribeImagesOptionsTest { } private void testMapFilters(AWSDescribeImagesOptions options) { - assertEquals(options.buildFormParameters().get("Filter.1.Name"), Collections.singletonList("is-public")); - assertEquals(options.buildFormParameters().get("Filter.1.Value.1"), Collections.singletonList("true")); - assertEquals(options.buildFormParameters().get("Filter.2.Name"), Collections.singletonList("architecture")); - assertEquals(options.buildFormParameters().get("Filter.2.Value.1"), Collections.singletonList("x86_64")); - assertEquals(options.buildFormParameters().get("Filter.3.Name"), Collections.singletonList("platform")); - assertEquals(options.buildFormParameters().get("Filter.3.Value.1"), Collections.singletonList("windows")); + assertEquals(options.buildFormParameters().get("Filter.1.Name"), ImmutableList.of("is-public")); + assertEquals(options.buildFormParameters().get("Filter.1.Value.1"), ImmutableList.of("true")); + assertEquals(options.buildFormParameters().get("Filter.2.Name"), ImmutableList.of("architecture")); + assertEquals(options.buildFormParameters().get("Filter.2.Value.1"), ImmutableList.of("x86_64")); + assertEquals(options.buildFormParameters().get("Filter.3.Name"), ImmutableList.of("platform")); + assertEquals(options.buildFormParameters().get("Filter.3.Value.1"), ImmutableList.of("windows")); } @Test @@ -163,12 +162,12 @@ public class AWSDescribeImagesOptionsTest { } private void testMultimapFilters(AWSDescribeImagesOptions options) { - assertEquals(options.buildFormParameters().get("Filter.1.Name"), Collections.singletonList("is-public")); - assertEquals(options.buildFormParameters().get("Filter.1.Value.1"), Collections.singletonList("true")); - assertEquals(options.buildFormParameters().get("Filter.2.Name"), Collections.singletonList("architecture")); - assertEquals(options.buildFormParameters().get("Filter.2.Value.1"), Collections.singletonList("x86_64")); - assertEquals(options.buildFormParameters().get("Filter.3.Name"), Collections.singletonList("platform")); - assertEquals(options.buildFormParameters().get("Filter.3.Value.1"), Collections.singletonList("windows")); + assertEquals(options.buildFormParameters().get("Filter.1.Name"), ImmutableList.of("is-public")); + assertEquals(options.buildFormParameters().get("Filter.1.Value.1"), ImmutableList.of("true")); + assertEquals(options.buildFormParameters().get("Filter.2.Name"), ImmutableList.of("architecture")); + assertEquals(options.buildFormParameters().get("Filter.2.Value.1"), ImmutableList.of("x86_64")); + assertEquals(options.buildFormParameters().get("Filter.3.Name"), ImmutableList.of("platform")); + assertEquals(options.buildFormParameters().get("Filter.3.Value.1"), ImmutableList.of("windows")); } @Test diff --git a/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/options/AWSRunInstancesOptionsTest.java b/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/options/AWSRunInstancesOptionsTest.java index fdc5c63568..5114881821 100644 --- a/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/options/AWSRunInstancesOptionsTest.java +++ b/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/options/AWSRunInstancesOptionsTest.java @@ -30,13 +30,12 @@ import static org.jclouds.aws.ec2.options.AWSRunInstancesOptions.Builder.withSub import static org.jclouds.aws.ec2.options.AWSRunInstancesOptions.Builder.withUserData; import static org.testng.Assert.assertEquals; -import java.util.Collections; - import org.jclouds.ec2.domain.BlockDeviceMapping; import org.jclouds.ec2.domain.InstanceType; import org.jclouds.http.options.HttpRequestOptions; import org.testng.annotations.Test; +import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; /** @@ -56,19 +55,19 @@ public class AWSRunInstancesOptionsTest { public void testWithKeyName() { AWSRunInstancesOptions options = new AWSRunInstancesOptions(); options.withKeyName("test"); - assertEquals(options.buildFormParameters().get("KeyName"), Collections.singletonList("test")); + assertEquals(options.buildFormParameters().get("KeyName"), ImmutableList.of("test")); } @Test public void testNullWithKeyName() { AWSRunInstancesOptions options = new AWSRunInstancesOptions(); - assertEquals(options.buildFormParameters().get("KeyName"), Collections.EMPTY_LIST); + assertEquals(options.buildFormParameters().get("KeyName"), ImmutableList.of()); } @Test public void testWithKeyNameStatic() { AWSRunInstancesOptions options = withKeyName("test"); - assertEquals(options.buildFormParameters().get("KeyName"), Collections.singletonList("test")); + assertEquals(options.buildFormParameters().get("KeyName"), ImmutableList.of("test")); } @Test(expectedExceptions = NullPointerException.class) @@ -80,19 +79,19 @@ public class AWSRunInstancesOptionsTest { public void testWithSecurityGroup() { AWSRunInstancesOptions options = new AWSRunInstancesOptions(); options.withSecurityGroup("test"); - assertEquals(options.buildFormParameters().get("SecurityGroup.1"), Collections.singletonList("test")); + assertEquals(options.buildFormParameters().get("SecurityGroup.1"), ImmutableList.of("test")); } @Test public void testNullWithSecurityGroup() { AWSRunInstancesOptions options = new AWSRunInstancesOptions(); - assertEquals(options.buildFormParameters().get("SecurityGroup"), Collections.EMPTY_LIST); + assertEquals(options.buildFormParameters().get("SecurityGroup"), ImmutableList.of()); } @Test public void testWithSecurityGroupStatic() { AWSRunInstancesOptions options = withSecurityGroup("test"); - assertEquals(options.buildFormParameters().get("SecurityGroup.1"), Collections.singletonList("test")); + assertEquals(options.buildFormParameters().get("SecurityGroup.1"), ImmutableList.of("test")); } @Test(expectedExceptions = NullPointerException.class) @@ -105,19 +104,19 @@ public class AWSRunInstancesOptionsTest { public void testWithSecurityGroupId() { AWSRunInstancesOptions options = new AWSRunInstancesOptions(); options.withSecurityGroupId("test"); - assertEquals(options.buildFormParameters().get("SecurityGroupId.1"), Collections.singletonList("test")); + assertEquals(options.buildFormParameters().get("SecurityGroupId.1"), ImmutableList.of("test")); } @Test public void testNullWithSecurityGroupId() { AWSRunInstancesOptions options = new AWSRunInstancesOptions(); - assertEquals(options.buildFormParameters().get("SecurityGroupId"), Collections.EMPTY_LIST); + assertEquals(options.buildFormParameters().get("SecurityGroupId"), ImmutableList.of()); } @Test public void testWithSecurityGroupIdStatic() { AWSRunInstancesOptions options = withSecurityGroupId("test"); - assertEquals(options.buildFormParameters().get("SecurityGroupId.1"), Collections.singletonList("test")); + assertEquals(options.buildFormParameters().get("SecurityGroupId.1"), ImmutableList.of("test")); } @Test(expectedExceptions = NullPointerException.class) @@ -128,26 +127,26 @@ public class AWSRunInstancesOptionsTest { @Test public void testNullWithAdditionalInfo() { AWSRunInstancesOptions options = new AWSRunInstancesOptions(); - assertEquals(options.buildFormParameters().get("AdditionalInfo"), Collections.EMPTY_LIST); + assertEquals(options.buildFormParameters().get("AdditionalInfo"), ImmutableList.of()); } @Test public void testWithUserData() { AWSRunInstancesOptions options = new AWSRunInstancesOptions(); options.withUserData("test".getBytes()); - assertEquals(options.buildFormParameters().get("UserData"), Collections.singletonList("dGVzdA==")); + assertEquals(options.buildFormParameters().get("UserData"), ImmutableList.of("dGVzdA==")); } @Test public void testNullWithUserData() { AWSRunInstancesOptions options = new AWSRunInstancesOptions(); - assertEquals(options.buildFormParameters().get("UserData"), Collections.EMPTY_LIST); + assertEquals(options.buildFormParameters().get("UserData"), ImmutableList.of()); } @Test public void testWithUserDataStatic() { AWSRunInstancesOptions options = withUserData("test".getBytes()); - assertEquals(options.buildFormParameters().get("UserData"), Collections.singletonList("dGVzdA==")); + assertEquals(options.buildFormParameters().get("UserData"), ImmutableList.of("dGVzdA==")); } @Test(expectedExceptions = NullPointerException.class) @@ -164,19 +163,19 @@ public class AWSRunInstancesOptionsTest { public void testWithInstanceType() { AWSRunInstancesOptions options = new AWSRunInstancesOptions(); options.asType(InstanceType.C1_XLARGE); - assertEquals(options.buildFormParameters().get("InstanceType"), Collections.singletonList("c1.xlarge")); + assertEquals(options.buildFormParameters().get("InstanceType"), ImmutableList.of("c1.xlarge")); } @Test public void testNullWithInstanceType() { AWSRunInstancesOptions options = new AWSRunInstancesOptions(); - assertEquals(options.buildFormParameters().get("InstanceType"), Collections.EMPTY_LIST); + assertEquals(options.buildFormParameters().get("InstanceType"), ImmutableList.of()); } @Test public void testWithInstanceTypeStatic() { AWSRunInstancesOptions options = asType(InstanceType.C1_XLARGE); - assertEquals(options.buildFormParameters().get("InstanceType"), Collections.singletonList("c1.xlarge")); + assertEquals(options.buildFormParameters().get("InstanceType"), ImmutableList.of("c1.xlarge")); } @Test(expectedExceptions = NullPointerException.class) @@ -188,19 +187,19 @@ public class AWSRunInstancesOptionsTest { public void testWithKernelId() { AWSRunInstancesOptions options = new AWSRunInstancesOptions(); options.withKernelId("test"); - assertEquals(options.buildFormParameters().get("KernelId"), Collections.singletonList("test")); + assertEquals(options.buildFormParameters().get("KernelId"), ImmutableList.of("test")); } @Test public void testNullWithKernelId() { AWSRunInstancesOptions options = new AWSRunInstancesOptions(); - assertEquals(options.buildFormParameters().get("KernelId"), Collections.EMPTY_LIST); + assertEquals(options.buildFormParameters().get("KernelId"), ImmutableList.of()); } @Test public void testWithKernelIdStatic() { AWSRunInstancesOptions options = withKernelId("test"); - assertEquals(options.buildFormParameters().get("KernelId"), Collections.singletonList("test")); + assertEquals(options.buildFormParameters().get("KernelId"), ImmutableList.of("test")); } @Test(expectedExceptions = NullPointerException.class) @@ -212,38 +211,38 @@ public class AWSRunInstancesOptionsTest { public void testWithMonitoringEnabled() { AWSRunInstancesOptions options = new AWSRunInstancesOptions(); options.enableMonitoring(); - assertEquals(options.buildFormParameters().get("Monitoring.Enabled"), Collections.singletonList("true")); + assertEquals(options.buildFormParameters().get("Monitoring.Enabled"), ImmutableList.of("true")); } @Test public void testNullWithMonitoringEnabled() { AWSRunInstancesOptions options = new AWSRunInstancesOptions(); - assertEquals(options.buildFormParameters().get("Monitoring.Enabled"), Collections.EMPTY_LIST); + assertEquals(options.buildFormParameters().get("Monitoring.Enabled"), ImmutableList.of()); } @Test public void testWithMonitoringEnabledStatic() { AWSRunInstancesOptions options = enableMonitoring(); - assertEquals(options.buildFormParameters().get("Monitoring.Enabled"), Collections.singletonList("true")); + assertEquals(options.buildFormParameters().get("Monitoring.Enabled"), ImmutableList.of("true")); } @Test public void testWithSubnetId() { AWSRunInstancesOptions options = new AWSRunInstancesOptions(); options.withSubnetId("test"); - assertEquals(options.buildFormParameters().get("SubnetId"), Collections.singletonList("test")); + assertEquals(options.buildFormParameters().get("SubnetId"), ImmutableList.of("test")); } @Test public void testNullWithSubnetId() { AWSRunInstancesOptions options = new AWSRunInstancesOptions(); - assertEquals(options.buildFormParameters().get("SubnetId"), Collections.EMPTY_LIST); + assertEquals(options.buildFormParameters().get("SubnetId"), ImmutableList.of()); } @Test public void testWithSubnetIdStatic() { AWSRunInstancesOptions options = withSubnetId("test"); - assertEquals(options.buildFormParameters().get("SubnetId"), Collections.singletonList("test")); + assertEquals(options.buildFormParameters().get("SubnetId"), ImmutableList.of("test")); } @Test(expectedExceptions = NullPointerException.class) @@ -255,19 +254,19 @@ public class AWSRunInstancesOptionsTest { public void testWithRamdisk() { AWSRunInstancesOptions options = new AWSRunInstancesOptions(); options.withRamdisk("test"); - assertEquals(options.buildFormParameters().get("RamdiskId"), Collections.singletonList("test")); + assertEquals(options.buildFormParameters().get("RamdiskId"), ImmutableList.of("test")); } @Test public void testNullWithRamdisk() { AWSRunInstancesOptions options = new AWSRunInstancesOptions(); - assertEquals(options.buildFormParameters().get("RamdiskId"), Collections.EMPTY_LIST); + assertEquals(options.buildFormParameters().get("RamdiskId"), ImmutableList.of()); } @Test public void testWithRamdiskStatic() { AWSRunInstancesOptions options = withRamdisk("test"); - assertEquals(options.buildFormParameters().get("RamdiskId"), Collections.singletonList("test")); + assertEquals(options.buildFormParameters().get("RamdiskId"), ImmutableList.of("test")); } @Test(expectedExceptions = NullPointerException.class) @@ -278,7 +277,7 @@ public class AWSRunInstancesOptionsTest { @Test public void testNullWithVirtualName() { AWSRunInstancesOptions options = new AWSRunInstancesOptions(); - assertEquals(options.buildFormParameters().get("BlockDeviceMapping.VirtualName"), Collections.EMPTY_LIST); + assertEquals(options.buildFormParameters().get("BlockDeviceMapping.VirtualName"), ImmutableList.of()); } @Test @@ -286,30 +285,30 @@ public class AWSRunInstancesOptionsTest { BlockDeviceMapping mapping = new BlockDeviceMapping.MapNewVolumeToDevice("/dev/sda1", 120, true); AWSRunInstancesOptions options = new AWSRunInstancesOptions().withBlockDeviceMappings(ImmutableSet . of(mapping)); - assertEquals(options.buildFormParameters().get("BlockDeviceMapping.1.DeviceName"), Collections - .singletonList("/dev/sda1")); - assertEquals(options.buildFormParameters().get("BlockDeviceMapping.1.Ebs.VolumeSize"), Collections - .singletonList("120")); - assertEquals(options.buildFormParameters().get("BlockDeviceMapping.1.Ebs.DeleteOnTermination"), Collections - .singletonList("true")); + assertEquals(options.buildFormParameters().get("BlockDeviceMapping.1.DeviceName"), + ImmutableList.of("/dev/sda1")); + assertEquals(options.buildFormParameters().get("BlockDeviceMapping.1.Ebs.VolumeSize"), + ImmutableList.of("120")); + assertEquals(options.buildFormParameters().get("BlockDeviceMapping.1.Ebs.DeleteOnTermination"), + ImmutableList.of("true")); } @Test public void testNullWithBlockDeviceMapping() { AWSRunInstancesOptions options = new AWSRunInstancesOptions(); - assertEquals(options.buildFormParameters().get("BlockDeviceMapping"), Collections.EMPTY_LIST); + assertEquals(options.buildFormParameters().get("BlockDeviceMapping"), ImmutableList.of()); } @Test public void testWithBlockDeviceMappingStatic() { BlockDeviceMapping mapping = new BlockDeviceMapping.MapNewVolumeToDevice("/dev/sda1", 120, true); AWSRunInstancesOptions options = withBlockDeviceMappings(ImmutableSet. of(mapping)); - assertEquals(options.buildFormParameters().get("BlockDeviceMapping.1.DeviceName"), Collections - .singletonList("/dev/sda1")); - assertEquals(options.buildFormParameters().get("BlockDeviceMapping.1.Ebs.VolumeSize"), Collections - .singletonList("120")); - assertEquals(options.buildFormParameters().get("BlockDeviceMapping.1.Ebs.DeleteOnTermination"), Collections - .singletonList("true")); + assertEquals(options.buildFormParameters().get("BlockDeviceMapping.1.DeviceName"), + ImmutableList.of("/dev/sda1")); + assertEquals(options.buildFormParameters().get("BlockDeviceMapping.1.Ebs.VolumeSize"), + ImmutableList.of("120")); + assertEquals(options.buildFormParameters().get("BlockDeviceMapping.1.Ebs.DeleteOnTermination"), + ImmutableList.of("true")); } @Test(expectedExceptions = NullPointerException.class) diff --git a/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/options/DescribeSpotPriceHistoryOptionsTest.java b/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/options/DescribeSpotPriceHistoryOptionsTest.java index 9d0f9de63e..ad95d18559 100644 --- a/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/options/DescribeSpotPriceHistoryOptionsTest.java +++ b/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/options/DescribeSpotPriceHistoryOptionsTest.java @@ -24,9 +24,9 @@ import static org.jclouds.aws.ec2.options.DescribeSpotPriceHistoryOptions.Builde import static org.jclouds.aws.ec2.options.DescribeSpotPriceHistoryOptions.Builder.to; import static org.testng.Assert.assertEquals; -import java.util.Collections; import java.util.Date; +import com.google.common.collect.ImmutableList; import org.jclouds.http.options.HttpRequestOptions; import org.testng.annotations.Test; @@ -48,13 +48,13 @@ public class DescribeSpotPriceHistoryOptionsTest { public void testDescription() { DescribeSpotPriceHistoryOptions options = new DescribeSpotPriceHistoryOptions(); options.productDescription("test"); - assertEquals(options.buildFormParameters().get("ProductDescription"), Collections.singletonList("test")); + assertEquals(options.buildFormParameters().get("ProductDescription"), ImmutableList.of("test")); } @Test public void testDescriptionStatic() { DescribeSpotPriceHistoryOptions options = productDescription("test"); - assertEquals(options.buildFormParameters().get("ProductDescription"), Collections.singletonList("test")); + assertEquals(options.buildFormParameters().get("ProductDescription"), ImmutableList.of("test")); } @Test(expectedExceptions = NullPointerException.class) @@ -66,13 +66,13 @@ public class DescribeSpotPriceHistoryOptionsTest { public void testInstanceType() { DescribeSpotPriceHistoryOptions options = new DescribeSpotPriceHistoryOptions(); options.instanceType("test"); - assertEquals(options.buildFormParameters().get("InstanceType.1"), Collections.singletonList("test")); + assertEquals(options.buildFormParameters().get("InstanceType.1"), ImmutableList.of("test")); } @Test public void testInstanceTypeStatic() { DescribeSpotPriceHistoryOptions options = instanceType("test"); - assertEquals(options.buildFormParameters().get("InstanceType.1"), Collections.singletonList("test")); + assertEquals(options.buildFormParameters().get("InstanceType.1"), ImmutableList.of("test")); } @Test(expectedExceptions = NullPointerException.class) @@ -84,7 +84,7 @@ public class DescribeSpotPriceHistoryOptionsTest { public void testFrom() { DescribeSpotPriceHistoryOptions options = new DescribeSpotPriceHistoryOptions(); options.from(test); - assertEquals(options.buildFormParameters().get("StartTime"), Collections.singletonList("1970-05-23T21:21:18.910Z")); + assertEquals(options.buildFormParameters().get("StartTime"), ImmutableList.of("1970-05-23T21:21:18.910Z")); } Date test = new Date(12345678910l); @@ -92,7 +92,7 @@ public class DescribeSpotPriceHistoryOptionsTest { @Test public void testFromStatic() { DescribeSpotPriceHistoryOptions options = from(test); - assertEquals(options.buildFormParameters().get("StartTime"), Collections.singletonList("1970-05-23T21:21:18.910Z")); + assertEquals(options.buildFormParameters().get("StartTime"), ImmutableList.of("1970-05-23T21:21:18.910Z")); } @Test(expectedExceptions = NullPointerException.class) @@ -104,13 +104,13 @@ public class DescribeSpotPriceHistoryOptionsTest { public void testTo() { DescribeSpotPriceHistoryOptions options = new DescribeSpotPriceHistoryOptions(); options.to(test); - assertEquals(options.buildFormParameters().get("EndTime"), Collections.singletonList("1970-05-23T21:21:18.910Z")); + assertEquals(options.buildFormParameters().get("EndTime"), ImmutableList.of("1970-05-23T21:21:18.910Z")); } @Test public void testToStatic() { DescribeSpotPriceHistoryOptions options = to(test); - assertEquals(options.buildFormParameters().get("EndTime"), Collections.singletonList("1970-05-23T21:21:18.910Z")); + assertEquals(options.buildFormParameters().get("EndTime"), ImmutableList.of("1970-05-23T21:21:18.910Z")); } @Test(expectedExceptions = NullPointerException.class) diff --git a/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/options/RequestSpotInstancesOptionsTest.java b/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/options/RequestSpotInstancesOptionsTest.java index f8c6eabcf6..13f2d10e6a 100644 --- a/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/options/RequestSpotInstancesOptionsTest.java +++ b/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/options/RequestSpotInstancesOptionsTest.java @@ -25,9 +25,10 @@ import static org.jclouds.aws.ec2.options.RequestSpotInstancesOptions.Builder.va import static org.jclouds.aws.ec2.options.RequestSpotInstancesOptions.Builder.validUntil; import static org.testng.Assert.assertEquals; -import java.util.Collections; import java.util.Date; +import com.google.common.collect.ImmutableList; + import org.jclouds.aws.ec2.domain.SpotInstanceRequest; import org.jclouds.http.options.HttpRequestOptions; import org.testng.annotations.Test; @@ -49,13 +50,13 @@ public class RequestSpotInstancesOptionsTest { public void testAvailabilityZoneGroup() { RequestSpotInstancesOptions options = new RequestSpotInstancesOptions(); options.availabilityZoneGroup("test"); - assertEquals(options.buildFormParameters().get("AvailabilityZoneGroup"), Collections.singletonList("test")); + assertEquals(options.buildFormParameters().get("AvailabilityZoneGroup"), ImmutableList.of("test")); } @Test public void testAvailabilityZoneGroupStatic() { RequestSpotInstancesOptions options = availabilityZoneGroup("test"); - assertEquals(options.buildFormParameters().get("AvailabilityZoneGroup"), Collections.singletonList("test")); + assertEquals(options.buildFormParameters().get("AvailabilityZoneGroup"), ImmutableList.of("test")); } @Test(expectedExceptions = NullPointerException.class) @@ -67,13 +68,13 @@ public class RequestSpotInstancesOptionsTest { public void testLaunchGroup() { RequestSpotInstancesOptions options = new RequestSpotInstancesOptions(); options.launchGroup("test"); - assertEquals(options.buildFormParameters().get("LaunchGroup"), Collections.singletonList("test")); + assertEquals(options.buildFormParameters().get("LaunchGroup"), ImmutableList.of("test")); } @Test public void testLaunchGroupStatic() { RequestSpotInstancesOptions options = launchGroup("test"); - assertEquals(options.buildFormParameters().get("LaunchGroup"), Collections.singletonList("test")); + assertEquals(options.buildFormParameters().get("LaunchGroup"), ImmutableList.of("test")); } @Test(expectedExceptions = NullPointerException.class) @@ -85,13 +86,13 @@ public class RequestSpotInstancesOptionsTest { public void testInstanceType() { RequestSpotInstancesOptions options = new RequestSpotInstancesOptions(); options.type(SpotInstanceRequest.Type.PERSISTENT); - assertEquals(options.buildFormParameters().get("Type"), Collections.singletonList("persistent")); + assertEquals(options.buildFormParameters().get("Type"), ImmutableList.of("persistent")); } @Test public void testInstanceTypeStatic() { RequestSpotInstancesOptions options = type(SpotInstanceRequest.Type.PERSISTENT); - assertEquals(options.buildFormParameters().get("Type"), Collections.singletonList("persistent")); + assertEquals(options.buildFormParameters().get("Type"), ImmutableList.of("persistent")); } @Test(expectedExceptions = NullPointerException.class) @@ -104,7 +105,7 @@ public class RequestSpotInstancesOptionsTest { RequestSpotInstancesOptions options = new RequestSpotInstancesOptions(); options.validFrom(test); assertEquals(options.buildFormParameters().get("ValidFrom"), - Collections.singletonList("1970-05-23T21:21:18Z")); + ImmutableList.of("1970-05-23T21:21:18Z")); } Date test = new Date(12345678910l); @@ -113,7 +114,7 @@ public class RequestSpotInstancesOptionsTest { public void testFromStatic() { RequestSpotInstancesOptions options = validFrom(test); assertEquals(options.buildFormParameters().get("ValidFrom"), - Collections.singletonList("1970-05-23T21:21:18Z")); + ImmutableList.of("1970-05-23T21:21:18Z")); } @Test(expectedExceptions = NullPointerException.class) @@ -126,14 +127,14 @@ public class RequestSpotInstancesOptionsTest { RequestSpotInstancesOptions options = new RequestSpotInstancesOptions(); options.validUntil(test); assertEquals(options.buildFormParameters().get("ValidUntil"), - Collections.singletonList("1970-05-23T21:21:18Z")); + ImmutableList.of("1970-05-23T21:21:18Z")); } @Test public void testToStatic() { RequestSpotInstancesOptions options = validUntil(test); assertEquals(options.buildFormParameters().get("ValidUntil"), - Collections.singletonList("1970-05-23T21:21:18Z")); + ImmutableList.of("1970-05-23T21:21:18Z")); } @Test(expectedExceptions = NullPointerException.class) diff --git a/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/parse/DescribeInstancesResponseTest.java b/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/parse/DescribeInstancesResponseTest.java new file mode 100644 index 0000000000..646853fcfd --- /dev/null +++ b/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/parse/DescribeInstancesResponseTest.java @@ -0,0 +1,114 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.aws.ec2.parse; + +import static org.testng.Assert.assertEquals; + +import java.io.InputStream; +import java.util.Set; + +import org.jclouds.aws.ec2.domain.AWSRunningInstance; +import org.jclouds.aws.ec2.domain.MonitoringState; +import org.jclouds.aws.ec2.xml.AWSDescribeInstancesResponseHandler; +import org.jclouds.date.DateService; +import org.jclouds.ec2.domain.Attachment; +import org.jclouds.ec2.domain.BlockDevice; +import org.jclouds.ec2.domain.Hypervisor; +import org.jclouds.ec2.domain.InstanceState; +import org.jclouds.ec2.domain.Reservation; +import org.jclouds.ec2.domain.RootDeviceType; +import org.jclouds.ec2.domain.RunningInstance; +import org.jclouds.ec2.xml.BaseEC2HandlerTest; +import org.testng.annotations.BeforeTest; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableSet; + +/** + * Tests behavior of {@code AWSDescribeInstancesResponseHandler} + * + * @author Adrian Cole + */ +// NOTE:without testName, this will not call @Before* and fail w/NPE during +// surefire +@Test(groups = "unit", testName = "AWSDescribeInstancesResponseHandlerTest") +public class DescribeInstancesResponseTest extends BaseEC2HandlerTest { + + private DateService dateService; + + @BeforeTest + @Override + protected void setUpInjector() { + super.setUpInjector(); + dateService = injector.getInstance(DateService.class); + assert dateService != null; + } + + public void test() { + InputStream is = getClass().getResourceAsStream("/describe_instances_pending.xml"); + + Set> expected = expected(); + + AWSDescribeInstancesResponseHandler handler = injector.getInstance(AWSDescribeInstancesResponseHandler.class); + Set> result = factory.create(handler).parse(is); + + assertEquals(result.toString(), expected.toString()); + + } + + public Set> expected() { + return ImmutableSet.of(Reservation.builder() + .region(defaultRegion) + .reservationId("r-3f056a58") + .ownerId("095072994936") +// sg-f788299f + .groupName("launchpad_sec_group") +// sg-7e512116 + .groupName("jclouds#4c858090-f66c-4225-aa57-6fcaa42198ae") + .instance(AWSRunningInstance.builder() + .region(defaultRegion) + .instanceId("i-32451248") + .imageId("ami-bf8131d6") + .rawState("pending") + .instanceState(InstanceState.PENDING) + .privateDnsName("ip-10-194-149-220.ec2.internal") + .dnsName("ec2-23-20-17-42.compute-1.amazonaws.com") + .keyName("jclouds#4c858090-f66c-4225-aa57-6fcaa42198ae#105") + .amiLaunchIndex("0") + .instanceType("c1.medium") + .launchTime(dateService.iso8601DateParse("2012-09-14T20:01:34.000Z")) + .availabilityZone("us-east-1d") +// .tenancy("default") + .kernelId("aki-825ea7eb") + .monitoringState(MonitoringState.DISABLED) + .privateIpAddress("10.194.149.220") + .ipAddress("23.20.17.42") + .securityGroupIdToName("sg-f788299f", "launchpad_sec_group") + .securityGroupIdToName("sg-7e512116", "jclouds#4c858090-f66c-4225-aa57-6fcaa42198ae") +// .architecture("x86_64") + .rootDeviceType(RootDeviceType.EBS) + .rootDeviceName("/dev/sda1") + .device("/dev/sda1", new BlockDevice("vol-b2beb3c9", Attachment.Status.ATTACHING, dateService.iso8601DateParse("2012-09-14T20:01:37.000Z"), true)) + .virtualizationType("paravirtual") + .tag("Name", "4c858090-f66c-4225-aa57-6fcaa42198ae-32451248") + .hypervisor(Hypervisor.XEN) + .build()).build()); + } + +} diff --git a/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/parse/DescribeSecurityGroupsResponseTest.java b/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/parse/DescribeSecurityGroupsResponseTest.java new file mode 100644 index 0000000000..0394d2baae --- /dev/null +++ b/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/parse/DescribeSecurityGroupsResponseTest.java @@ -0,0 +1,87 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.aws.ec2.parse; + +import static org.easymock.EasyMock.createMock; +import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.replay; +import static org.testng.Assert.assertEquals; + +import java.io.InputStream; +import java.util.Set; + +import org.jclouds.ec2.domain.IpPermission; +import org.jclouds.ec2.domain.IpProtocol; +import org.jclouds.ec2.domain.SecurityGroup; +import org.jclouds.ec2.xml.BaseEC2HandlerTest; +import org.jclouds.ec2.xml.DescribeSecurityGroupsResponseHandler; +import org.jclouds.http.functions.ParseSax; +import org.jclouds.rest.internal.GeneratedHttpRequest; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableSet; + +/** + * + * @author Adrian Cole + */ +// NOTE:without testName, this will not call @Before* and fail w/NPE during +// surefire +@Test(groups = "unit", testName = "DescribeSecurityGroupsResponseTest") +public class DescribeSecurityGroupsResponseTest extends BaseEC2HandlerTest { + + public void test() { + InputStream is = getClass().getResourceAsStream("/describe_security_groups_vpc.xml"); + + Set expected = expected(); + + DescribeSecurityGroupsResponseHandler handler = injector.getInstance(DescribeSecurityGroupsResponseHandler.class); + addDefaultRegionToHandler(handler); + Set result = factory.create(handler).parse(is); + + assertEquals(result.toString(), expected.toString()); + } + + public Set expected() { + return ImmutableSet.of(SecurityGroup.builder() + .region(defaultRegion) + .ownerId("123123123123") + .id("sg-11111111") + .name("default") + .description("default VPC security group") +// .vpcId("vpc-99999999") + .ipPermission(IpPermission.builder() + .ipProtocol(IpProtocol.ALL) + .userIdGroupPair("123123123123","sg-11111111").build()) +// .ipPermissionEgress(IpPermission.builder() +// .ipProtocol(IpProtocol.ALL) +// .ipRange("0.0.0.0/0").build()) + .build()); + + } + + private void addDefaultRegionToHandler(ParseSax.HandlerWithResult handler) { + GeneratedHttpRequest request = createMock(GeneratedHttpRequest.class); + expect(request.getArgs()).andReturn(ImmutableList. of()).atLeastOnce(); + replay(request); + handler.setContext(request); + } + +} diff --git a/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/services/PlacementGroupClientLiveTest.java b/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/services/PlacementGroupClientLiveTest.java index 9d33a3b6ef..dc93bd90f3 100644 --- a/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/services/PlacementGroupClientLiveTest.java +++ b/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/services/PlacementGroupClientLiveTest.java @@ -63,7 +63,7 @@ import com.google.inject.Module; */ @Test(groups = "live", singleThreaded = true, testName = "PlacementGroupClientLiveTest") public class PlacementGroupClientLiveTest extends BaseComputeServiceContextLiveTest { - ArrayList supportedRegions = newArrayList(Region.US_EAST_1, Region.EU_WEST_1); + ArrayList supportedRegions = newArrayList(Region.US_EAST_1, Region.US_WEST_2, Region.EU_WEST_1); public PlacementGroupClientLiveTest() { provider = "aws-ec2"; diff --git a/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/services/SpotInstanceClientLiveTest.java b/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/services/SpotInstanceClientLiveTest.java index 7bbc22c6ee..26188dc5f7 100644 --- a/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/services/SpotInstanceClientLiveTest.java +++ b/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/services/SpotInstanceClientLiveTest.java @@ -41,7 +41,7 @@ import org.jclouds.aws.ec2.predicates.SpotInstanceRequestActive; import org.jclouds.compute.internal.BaseComputeServiceContextLiveTest; import org.jclouds.ec2.domain.InstanceType; import org.jclouds.predicates.RetryablePredicate; -import org.testng.annotations.AfterTest; +import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; @@ -160,8 +160,9 @@ public class SpotInstanceClientLiveTest extends BaseComputeServiceContextLiveTe public static final String PREFIX = System.getProperty("user.name") + "ec2"; - @AfterTest - public void shutdown() { + @Override + @AfterClass(groups = { "integration", "live" }) + protected void tearDownContext() { if (requests != null) { for (SpotInstanceRequest request : requests) client.getSpotInstanceServices().cancelSpotInstanceRequestsInRegion(request.getRegion(), request.getId()); @@ -170,5 +171,6 @@ public class SpotInstanceClientLiveTest extends BaseComputeServiceContextLiveTe if (instance != null) { client.getInstanceServices().terminateInstancesInRegion(instance.getRegion(), instance.getId()); } + super.tearDownContext(); } } diff --git a/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/services/TagClientLiveTest.java b/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/services/TagClientLiveTest.java index 42286e54a5..f6d3466159 100644 --- a/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/services/TagClientLiveTest.java +++ b/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/services/TagClientLiveTest.java @@ -30,7 +30,7 @@ import org.jclouds.aws.ec2.domain.Tag; import org.jclouds.aws.ec2.util.TagFilters; import org.jclouds.aws.ec2.util.TagFilters.ResourceType; import org.jclouds.compute.internal.BaseComputeServiceContextLiveTest; -import org.testng.annotations.AfterGroups; +import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; @@ -69,9 +69,11 @@ public class TagClientLiveTest extends BaseComputeServiceContextLiveTest { } } - @AfterGroups(groups = { "live" }) - public void deleteSecurityGroup() { + @Override + @AfterClass(groups = { "integration", "live" }) + protected void tearDownContext() { view.unwrap(AWSEC2ApiMetadata.CONTEXT_TOKEN).getApi().getSecurityGroupServices().deleteSecurityGroupInRegionById(null, testGroup); + super.tearDownContext(); } public static final String PREFIX = System.getProperty("user.name") + "-ec2"; diff --git a/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/xml/AWSDescribeInstancesResponseHandlerTest.java b/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/xml/AWSDescribeInstancesResponseHandlerTest.java index 25aa26bc7c..c247bf23a0 100644 --- a/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/xml/AWSDescribeInstancesResponseHandlerTest.java +++ b/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/xml/AWSDescribeInstancesResponseHandlerTest.java @@ -31,7 +31,6 @@ import org.jclouds.ec2.domain.Attachment; import org.jclouds.ec2.domain.BlockDevice; import org.jclouds.ec2.domain.Hypervisor; import org.jclouds.ec2.domain.InstanceState; -import org.jclouds.ec2.domain.InstanceType; import org.jclouds.ec2.domain.Reservation; import org.jclouds.ec2.domain.RootDeviceType; import org.jclouds.ec2.domain.RunningInstance; @@ -71,44 +70,13 @@ public class AWSDescribeInstancesResponseHandlerTest extends BaseEC2HandlerTest assert dateService != null; } - public void testWhenRunning() throws UnknownHostException { - - Set> contents = ImmutableSet.of( - new Reservation(defaultRegion, ImmutableSet.of("adriancole.ec2ingress"), ImmutableSet.of( - new AWSRunningInstance.Builder() - .region(defaultRegion) - .groupId("adriancole.ec2ingress") - .amiLaunchIndex("0") - .dnsName("ec2-174-129-81-68.compute-1.amazonaws.com") - .imageId("ami-82e4b5c7") - .instanceId("i-0799056f") - .instanceState(InstanceState.RUNNING) - .rawState("running") - .instanceType(InstanceType.M1_SMALL) - .ipAddress("174.129.81.68") - .kernelId("aki-a71cf9ce") - .keyName("adriancole.ec21") - .launchTime(dateService.iso8601DateParse("2009-11-09T03:00:34.000Z")) - .monitoringState(MonitoringState.DISABLED) - .availabilityZone("us-east-1c") - .virtualizationType("paravirtual") - .privateDnsName("ip-10-243-42-70.ec2.internal") - .privateIpAddress("10.243.42.70") - .ramdiskId("ari-a51cf9cc") - .rootDeviceType(RootDeviceType.INSTANCE_STORE) - .hypervisor(Hypervisor.XEN) - .build()), - "993194456877", null, "r-a3c508cb")); - - Set> result = parseAWSRunningInstances("/describe_instances_running.xml"); - - assertEquals(result.toString(), contents.toString()); - } public void testWhenRunningLatest() throws UnknownHostException { - Set> contents = ImmutableSet.of(new Reservation( - defaultRegion, ImmutableSet.of("jclouds#ec2-s#us-east-1"), ImmutableSet.of( - new AWSRunningInstance.Builder() + Set> contents = ImmutableSet.of(Reservation.builder() + .region(defaultRegion) + .reservationId("r-0f4c2160") + .groupName("jclouds#zkclustertest#us-east-1") + .instance(AWSRunningInstance.builder() .region(defaultRegion) .instanceId("i-911444f0") .imageId("ami-63be790a") @@ -135,8 +103,8 @@ public class AWSDescribeInstancesResponseHandlerTest extends BaseEC2HandlerTest new BlockDevice("vol-5829fc32", Attachment.Status.ATTACHED, dateService .iso8601DateParse("2011-08-16T13:41:19.000Z"), true)) .hypervisor(Hypervisor.XEN) - .virtualizationType("paravirtual").build(),// - new AWSRunningInstance.Builder() + .virtualizationType("paravirtual").build()) + .instance(AWSRunningInstance.builder() .region(defaultRegion) .instanceId("i-931444f2") .imageId("ami-63be790a") @@ -162,7 +130,7 @@ public class AWSDescribeInstancesResponseHandlerTest extends BaseEC2HandlerTest new BlockDevice("vol-5029fc3a", Attachment.Status.ATTACHED, dateService .iso8601DateParse("2011-08-16T13:41:19.000Z"), true)) .hypervisor(Hypervisor.XEN) - .virtualizationType("paravirtual").build()), defaultRegion, defaultRegion, defaultRegion)); + .virtualizationType("paravirtual").build()).build()); Set> result = parseAWSRunningInstances("/describe_instances_latest.xml"); @@ -175,76 +143,6 @@ public class AWSDescribeInstancesResponseHandlerTest extends BaseEC2HandlerTest parseAWSRunningInstances("/describe_instances_3.xml"); } - public void testApplyInputStream() { - Set> contents = ImmutableSet.of(new Reservation( - defaultRegion, ImmutableSet.of("default"), ImmutableSet.of( - new AWSRunningInstance.Builder().region(defaultRegion).groupId("default").amiLaunchIndex("23") - .dnsName("ec2-72-44-33-4.compute-1.amazonaws.com").imageId("ami-6ea54007") - .instanceId("i-28a64341").instanceState(InstanceState.RUNNING).rawState("running") - .instanceType(InstanceType.M1_LARGE).kernelId("aki-ba3adfd3").keyName("example-key-name") - .launchTime(dateService.iso8601DateParse("2007-08-07T11:54:42.000Z")) - .monitoringState(MonitoringState.DISABLED).availabilityZone("us-east-1b") - .virtualizationType("paravirtual").privateDnsName("10-251-50-132.ec2.internal") - .productCode("774F4FF8").ramdiskId("ari-badbad00") - .hypervisor(Hypervisor.XEN) - .rootDeviceType(RootDeviceType.INSTANCE_STORE).build(), - new AWSRunningInstance.Builder().region(defaultRegion).groupId("default").amiLaunchIndex("23") - .dnsName("ec2-72-44-33-6.compute-1.amazonaws.com").imageId("ami-6ea54007") - .instanceId("i-28a64435").instanceState(InstanceState.RUNNING).rawState("running") - .instanceType(InstanceType.M1_LARGE).kernelId("aki-ba3adfd3").keyName("example-key-name") - .launchTime(dateService.iso8601DateParse("2007-08-07T11:54:42.000Z")) - .monitoringState(MonitoringState.DISABLED).availabilityZone("us-east-1b") - .virtualizationType("paravirtual").privateDnsName("10-251-50-134.ec2.internal") - .productCode("774F4FF8").ramdiskId("ari-badbad00") - .hypervisor(Hypervisor.XEN) - .rootDeviceType(RootDeviceType.INSTANCE_STORE).build()), "UYY3TLBUXIEON5NQVUUX6OMPWBZIQNFM", - null, "r-44a5402d")); - - Set> result = parseAWSRunningInstances("/describe_instances.xml"); - - assertEquals(result.toString(), contents.toString()); - } - - public void testEBS() throws UnknownHostException { - - Set> contents = ImmutableSet.of(new Reservation( - defaultRegion, ImmutableSet.of("adriancole.ec2ebsingress"), ImmutableSet - .of(new AWSRunningInstance.Builder() - .region(defaultRegion) - .groupId("adriancole.ec2ebsingress") - .amiLaunchIndex("0") - .dnsName("ec2-75-101-203-146.compute-1.amazonaws.com") - .imageId("ami-849875ed") - .instanceId("i-e564438d") - .instanceState(InstanceState.RUNNING) - .rawState("running") - .instanceType(InstanceType.M1_SMALL) - .ipAddress("75.101.203.146") - .kernelId("aki-a71cf9ce") - .keyName("adriancole.ec2ebs1") - .launchTime(dateService.iso8601DateParse("2009-12-30T04:06:23.000Z")) - .monitoringState(MonitoringState.DISABLED) - .availabilityZone("us-east-1b") - .placementGroup("placement") - .virtualizationType("hvm") - .privateDnsName("domU-12-31-39-09-CE-53.compute-1.internal") - .privateIpAddress("10.210.209.157") - .ramdiskId("ari-a51cf9cc") - .hypervisor(Hypervisor.XEN) - .rootDeviceType(RootDeviceType.EBS) - .rootDeviceName("/dev/sda1") - .hypervisor(Hypervisor.XEN) - .device( - "/dev/sda1", - new BlockDevice("vol-dc6ca8b5", Attachment.Status.ATTACHED, dateService - .iso8601DateParse("2009-12-30T04:06:29.000Z"), true)).build()), "993194456877", - null, "r-596dd731")); - - Set> result = parseAWSRunningInstances("/describe_instances_ebs.xml"); - - assertEquals(result.toString(), contents.toString()); - } - static ParseSax>> createParser() { Injector injector = Guice.createInjector(new SaxParserModule(), new AbstractModule() { diff --git a/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/xml/AWSRunInstancesResponseHandlerTest.java b/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/xml/AWSRunInstancesResponseHandlerTest.java index 09547f97e9..73d4a37eaa 100644 --- a/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/xml/AWSRunInstancesResponseHandlerTest.java +++ b/providers/aws-ec2/src/test/java/org/jclouds/aws/ec2/xml/AWSRunInstancesResponseHandlerTest.java @@ -44,7 +44,6 @@ import org.testng.annotations.Test; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableSet; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.TypeLiteral; @@ -82,28 +81,25 @@ public class AWSRunInstancesResponseHandlerTest extends BaseEC2HandlerTest { InputStream is = getClass().getResourceAsStream("/run_instances.xml"); - Reservation expected = new Reservation(defaultRegion, - ImmutableSet.of("default"), ImmutableSet.of( - - new AWSRunningInstance.Builder().region(defaultRegion).groupId("default").amiLaunchIndex("0").imageId( + Reservation expected = Reservation.builder() + .region(defaultRegion) + .instance(AWSRunningInstance.builder().region(defaultRegion).groupName("default").amiLaunchIndex("0").imageId( "ami-60a54009").instanceId("i-2ba64342").instanceState(InstanceState.PENDING).rawState( "pending").instanceType(InstanceType.M1_SMALL).keyName("example-key-name").launchTime( dateService.iso8601DateParse("2007-08-07T11:51:50.000Z")).hypervisor(Hypervisor.XEN) - .monitoringState(MonitoringState.ENABLED).availabilityZone("us-east-1b").build(), - - new AWSRunningInstance.Builder().region(defaultRegion).groupId("default").amiLaunchIndex("1").imageId( + .monitoringState(MonitoringState.ENABLED).availabilityZone("us-east-1b").build()) + .instance(AWSRunningInstance.builder().region(defaultRegion).groupName("default").amiLaunchIndex("1").imageId( "ami-60a54009").instanceId("i-2bc64242").instanceState(InstanceState.PENDING).rawState( "pending").instanceType(InstanceType.M1_SMALL).keyName("example-key-name").launchTime( dateService.iso8601DateParse("2007-08-07T11:51:50.000Z")).hypervisor(Hypervisor.XEN) - .monitoringState(MonitoringState.ENABLED).availabilityZone("us-east-1b").build(), - - new AWSRunningInstance.Builder().region(defaultRegion).groupId("default").amiLaunchIndex("2").imageId( + .monitoringState(MonitoringState.ENABLED).availabilityZone("us-east-1b").build()) + .instance(AWSRunningInstance.builder().region(defaultRegion).groupName("default").amiLaunchIndex("2").imageId( "ami-60a54009").instanceId("i-2be64332").instanceState(InstanceState.PENDING).rawState( "pending").instanceType(InstanceType.M1_SMALL).keyName("example-key-name").launchTime( dateService.iso8601DateParse("2007-08-07T11:51:50.000Z")).hypervisor(Hypervisor.XEN) .monitoringState(MonitoringState.ENABLED).availabilityZone("us-east-1b").build()) - - , "AIDADH4IGTRXXKCD", null, "r-47a5402e"); + .ownerId("AIDADH4IGTRXXKCD") + .reservationId("r-47a5402e").build(); AWSRunInstancesResponseHandler handler = injector.getInstance(AWSRunInstancesResponseHandler.class); addDefaultRegionToHandler(handler); diff --git a/providers/aws-ec2/src/test/resources/describe_instances_pending.xml b/providers/aws-ec2/src/test/resources/describe_instances_pending.xml new file mode 100644 index 0000000000..92f9f4ebe4 --- /dev/null +++ b/providers/aws-ec2/src/test/resources/describe_instances_pending.xml @@ -0,0 +1,82 @@ + + + dcd37ecf-e5b6-462b-99a8-112427b3e3a2 + + + r-3f056a58 + 095072994936 + + + sg-f788299f + launchpad_sec_group + + + sg-7e512116 + jclouds#4c858090-f66c-4225-aa57-6fcaa42198ae + + + + + i-32451248 + ami-bf8131d6 + + 0 + pending + + ip-10-194-149-220.ec2.internal + ec2-23-20-17-42.compute-1.amazonaws.com + + jclouds#4c858090-f66c-4225-aa57-6fcaa42198ae#105 + 0 + + c1.medium + 2012-09-14T20:01:34.000Z + + us-east-1d + + default + + aki-825ea7eb + + disabled + + 10.194.149.220 + 23.20.17.42 + + + sg-f788299f + launchpad_sec_group + + + sg-7e512116 + jclouds#4c858090-f66c-4225-aa57-6fcaa42198ae + + + x86_64 + ebs + /dev/sda1 + + + /dev/sda1 + + vol-b2beb3c9 + attaching + 2012-09-14T20:01:37.000Z + true + + + + paravirtual + + + + Name + 4c858090-f66c-4225-aa57-6fcaa42198ae-32451248 + + + xen + + + + + \ No newline at end of file diff --git a/providers/aws-ec2/src/test/resources/describe_security_groups_vpc.xml b/providers/aws-ec2/src/test/resources/describe_security_groups_vpc.xml new file mode 100644 index 0000000000..cd635b4e71 --- /dev/null +++ b/providers/aws-ec2/src/test/resources/describe_security_groups_vpc.xml @@ -0,0 +1,35 @@ + + xxxxxxxxxxxxxxxx + + + 123123123123 + sg-11111111 + default + default VPC security group + vpc-99999999 + + + -1 + + + 123123123123 + sg-11111111 + + + + + + + + -1 + + + + 0.0.0.0/0 + + + + + + + \ No newline at end of file diff --git a/providers/aws-s3/pom.xml b/providers/aws-s3/pom.xml index df59d53a4b..cfa0af99c0 100644 --- a/providers/aws-s3/pom.xml +++ b/providers/aws-s3/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider diff --git a/providers/aws-s3/src/test/java/org/jclouds/aws/s3/AWSS3ClientLiveTest.java b/providers/aws-s3/src/test/java/org/jclouds/aws/s3/AWSS3ClientLiveTest.java index 568a7f8f71..2cae80a94e 100644 --- a/providers/aws-s3/src/test/java/org/jclouds/aws/s3/AWSS3ClientLiveTest.java +++ b/providers/aws-s3/src/test/java/org/jclouds/aws/s3/AWSS3ClientLiveTest.java @@ -111,7 +111,7 @@ public class AWSS3ClientLiveTest extends S3ClientLiveTest { String key = "constitution.txt"; String uploadId = getApi().initiateMultipartUpload(containerName, ObjectMetadataBuilder.create().key(key).contentMD5(oneHundredOneConstitutionsMD5).build()); - byte[] buffer = toByteArray(oneHundredOneConstitutions.getInput()); + byte[] buffer = toByteArray(oneHundredOneConstitutions); assertEquals(oneHundredOneConstitutionsLength, (long) buffer.length); Payload part1 = newByteArrayPayload(buffer); @@ -153,7 +153,7 @@ public class AWSS3ClientLiveTest extends S3ClientLiveTest { public void testMultipartChunkedFileStream() throws IOException, InterruptedException { FileOutputStream fous = new FileOutputStream(new File("target/const.txt")); - ByteStreams.copy(oneHundredOneConstitutions.getInput(), fous); + ByteStreams.copy(oneHundredOneConstitutions, fous); fous.flush(); fous.close(); String containerName = getContainerName(); diff --git a/providers/aws-s3/src/test/java/org/jclouds/aws/s3/blobstore/integration/PathBasedContainerLiveTest.java b/providers/aws-s3/src/test/java/org/jclouds/aws/s3/blobstore/integration/PathBasedContainerLiveTest.java new file mode 100644 index 0000000000..27daa6e005 --- /dev/null +++ b/providers/aws-s3/src/test/java/org/jclouds/aws/s3/blobstore/integration/PathBasedContainerLiveTest.java @@ -0,0 +1,44 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.aws.s3.blobstore.integration; + +import static org.jclouds.s3.reference.S3Constants.PROPERTY_S3_VIRTUAL_HOST_BUCKETS; + +import java.util.Properties; + +import org.jclouds.s3.blobstore.integration.S3ContainerLiveTest; +import org.testng.annotations.Test; + +/** + * @author Adrian Cole + */ +@Test(groups = "live", singleThreaded = true, testName = "PathBasedContainerLiveTest") +public class PathBasedContainerLiveTest extends S3ContainerLiveTest { + public PathBasedContainerLiveTest() { + provider = "aws-s3"; + } + + @Override + public Properties setupProperties() { + Properties properties = super.setupProperties(); + properties.setProperty(PROPERTY_S3_VIRTUAL_HOST_BUCKETS, "false"); + return properties; + } + +} diff --git a/providers/aws-sqs/pom.xml b/providers/aws-sqs/pom.xml new file mode 100644 index 0000000000..7f6db14e16 --- /dev/null +++ b/providers/aws-sqs/pom.xml @@ -0,0 +1,114 @@ + + + + 4.0.0 + + org.jclouds + jclouds-project + 1.6.0-SNAPSHOT + ../../project/pom.xml + + org.jclouds.provider + aws-sqs + jclouds Amazon Simple Queue Service provider + Simple Queue Service implementation targeted to Amazon Web Services + bundle + + + https://sqs.us-east-1.amazonaws.com + 2011-10-01 + + ${test.aws.identity} + ${test.aws.credential} + + org.jclouds.aws.sqs*;version="${project.version}" + org.jclouds*;version="${project.version}",* + + + + + org.jclouds.api + sqs + ${project.version} + jar + + + org.jclouds.api + sqs + ${project.version} + test-jar + test + + + org.jclouds + jclouds-core + ${project.version} + test-jar + test + + + org.jclouds.driver + jclouds-slf4j + ${project.version} + test + + + ch.qos.logback + logback-classic + 1.0.0 + test + + + + + + live + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration + integration-test + + test + + + + ${test.aws-sqs.endpoint} + ${test.aws-sqs.api-version} + ${test.aws-sqs.build-version} + ${test.aws-sqs.identity} + ${test.aws-sqs.credential} + + + + + + + + + + + diff --git a/providers/aws-sqs/src/main/java/org/jclouds/aws/sqs/AWSSQSProviderMetadata.java b/providers/aws-sqs/src/main/java/org/jclouds/aws/sqs/AWSSQSProviderMetadata.java new file mode 100644 index 0000000000..5b85c987ea --- /dev/null +++ b/providers/aws-sqs/src/main/java/org/jclouds/aws/sqs/AWSSQSProviderMetadata.java @@ -0,0 +1,107 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.aws.sqs; + +import static org.jclouds.aws.domain.Region.AP_NORTHEAST_1; +import static org.jclouds.aws.domain.Region.AP_SOUTHEAST_1; +import static org.jclouds.aws.domain.Region.EU_WEST_1; +import static org.jclouds.aws.domain.Region.SA_EAST_1; +import static org.jclouds.aws.domain.Region.US_EAST_1; +import static org.jclouds.aws.domain.Region.US_WEST_1; +import static org.jclouds.aws.domain.Region.US_WEST_2; +import static org.jclouds.location.reference.LocationConstants.PROPERTY_REGION; + +import java.net.URI; +import java.util.Properties; + +import org.jclouds.aws.domain.Region; +import org.jclouds.sqs.SQSApiMetadata; +import org.jclouds.providers.ProviderMetadata; +import org.jclouds.providers.internal.BaseProviderMetadata; + +/** + * Implementation of @ link org.jclouds.types.ProviderMetadata} for Amazon's Simple Queue Service + * provider. + * + * @author Adrian Cole + */ +public class AWSSQSProviderMetadata extends BaseProviderMetadata { + + /** The serialVersionUID */ + private static final long serialVersionUID = 7750012233546655021L; + + public static Builder builder() { + return new Builder(); + } + + @Override + public Builder toBuilder() { + return Builder.class.cast(builder().fromProviderMetadata(this)); + } + + public AWSSQSProviderMetadata() { + super(builder()); + } + + public AWSSQSProviderMetadata(Builder builder) { + super(builder); + } + + public static Properties defaultProperties() { + Properties properties = new Properties(); + properties.putAll(Region.regionProperties()); + properties.setProperty(PROPERTY_REGION + "." + US_EAST_1 + ".endpoint", + "https://sqs.us-east-1.amazonaws.com"); + properties.setProperty(PROPERTY_REGION + "." + US_WEST_1 + ".endpoint", + "https://sqs.us-west-1.amazonaws.com"); + properties.setProperty(PROPERTY_REGION + "." + US_WEST_2 + ".endpoint", + "https://sqs.us-west-2.amazonaws.com"); + properties.setProperty(PROPERTY_REGION + "." + SA_EAST_1 + ".endpoint", + "https://sqs.sa-east-1.amazonaws.com"); + properties.setProperty(PROPERTY_REGION + "." + EU_WEST_1 + ".endpoint", + "https://sqs.eu-west-1.amazonaws.com"); + properties.setProperty(PROPERTY_REGION + "." + AP_SOUTHEAST_1 + ".endpoint", + "https://sqs.ap-southeast-1.amazonaws.com"); + properties.setProperty(PROPERTY_REGION + "." + AP_NORTHEAST_1 + ".endpoint", + "https://sqs.ap-northeast-1.amazonaws.com"); + return properties; + } + + public static class Builder extends BaseProviderMetadata.Builder { + + protected Builder(){ + id("aws-sqs") + .name("Amazon Simple Queue Service") + .endpoint("https://sqs.us-east-1.amazonaws.com") + .homepage(URI.create("http://aws.amazon.com/sqs")) + .console(URI.create("https://console.aws.amazon.com/ec2/home")) + .linkedServices("aws-ec2", "aws-rds", "aws-sqs", "aws-elb", "aws-iam","aws-cloudwatch", "aws-s3", "aws-simpledb") + .iso3166Codes("US-VA", "US-CA", "BR-SP", "US-OR", "IE", "SG", "JP-13") + .apiMetadata(new SQSApiMetadata()) + .defaultProperties(AWSSQSProviderMetadata.defaultProperties()); + } + + @Override + public Builder fromProviderMetadata( + ProviderMetadata in) { + super.fromProviderMetadata(in); + return this; + } + } +} diff --git a/providers/aws-sqs/src/main/resources/META-INF/services/org.jclouds.providers.ProviderMetadata b/providers/aws-sqs/src/main/resources/META-INF/services/org.jclouds.providers.ProviderMetadata new file mode 100644 index 0000000000..6f797d6ddc --- /dev/null +++ b/providers/aws-sqs/src/main/resources/META-INF/services/org.jclouds.providers.ProviderMetadata @@ -0,0 +1 @@ +org.jclouds.aws.sqs.AWSSQSProviderMetadata diff --git a/providers/aws-sqs/src/test/java/org/jclouds/aws/sqs/AWSSQSProviderTest.java b/providers/aws-sqs/src/test/java/org/jclouds/aws/sqs/AWSSQSProviderTest.java new file mode 100644 index 0000000000..8b137f7ea6 --- /dev/null +++ b/providers/aws-sqs/src/test/java/org/jclouds/aws/sqs/AWSSQSProviderTest.java @@ -0,0 +1,36 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.aws.sqs; + +import org.jclouds.sqs.SQSApiMetadata; +import org.jclouds.providers.internal.BaseProviderMetadataTest; +import org.testng.annotations.Test; + +/** + * The AWSSQSProviderTest tests the org.jclouds.providers.AWSSQSProvider class. + * + * @author Adrian Cole + */ +@Test(groups = "unit", testName = "AWSSQSProviderTest") +public class AWSSQSProviderTest extends BaseProviderMetadataTest { + + public AWSSQSProviderTest() { + super(new AWSSQSProviderMetadata(), new SQSApiMetadata()); + } +} diff --git a/providers/aws-sqs/src/test/java/org/jclouds/aws/sqs/features/AWSMessageApiLiveTest.java b/providers/aws-sqs/src/test/java/org/jclouds/aws/sqs/features/AWSMessageApiLiveTest.java new file mode 100644 index 0000000000..43d1c95584 --- /dev/null +++ b/providers/aws-sqs/src/test/java/org/jclouds/aws/sqs/features/AWSMessageApiLiveTest.java @@ -0,0 +1,35 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.aws.sqs.features; + +import org.jclouds.sqs.features.MessageApiLiveTest; +import org.testng.annotations.Test; + +/** + * + * @author Adrian Cole + */ +@Test(groups = "live", testName = "AWSMessageApiLiveTest") +public class AWSMessageApiLiveTest extends MessageApiLiveTest { + + public AWSMessageApiLiveTest() { + provider = "aws-sqs"; + } + +} diff --git a/providers/aws-sqs/src/test/java/org/jclouds/aws/sqs/features/AWSPermissionApiLiveTest.java b/providers/aws-sqs/src/test/java/org/jclouds/aws/sqs/features/AWSPermissionApiLiveTest.java new file mode 100644 index 0000000000..14fa42384f --- /dev/null +++ b/providers/aws-sqs/src/test/java/org/jclouds/aws/sqs/features/AWSPermissionApiLiveTest.java @@ -0,0 +1,35 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.aws.sqs.features; + +import org.jclouds.sqs.features.PermissionApiLiveTest; +import org.testng.annotations.Test; + +/** + * + * @author Adrian Cole + */ +@Test(groups = "live", testName = "AWSPermissionApiLiveTest") +public class AWSPermissionApiLiveTest extends PermissionApiLiveTest { + + public AWSPermissionApiLiveTest() { + provider = "aws-sqs"; + } + +} diff --git a/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/paas/reference/PaasConstants.java b/providers/aws-sqs/src/test/java/org/jclouds/aws/sqs/features/AWSQueueApiLiveTest.java similarity index 70% rename from demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/paas/reference/PaasConstants.java rename to providers/aws-sqs/src/test/java/org/jclouds/aws/sqs/features/AWSQueueApiLiveTest.java index 8af7021bd2..0065477e22 100644 --- a/demos/tweetstore/runatcloud-tweetstore/src/main/java/org/jclouds/demo/paas/reference/PaasConstants.java +++ b/providers/aws-sqs/src/test/java/org/jclouds/aws/sqs/features/AWSQueueApiLiveTest.java @@ -16,13 +16,20 @@ * specific language governing permissions and limitations * under the License. */ -package org.jclouds.demo.paas.reference; +package org.jclouds.aws.sqs.features; + +import org.jclouds.sqs.features.QueueApiLiveTest; +import org.testng.annotations.Test; /** - * Configuration properties and constants used in PaaS applications. * - * @author Andrew Phillips + * @author Adrian Cole */ -public interface PaasConstants { - static final String PROPERTY_PLATFORM_BASE_URL = "jclouds.paas.baseurl"; +@Test(groups = "live", testName = "AWSQueueApiLiveTest") +public class AWSQueueApiLiveTest extends QueueApiLiveTest { + + public AWSQueueApiLiveTest() { + provider = "aws-sqs"; + } + } diff --git a/providers/azureblob/pom.xml b/providers/azureblob/pom.xml index d069336efe..7bfeb26048 100644 --- a/providers/azureblob/pom.xml +++ b/providers/azureblob/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider diff --git a/providers/azureblob/src/test/java/org/jclouds/azureblob/AzureBlobClientLiveTest.java b/providers/azureblob/src/test/java/org/jclouds/azureblob/AzureBlobClientLiveTest.java index e2a7ffc7bf..5069c76d7a 100644 --- a/providers/azureblob/src/test/java/org/jclouds/azureblob/AzureBlobClientLiveTest.java +++ b/providers/azureblob/src/test/java/org/jclouds/azureblob/AzureBlobClientLiveTest.java @@ -49,6 +49,7 @@ import org.jclouds.util.Strings2; import org.jclouds.util.Throwables2; import org.testng.annotations.Test; +import com.google.common.base.Charsets; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.Iterables; @@ -306,7 +307,7 @@ public class AzureBlobClientLiveTest extends BaseBlobStoreIntegrationTest { assertEquals(((HttpResponseException) e.getCause()).getResponse().getStatusCode(), 422); } - ByteArrayInputStream bais = new ByteArrayInputStream(data.getBytes("UTF-8")); + ByteArrayInputStream bais = new ByteArrayInputStream(data.getBytes(Charsets.UTF_8)); object = getApi().newBlob(); object.getProperties().setName("chunked-object"); object.setPayload(bais); diff --git a/providers/bluelock-vcloud-zone01/pom.xml b/providers/bluelock-vcloud-zone01/pom.xml index 68786b0d1c..bfb8a283d9 100644 --- a/providers/bluelock-vcloud-zone01/pom.xml +++ b/providers/bluelock-vcloud-zone01/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider diff --git a/providers/cloudfiles-uk/pom.xml b/providers/cloudfiles-uk/pom.xml index f55d07e7b0..e81694b4bc 100644 --- a/providers/cloudfiles-uk/pom.xml +++ b/providers/cloudfiles-uk/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider @@ -34,6 +34,7 @@ bundle + 15 https://lon.auth.api.rackspacecloud.com 1.0 @@ -111,6 +112,7 @@ 1 + ${test.blobstore.container-count} ${test.cloudfiles-uk.endpoint} ${test.cloudfiles-uk.api-version} ${test.cloudfiles-uk.build-version} diff --git a/providers/cloudfiles-us/pom.xml b/providers/cloudfiles-us/pom.xml index 42712424ca..f4d8a0ee68 100644 --- a/providers/cloudfiles-us/pom.xml +++ b/providers/cloudfiles-us/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider diff --git a/providers/cloudloadbalancers-uk/pom.xml b/providers/cloudloadbalancers-uk/pom.xml index c7be621898..2863bd6776 100644 --- a/providers/cloudloadbalancers-uk/pom.xml +++ b/providers/cloudloadbalancers-uk/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider diff --git a/providers/cloudloadbalancers-us/pom.xml b/providers/cloudloadbalancers-us/pom.xml index cc2e829f51..a5015b1097 100644 --- a/providers/cloudloadbalancers-us/pom.xml +++ b/providers/cloudloadbalancers-us/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider diff --git a/providers/cloudonestorage/pom.xml b/providers/cloudonestorage/pom.xml index c2bf04a802..3aa5c3d082 100644 --- a/providers/cloudonestorage/pom.xml +++ b/providers/cloudonestorage/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider diff --git a/providers/cloudservers-uk/pom.xml b/providers/cloudservers-uk/pom.xml index 771662ca44..eca8d0cdef 100644 --- a/providers/cloudservers-uk/pom.xml +++ b/providers/cloudservers-uk/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider diff --git a/providers/cloudservers-us/pom.xml b/providers/cloudservers-us/pom.xml index 70a314009c..7db77c509a 100644 --- a/providers/cloudservers-us/pom.xml +++ b/providers/cloudservers-us/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider diff --git a/providers/cloudsigma-lvs/pom.xml b/providers/cloudsigma-lvs/pom.xml index 46b4ff1ff9..77e0af9613 100644 --- a/providers/cloudsigma-lvs/pom.xml +++ b/providers/cloudsigma-lvs/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider diff --git a/providers/cloudsigma-lvs/src/test/java/org/jclouds/cloudsigma/compute/CloudSigmaLasVegasTemplateBuilderLiveTest.java b/providers/cloudsigma-lvs/src/test/java/org/jclouds/cloudsigma/compute/CloudSigmaLasVegasTemplateBuilderLiveTest.java index 4c6c3c26ec..20881a0bef 100644 --- a/providers/cloudsigma-lvs/src/test/java/org/jclouds/cloudsigma/compute/CloudSigmaLasVegasTemplateBuilderLiveTest.java +++ b/providers/cloudsigma-lvs/src/test/java/org/jclouds/cloudsigma/compute/CloudSigmaLasVegasTemplateBuilderLiveTest.java @@ -51,23 +51,22 @@ public class CloudSigmaLasVegasTemplateBuilderLiveTest extends BaseTemplateBuild @Override public boolean apply(OsFamilyVersion64Bit input) { switch (input.family) { - case UBUNTU: - return (input.version.equals("11.04") && input.is64Bit) - || (input.version.equals("11.10") && !input.is64Bit) || input.version.equals("") - || input.version.equals("10.04"); - case SOLARIS: - return input.version.equals("") && input.is64Bit; - case DEBIAN: - return false; - case CENTOS: - return (input.version.equals("") || input.version.equals("5.7") || input.version.equals("6.0")) - && input.is64Bit; - case WINDOWS: - return (input.version.equals("2008 R2") || (input.version.equals("2003") || input.version.equals("")) - && input.is64Bit) - || (input.version.equals("") && !input.is64Bit); - default: - return false; + case UBUNTU: + return (ImmutableSet.of("11.04", "10.10").contains(input.version) && input.is64Bit) + || (input.version.equals("11.10") && !input.is64Bit) || input.version.equals("") + || input.version.equals("10.04") || input.version.equals("12.04"); + case SOLARIS: + return (input.version.equals("") || input.version.equals("10")) && input.is64Bit; + case DEBIAN: + return input.version.equals("") || (input.version.equals("5.0") && !input.is64Bit) + || (input.version.equals("6.0") && input.is64Bit); + case CENTOS: + return (input.version.equals("") || input.version.equals("5.5") || input.version.equals("5.7") || input.version + .equals("6.0")) && input.is64Bit; + case WINDOWS: + return input.version.equals("2008") || input.version.equals("2003") || input.version.equals(""); + default: + return false; } } diff --git a/providers/cloudsigma-zrh/pom.xml b/providers/cloudsigma-zrh/pom.xml index a8d9b8df0d..7c7a5c7b8f 100644 --- a/providers/cloudsigma-zrh/pom.xml +++ b/providers/cloudsigma-zrh/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider diff --git a/providers/elastichosts-lax-p/pom.xml b/providers/elastichosts-lax-p/pom.xml index d905cc54a6..05f3fbb030 100644 --- a/providers/elastichosts-lax-p/pom.xml +++ b/providers/elastichosts-lax-p/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider diff --git a/providers/elastichosts-lon-b/pom.xml b/providers/elastichosts-lon-b/pom.xml index 5ed8c9ddf2..ac1770ae12 100644 --- a/providers/elastichosts-lon-b/pom.xml +++ b/providers/elastichosts-lon-b/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider diff --git a/providers/elastichosts-lon-p/pom.xml b/providers/elastichosts-lon-p/pom.xml index bed96b3dd7..aa0053c1c4 100644 --- a/providers/elastichosts-lon-p/pom.xml +++ b/providers/elastichosts-lon-p/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider diff --git a/providers/elastichosts-sat-p/pom.xml b/providers/elastichosts-sat-p/pom.xml index b756afbacb..8a36f09d67 100644 --- a/providers/elastichosts-sat-p/pom.xml +++ b/providers/elastichosts-sat-p/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider diff --git a/providers/elastichosts-tor-p/pom.xml b/providers/elastichosts-tor-p/pom.xml index 5dbb421a49..2a58cfe85a 100644 --- a/providers/elastichosts-tor-p/pom.xml +++ b/providers/elastichosts-tor-p/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider diff --git a/providers/eucalyptus-partnercloud-ec2/pom.xml b/providers/eucalyptus-partnercloud-ec2/pom.xml index bd9374e27e..e1914a3383 100644 --- a/providers/eucalyptus-partnercloud-ec2/pom.xml +++ b/providers/eucalyptus-partnercloud-ec2/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider diff --git a/providers/eucalyptus-partnercloud-s3/pom.xml b/providers/eucalyptus-partnercloud-s3/pom.xml index 7e82c13687..123238f5a3 100644 --- a/providers/eucalyptus-partnercloud-s3/pom.xml +++ b/providers/eucalyptus-partnercloud-s3/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider diff --git a/labs/glesys/pom.xml b/providers/glesys/pom.xml similarity index 93% rename from labs/glesys/pom.xml rename to providers/glesys/pom.xml index bc2b6772d7..eb722df3f2 100644 --- a/labs/glesys/pom.xml +++ b/providers/glesys/pom.xml @@ -24,10 +24,10 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml - org.jclouds.labs + org.jclouds.provider glesys jclouds GleSYS core jclouds components to access GleSYS @@ -36,10 +36,10 @@ https://api.glesys.com 1 - + 3.5.0 FIXME FIXME - + osFamily=UBUNTU,osVersionMatches=1[012].[01][04],os64Bit=true,minRam=768 org.jclouds.glesys*;version="${project.version}" org.jclouds*;version="${project.version}",* diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/GleSYSApi.java b/providers/glesys/src/main/java/org/jclouds/glesys/GleSYSApi.java similarity index 95% rename from labs/glesys/src/main/java/org/jclouds/glesys/GleSYSApi.java rename to providers/glesys/src/main/java/org/jclouds/glesys/GleSYSApi.java index 7852a01d4f..cdc7f499c3 100644 --- a/labs/glesys/src/main/java/org/jclouds/glesys/GleSYSApi.java +++ b/providers/glesys/src/main/java/org/jclouds/glesys/GleSYSApi.java @@ -23,7 +23,7 @@ import java.util.concurrent.TimeUnit; import org.jclouds.concurrent.Timeout; import org.jclouds.glesys.features.ArchiveApi; import org.jclouds.glesys.features.DomainApi; -import org.jclouds.glesys.features.EmailApi; +import org.jclouds.glesys.features.EmailAccountApi; import org.jclouds.glesys.features.IpApi; import org.jclouds.glesys.features.ServerApi; import org.jclouds.rest.annotations.Delegate; @@ -67,6 +67,6 @@ public interface GleSYSApi { * Provides synchronous access to E-Mail features. */ @Delegate - EmailApi getEmailApi(); + EmailAccountApi getEmailAccountApi(); } diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/GleSYSApiMetadata.java b/providers/glesys/src/main/java/org/jclouds/glesys/GleSYSApiMetadata.java similarity index 99% rename from labs/glesys/src/main/java/org/jclouds/glesys/GleSYSApiMetadata.java rename to providers/glesys/src/main/java/org/jclouds/glesys/GleSYSApiMetadata.java index 6325afcbdb..357d6bcfb5 100644 --- a/labs/glesys/src/main/java/org/jclouds/glesys/GleSYSApiMetadata.java +++ b/providers/glesys/src/main/java/org/jclouds/glesys/GleSYSApiMetadata.java @@ -78,6 +78,7 @@ public class GleSYSApiMetadata extends BaseRestApiMetadata { .credentialName("API Key") .documentation(URI.create("https://customer.glesys.com/api.php")) .version("1") + .buildVersion("3.5.0") .defaultEndpoint("https://api.glesys.com") .defaultProperties(GleSYSApiMetadata.defaultProperties()) .view(TypeToken.of(ComputeServiceContext.class)) diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/GleSYSAsyncApi.java b/providers/glesys/src/main/java/org/jclouds/glesys/GleSYSAsyncApi.java similarity index 94% rename from labs/glesys/src/main/java/org/jclouds/glesys/GleSYSAsyncApi.java rename to providers/glesys/src/main/java/org/jclouds/glesys/GleSYSAsyncApi.java index 65cedb0306..fd341eb104 100644 --- a/labs/glesys/src/main/java/org/jclouds/glesys/GleSYSAsyncApi.java +++ b/providers/glesys/src/main/java/org/jclouds/glesys/GleSYSAsyncApi.java @@ -20,7 +20,7 @@ package org.jclouds.glesys; import org.jclouds.glesys.features.ArchiveAsyncApi; import org.jclouds.glesys.features.DomainAsyncApi; -import org.jclouds.glesys.features.EmailAsyncApi; +import org.jclouds.glesys.features.EmailAccountAsyncApi; import org.jclouds.glesys.features.IpAsyncApi; import org.jclouds.glesys.features.ServerAsyncApi; import org.jclouds.rest.annotations.Delegate; @@ -63,6 +63,6 @@ public interface GleSYSAsyncApi { * Provides asynchronous access to E-Mail features. */ @Delegate - EmailAsyncApi getEmailApi(); + EmailAccountAsyncApi getEmailAccountApi(); } diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/GleSYSProviderMetadata.java b/providers/glesys/src/main/java/org/jclouds/glesys/GleSYSProviderMetadata.java similarity index 95% rename from labs/glesys/src/main/java/org/jclouds/glesys/GleSYSProviderMetadata.java rename to providers/glesys/src/main/java/org/jclouds/glesys/GleSYSProviderMetadata.java index 20eccaefe3..fc272cc46d 100644 --- a/labs/glesys/src/main/java/org/jclouds/glesys/GleSYSProviderMetadata.java +++ b/providers/glesys/src/main/java/org/jclouds/glesys/GleSYSProviderMetadata.java @@ -62,7 +62,7 @@ public class GleSYSProviderMetadata extends BaseProviderMetadata { properties.setProperty(PROPERTY_ZONE + ".Falkenberg." + ISO3166_CODES, "SE-N"); properties.setProperty(PROPERTY_ZONE + ".New York City." + ISO3166_CODES, "US-NY"); properties.setProperty(PROPERTY_ZONE + ".Stockholm." + ISO3166_CODES, "SE-AB"); - properties.setProperty(TEMPLATE, "minRam=512,osFamily=UBUNTU,hypervisorMatches=OpenVZ,osVersionMatches=1[012].[01][04],os64Bit=true,locationId=Falkenberg"); + properties.setProperty(TEMPLATE, "osFamily=UBUNTU,osVersionMatches=1[012].[01][04],os64Bit=true,minRam=768"); return properties; } diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/compute/GleSYSComputeServiceAdapter.java b/providers/glesys/src/main/java/org/jclouds/glesys/compute/GleSYSComputeServiceAdapter.java similarity index 89% rename from labs/glesys/src/main/java/org/jclouds/glesys/compute/GleSYSComputeServiceAdapter.java rename to providers/glesys/src/main/java/org/jclouds/glesys/compute/GleSYSComputeServiceAdapter.java index 85622d3b27..c42a297a8c 100644 --- a/labs/glesys/src/main/java/org/jclouds/glesys/compute/GleSYSComputeServiceAdapter.java +++ b/providers/glesys/src/main/java/org/jclouds/glesys/compute/GleSYSComputeServiceAdapter.java @@ -20,8 +20,10 @@ package org.jclouds.glesys.compute; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; +import static org.jclouds.compute.util.ComputeServiceUtils.metadataAndTagsAsCommaDelimitedValue; import static org.jclouds.concurrent.FutureIterables.transformParallel; +import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ExecutorService; @@ -47,10 +49,11 @@ import org.jclouds.compute.domain.internal.VolumeImpl; import org.jclouds.compute.predicates.ImagePredicates; import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.compute.reference.ComputeServiceConstants.Timeouts; +import org.jclouds.crypto.CryptoStreams; import org.jclouds.domain.Location; import org.jclouds.domain.LoginCredentials; -import org.jclouds.glesys.GleSYSAsyncApi; import org.jclouds.glesys.GleSYSApi; +import org.jclouds.glesys.GleSYSAsyncApi; import org.jclouds.glesys.compute.options.GleSYSTemplateOptions; import org.jclouds.glesys.domain.AllowedArgumentsForCreateServer; import org.jclouds.glesys.domain.OSTemplate; @@ -64,7 +67,9 @@ import org.jclouds.logging.Logger; import org.jclouds.predicates.RetryablePredicate; import org.jclouds.util.Iterables2; +import com.google.common.base.Charsets; import com.google.common.base.Function; +import com.google.common.base.Joiner; import com.google.common.base.Predicate; import com.google.common.base.Supplier; import com.google.common.collect.ImmutableList; @@ -115,8 +120,12 @@ public class GleSYSComputeServiceAdapter implements ComputeServiceAdapter md = metadataAndTagsAsCommaDelimitedValue(template.getOptions()); + if (md.size() > 0) { + String description = Joiner.on('\n').withKeyValueSeparator("=").join(md); + // TODO: get glesys to stop stripping out equals and commas! + createServerOptions.description(CryptoStreams.hex(description.getBytes(Charsets.UTF_8))); + } ServerSpec.Builder builder = ServerSpec.builder(); builder.datacenter(template.getLocation().getId()); @@ -132,7 +141,7 @@ public class GleSYSComputeServiceAdapter implements ComputeServiceAdapter> creating new Server spec(%s) name(%s) options(%s)", spec, name, createServerOptions); - ServerDetails result = api.getServerApi().createServerWithHostnameAndRootPassword(spec, name, password, + ServerDetails result = api.getServerApi().createWithHostnameAndRootPassword(spec, name, password, createServerOptions); logger.trace("<< server(%s)", result.getId()); @@ -163,7 +172,7 @@ public class GleSYSComputeServiceAdapter implements ComputeServiceAdapter images = listImages(); for (Entry platformToArgs : api.getServerApi() - .getAllowedArgumentsForCreateServerByPlatform().entrySet()) + .getAllowedArgumentsForCreateByPlatform().entrySet()) for (String datacenter : platformToArgs.getValue().getDataCenters()) for (int diskSizeGB : platformToArgs.getValue().getDiskSizesInGB()) for (int cpuCores : platformToArgs.getValue().getCpuCoreOptions()) @@ -192,7 +201,7 @@ public class GleSYSComputeServiceAdapter implements ComputeServiceAdapter listImages() { - return api.getServerApi().listTemplates(); + return api.getServerApi().listTemplates().toImmutableSet(); } // cheat until we have a getTemplate command @@ -210,10 +219,10 @@ public class GleSYSComputeServiceAdapter implements ComputeServiceAdapter listNodes() { - return Iterables2.concreteCopy(transformParallel(api.getServerApi().listServers(), new Function>() { + return Iterables2.concreteCopy(transformParallel(api.getServerApi().list(), new Function>() { @Override public Future apply(Server from) { - return aapi.getServerApi().getServerDetails(from.getId()); + return aapi.getServerApi().get(from.getId()); } }, userThreads, null, logger, "server details")); @@ -222,7 +231,7 @@ public class GleSYSComputeServiceAdapter implements ComputeServiceAdapter listLocations() { return ImmutableSet.copyOf(Iterables.concat(Iterables.transform(api.getServerApi() - .getAllowedArgumentsForCreateServerByPlatform().values(), + .getAllowedArgumentsForCreateByPlatform().values(), new Function>() { @Override @@ -235,7 +244,7 @@ public class GleSYSComputeServiceAdapter implements ComputeServiceAdapter archiveSizes = ImmutableList.of(); /** - * @see ArchiveAllowedArguments#getArchiveSizes() + * @see ArchiveAllowedArguments#getSizes() */ public T archiveSizes(List archiveSizes) { this.archiveSizes = ImmutableList.copyOf(checkNotNull(archiveSizes, "archiveSizes")); @@ -65,7 +65,7 @@ public class ArchiveAllowedArguments { } public T fromArchiveAllowedArguments(ArchiveAllowedArguments in) { - return this.archiveSizes(in.getArchiveSizes()); + return this.archiveSizes(in.getSizes()); } } @@ -88,7 +88,7 @@ public class ArchiveAllowedArguments { /** * @return the list of allowed archive sizes, in GB */ - public List getArchiveSizes() { + public List getSizes() { return this.archiveSizes; } diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/domain/Console.java b/providers/glesys/src/main/java/org/jclouds/glesys/domain/Console.java similarity index 100% rename from labs/glesys/src/main/java/org/jclouds/glesys/domain/Console.java rename to providers/glesys/src/main/java/org/jclouds/glesys/domain/Console.java diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/domain/Cost.java b/providers/glesys/src/main/java/org/jclouds/glesys/domain/Cost.java similarity index 100% rename from labs/glesys/src/main/java/org/jclouds/glesys/domain/Cost.java rename to providers/glesys/src/main/java/org/jclouds/glesys/domain/Cost.java diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/domain/Domain.java b/providers/glesys/src/main/java/org/jclouds/glesys/domain/Domain.java similarity index 98% rename from labs/glesys/src/main/java/org/jclouds/glesys/domain/Domain.java rename to providers/glesys/src/main/java/org/jclouds/glesys/domain/Domain.java index 30b34b428e..59774e902a 100644 --- a/labs/glesys/src/main/java/org/jclouds/glesys/domain/Domain.java +++ b/providers/glesys/src/main/java/org/jclouds/glesys/domain/Domain.java @@ -60,7 +60,7 @@ public class Domain { protected int minimum; /** - * @see Domain#getDomainName() + * @see Domain#getName() */ public T domainName(String domainName) { this.domainName = checkNotNull(domainName, "domainName"); @@ -152,7 +152,7 @@ public class Domain { } public T fromDomain(Domain in) { - return this.domainName(in.getDomainName()) + return this.domainName(in.getName()) .createTime(in.getCreateTime()) .recordCount(in.getRecordCount()) .useGlesysNameServer(in.isUseGlesysNameServer()) @@ -207,7 +207,7 @@ public class Domain { /** * @return the domain name, ex. "jclouds.org" */ - public String getDomainName() { + public String getName() { return this.domainName; } diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/domain/DomainRecord.java b/providers/glesys/src/main/java/org/jclouds/glesys/domain/DomainRecord.java similarity index 97% rename from labs/glesys/src/main/java/org/jclouds/glesys/domain/DomainRecord.java rename to providers/glesys/src/main/java/org/jclouds/glesys/domain/DomainRecord.java index 7ece758cb9..2a35291c00 100644 --- a/labs/glesys/src/main/java/org/jclouds/glesys/domain/DomainRecord.java +++ b/providers/glesys/src/main/java/org/jclouds/glesys/domain/DomainRecord.java @@ -62,7 +62,7 @@ public class DomainRecord { } /** - * @see DomainRecord#getDomainname() + * @see DomainRecord#getname() */ public T domainname(String domainname) { this.domainname = checkNotNull(domainname, "domainname"); @@ -107,7 +107,7 @@ public class DomainRecord { public T fromDomainRecord(DomainRecord in) { return this.id(in.getId()) - .domainname(in.getDomainname()) + .domainname(in.getname()) .host(in.getHost()) .type(in.getType()) .data(in.getData()) @@ -152,7 +152,7 @@ public class DomainRecord { /** * @return the zone content of the record */ - public String getDomainname() { + public String getname() { return this.domainname; } diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/domain/EmailAccount.java b/providers/glesys/src/main/java/org/jclouds/glesys/domain/EmailAccount.java similarity index 100% rename from labs/glesys/src/main/java/org/jclouds/glesys/domain/EmailAccount.java rename to providers/glesys/src/main/java/org/jclouds/glesys/domain/EmailAccount.java diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/domain/EmailAlias.java b/providers/glesys/src/main/java/org/jclouds/glesys/domain/EmailAlias.java similarity index 100% rename from labs/glesys/src/main/java/org/jclouds/glesys/domain/EmailAlias.java rename to providers/glesys/src/main/java/org/jclouds/glesys/domain/EmailAlias.java diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/domain/EmailOverview.java b/providers/glesys/src/main/java/org/jclouds/glesys/domain/EmailOverview.java similarity index 96% rename from labs/glesys/src/main/java/org/jclouds/glesys/domain/EmailOverview.java rename to providers/glesys/src/main/java/org/jclouds/glesys/domain/EmailOverview.java index 88bdc4c56b..45c3c3f7d8 100644 --- a/labs/glesys/src/main/java/org/jclouds/glesys/domain/EmailOverview.java +++ b/providers/glesys/src/main/java/org/jclouds/glesys/domain/EmailOverview.java @@ -61,7 +61,7 @@ public class EmailOverview { } /** - * @see EmailOverview#getDomains() + * @see EmailOverview#gets() */ public T domains(Set domains) { this.domains = ImmutableSet.copyOf(checkNotNull(domains, "domains")); @@ -77,7 +77,7 @@ public class EmailOverview { } public T fromEmailOverview(EmailOverview in) { - return this.summary(in.getSummary()).domains(in.getDomains()); + return this.summary(in.getSummary()).domains(in.gets()); } } @@ -109,7 +109,7 @@ public class EmailOverview { /** * @return the set of detailed information about the e-mail addresses and aliases for each domain */ - public Set getDomains() { + public Set gets() { return this.domains; } diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/domain/EmailOverviewDomain.java b/providers/glesys/src/main/java/org/jclouds/glesys/domain/EmailOverviewDomain.java similarity index 95% rename from labs/glesys/src/main/java/org/jclouds/glesys/domain/EmailOverviewDomain.java rename to providers/glesys/src/main/java/org/jclouds/glesys/domain/EmailOverviewDomain.java index b201b2ab19..bbf9308d73 100644 --- a/labs/glesys/src/main/java/org/jclouds/glesys/domain/EmailOverviewDomain.java +++ b/providers/glesys/src/main/java/org/jclouds/glesys/domain/EmailOverviewDomain.java @@ -51,7 +51,7 @@ public class EmailOverviewDomain { protected int aliases; /** - * @see EmailOverviewDomain#getDomain() + * @see EmailOverviewDomain#get() */ public T domain(String domain) { this.domain = checkNotNull(domain, "domain"); @@ -79,7 +79,7 @@ public class EmailOverviewDomain { } public T fromEmailOverviewDomain(EmailOverviewDomain in) { - return this.domain(in.getDomain()).accounts(in.getAccounts()).aliases(in.getAliases()); + return this.domain(in.get()).accounts(in.getAccounts()).aliases(in.getAliases()); } } @@ -104,7 +104,7 @@ public class EmailOverviewDomain { } /** @return the domain name */ - public String getDomain() { + public String get() { return this.domain; } diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/domain/EmailOverviewSummary.java b/providers/glesys/src/main/java/org/jclouds/glesys/domain/EmailOverviewSummary.java similarity index 100% rename from labs/glesys/src/main/java/org/jclouds/glesys/domain/EmailOverviewSummary.java rename to providers/glesys/src/main/java/org/jclouds/glesys/domain/EmailOverviewSummary.java diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/domain/EmailQuota.java b/providers/glesys/src/main/java/org/jclouds/glesys/domain/EmailQuota.java similarity index 100% rename from labs/glesys/src/main/java/org/jclouds/glesys/domain/EmailQuota.java rename to providers/glesys/src/main/java/org/jclouds/glesys/domain/EmailQuota.java diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/domain/GleSYSBoolean.java b/providers/glesys/src/main/java/org/jclouds/glesys/domain/GleSYSBoolean.java similarity index 100% rename from labs/glesys/src/main/java/org/jclouds/glesys/domain/GleSYSBoolean.java rename to providers/glesys/src/main/java/org/jclouds/glesys/domain/GleSYSBoolean.java diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/domain/Ip.java b/providers/glesys/src/main/java/org/jclouds/glesys/domain/Ip.java similarity index 100% rename from labs/glesys/src/main/java/org/jclouds/glesys/domain/Ip.java rename to providers/glesys/src/main/java/org/jclouds/glesys/domain/Ip.java diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/domain/IpDetails.java b/providers/glesys/src/main/java/org/jclouds/glesys/domain/IpDetails.java similarity index 100% rename from labs/glesys/src/main/java/org/jclouds/glesys/domain/IpDetails.java rename to providers/glesys/src/main/java/org/jclouds/glesys/domain/IpDetails.java diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/domain/OSTemplate.java b/providers/glesys/src/main/java/org/jclouds/glesys/domain/OSTemplate.java similarity index 100% rename from labs/glesys/src/main/java/org/jclouds/glesys/domain/OSTemplate.java rename to providers/glesys/src/main/java/org/jclouds/glesys/domain/OSTemplate.java diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/domain/ResourceStatus.java b/providers/glesys/src/main/java/org/jclouds/glesys/domain/ResourceStatus.java similarity index 100% rename from labs/glesys/src/main/java/org/jclouds/glesys/domain/ResourceStatus.java rename to providers/glesys/src/main/java/org/jclouds/glesys/domain/ResourceStatus.java diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/domain/ResourceUsage.java b/providers/glesys/src/main/java/org/jclouds/glesys/domain/ResourceUsage.java similarity index 100% rename from labs/glesys/src/main/java/org/jclouds/glesys/domain/ResourceUsage.java rename to providers/glesys/src/main/java/org/jclouds/glesys/domain/ResourceUsage.java diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/domain/ResourceUsageInfo.java b/providers/glesys/src/main/java/org/jclouds/glesys/domain/ResourceUsageInfo.java similarity index 100% rename from labs/glesys/src/main/java/org/jclouds/glesys/domain/ResourceUsageInfo.java rename to providers/glesys/src/main/java/org/jclouds/glesys/domain/ResourceUsageInfo.java diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/domain/ResourceUsageValue.java b/providers/glesys/src/main/java/org/jclouds/glesys/domain/ResourceUsageValue.java similarity index 100% rename from labs/glesys/src/main/java/org/jclouds/glesys/domain/ResourceUsageValue.java rename to providers/glesys/src/main/java/org/jclouds/glesys/domain/ResourceUsageValue.java diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/domain/Server.java b/providers/glesys/src/main/java/org/jclouds/glesys/domain/Server.java similarity index 100% rename from labs/glesys/src/main/java/org/jclouds/glesys/domain/Server.java rename to providers/glesys/src/main/java/org/jclouds/glesys/domain/Server.java diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/domain/ServerDetails.java b/providers/glesys/src/main/java/org/jclouds/glesys/domain/ServerDetails.java similarity index 100% rename from labs/glesys/src/main/java/org/jclouds/glesys/domain/ServerDetails.java rename to providers/glesys/src/main/java/org/jclouds/glesys/domain/ServerDetails.java diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/domain/ServerLimit.java b/providers/glesys/src/main/java/org/jclouds/glesys/domain/ServerLimit.java similarity index 100% rename from labs/glesys/src/main/java/org/jclouds/glesys/domain/ServerLimit.java rename to providers/glesys/src/main/java/org/jclouds/glesys/domain/ServerLimit.java diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/domain/ServerSpec.java b/providers/glesys/src/main/java/org/jclouds/glesys/domain/ServerSpec.java similarity index 100% rename from labs/glesys/src/main/java/org/jclouds/glesys/domain/ServerSpec.java rename to providers/glesys/src/main/java/org/jclouds/glesys/domain/ServerSpec.java diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/domain/ServerStatus.java b/providers/glesys/src/main/java/org/jclouds/glesys/domain/ServerStatus.java similarity index 100% rename from labs/glesys/src/main/java/org/jclouds/glesys/domain/ServerStatus.java rename to providers/glesys/src/main/java/org/jclouds/glesys/domain/ServerStatus.java diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/domain/ServerUptime.java b/providers/glesys/src/main/java/org/jclouds/glesys/domain/ServerUptime.java similarity index 100% rename from labs/glesys/src/main/java/org/jclouds/glesys/domain/ServerUptime.java rename to providers/glesys/src/main/java/org/jclouds/glesys/domain/ServerUptime.java diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/features/ArchiveApi.java b/providers/glesys/src/main/java/org/jclouds/glesys/features/ArchiveApi.java similarity index 84% rename from labs/glesys/src/main/java/org/jclouds/glesys/features/ArchiveApi.java rename to providers/glesys/src/main/java/org/jclouds/glesys/features/ArchiveApi.java index d074a87537..d50417fbad 100644 --- a/labs/glesys/src/main/java/org/jclouds/glesys/features/ArchiveApi.java +++ b/providers/glesys/src/main/java/org/jclouds/glesys/features/ArchiveApi.java @@ -18,13 +18,14 @@ */ package org.jclouds.glesys.features; -import java.util.Set; import java.util.concurrent.TimeUnit; import org.jclouds.concurrent.Timeout; import org.jclouds.glesys.domain.Archive; import org.jclouds.glesys.domain.ArchiveAllowedArguments; +import com.google.common.collect.FluentIterable; + /** * Provides synchronous access to Archive requests. *

@@ -39,7 +40,7 @@ public interface ArchiveApi { /** * Lists all active disks on this account. */ - Set listArchives(); + FluentIterable list(); /** * Get detailed information about an archive volume. @@ -47,7 +48,7 @@ public interface ArchiveApi { * @param username the username associated with the archive * @return the archive information or null if not found */ - Archive getArchive(String username); + Archive get(String username); /** * Create a new backup volume. @@ -57,14 +58,14 @@ public interface ArchiveApi { * @param password the new password * @param size the new size required in GB */ - Archive createArchive(String username, String password, int size); + Archive createWithCredentialsAndSize(String username, String password, int size); /** * Delete an archive volume. All files on the volume * * @param username the username associated with the archive */ - void deleteArchive(String username); + void delete(String username); /** * Resize an archive volume. It is only possible to upgrade the size of the disk. Downgrading is currently not @@ -72,9 +73,9 @@ public interface ArchiveApi { * Then delete the old volume. * * @param username the username associated with the archive - * @param size the new size required, see #getArchiveAllowedArguments for valid values + * @param size the new size required, see #getAllowedArguments for valid values */ - Archive resizeArchive(String username, int size); + Archive resize(String username, int size); /** * Change the password for an archive user. @@ -82,11 +83,11 @@ public interface ArchiveApi { * @param username the archive username * @param password the new password */ - Archive changeArchivePassword(String username, String password); + Archive changePassword(String username, String password); /** * Lists the allowed arguments for some of the functions in this module such as archive size. */ - ArchiveAllowedArguments getArchiveAllowedArguments(); + ArchiveAllowedArguments getAllowedArguments(); } diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/features/ArchiveAsyncApi.java b/providers/glesys/src/main/java/org/jclouds/glesys/features/ArchiveAsyncApi.java similarity index 71% rename from labs/glesys/src/main/java/org/jclouds/glesys/features/ArchiveAsyncApi.java rename to providers/glesys/src/main/java/org/jclouds/glesys/features/ArchiveAsyncApi.java index 550c498ae3..4210f171a2 100644 --- a/labs/glesys/src/main/java/org/jclouds/glesys/features/ArchiveAsyncApi.java +++ b/providers/glesys/src/main/java/org/jclouds/glesys/features/ArchiveAsyncApi.java @@ -18,8 +18,6 @@ */ package org.jclouds.glesys.features; -import java.util.Set; - import javax.ws.rs.Consumes; import javax.ws.rs.FormParam; import javax.ws.rs.GET; @@ -33,9 +31,10 @@ import org.jclouds.http.filters.BasicAuthentication; import org.jclouds.rest.annotations.ExceptionParser; import org.jclouds.rest.annotations.RequestFilters; import org.jclouds.rest.annotations.SelectJson; -import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404; +import org.jclouds.rest.functions.ReturnEmptyFluentIterableOnNotFoundOr404; import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; +import com.google.common.collect.FluentIterable; import com.google.common.util.concurrent.ListenableFuture; /** @@ -50,67 +49,67 @@ import com.google.common.util.concurrent.ListenableFuture; public interface ArchiveAsyncApi { /** - * @see ArchiveApi#listArchives + * @see ArchiveApi#list */ @POST @Path("/archive/list/format/json") @SelectJson("archives") @Consumes(MediaType.APPLICATION_JSON) - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> listArchives(); + @ExceptionParser(ReturnEmptyFluentIterableOnNotFoundOr404.class) + ListenableFuture> list(); /** - * @see ArchiveApi#getArchive + * @see ArchiveApi#get */ @POST @Path("/archive/details/format/json") @SelectJson("details") @Consumes(MediaType.APPLICATION_JSON) @ExceptionParser(ReturnNullOnNotFoundOr404.class) - ListenableFuture getArchive(@FormParam("username") String username); + ListenableFuture get(@FormParam("username") String username); /** - * @see ArchiveApi#createArchive + * @see ArchiveApi#createWithCredentialsAndSize */ @POST @Path("/archive/create/format/json") @SelectJson("details") @Consumes(MediaType.APPLICATION_JSON) - ListenableFuture createArchive(@FormParam("username") String username, @FormParam("password") String password, + ListenableFuture createWithCredentialsAndSize(@FormParam("username") String username, @FormParam("password") String password, @FormParam("size")int size); /** - * @see ArchiveApi#deleteArchive + * @see ArchiveApi#delete */ @POST @Path("/archive/delete/format/json") - ListenableFuture deleteArchive(@FormParam("username") String username); + ListenableFuture delete(@FormParam("username") String username); /** - * @see ArchiveApi#resizeArchive + * @see ArchiveApi#resize */ @POST @Path("/archive/resize/format/json") @SelectJson("details") @Consumes(MediaType.APPLICATION_JSON) - ListenableFuture resizeArchive(@FormParam("username") String username, @FormParam("size") int size); + ListenableFuture resize(@FormParam("username") String username, @FormParam("size") int size); /** - * @see ArchiveApi#changeArchivePassword + * @see ArchiveApi#changePassword */ @POST @Path("/archive/changepassword/format/json") @SelectJson("details") @Consumes(MediaType.APPLICATION_JSON) - ListenableFuture changeArchivePassword(@FormParam("username") String username, @FormParam("password") String password); + ListenableFuture changePassword(@FormParam("username") String username, @FormParam("password") String password); /** - * @see org.jclouds.glesys.features.ArchiveApi#getArchiveAllowedArguments + * @see org.jclouds.glesys.features.ArchiveApi#getAllowedArguments */ @GET @Path("/archive/allowedarguments/format/json") @SelectJson("argumentslist") @Consumes(MediaType.APPLICATION_JSON) @ExceptionParser(ReturnNullOnNotFoundOr404.class) - ListenableFuture getArchiveAllowedArguments(); + ListenableFuture getAllowedArguments(); } diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/features/DomainApi.java b/providers/glesys/src/main/java/org/jclouds/glesys/features/DomainApi.java similarity index 83% rename from labs/glesys/src/main/java/org/jclouds/glesys/features/DomainApi.java rename to providers/glesys/src/main/java/org/jclouds/glesys/features/DomainApi.java index ca6a01d804..2b393a0e9c 100644 --- a/labs/glesys/src/main/java/org/jclouds/glesys/features/DomainApi.java +++ b/providers/glesys/src/main/java/org/jclouds/glesys/features/DomainApi.java @@ -27,7 +27,9 @@ import org.jclouds.glesys.domain.DomainRecord; import org.jclouds.glesys.options.AddDomainOptions; import org.jclouds.glesys.options.AddRecordOptions; import org.jclouds.glesys.options.DomainOptions; -import org.jclouds.glesys.options.EditRecordOptions; +import org.jclouds.glesys.options.UpdateRecordOptions; + +import com.google.common.collect.FluentIterable; /** * Provides synchronous access to Domain requests. @@ -45,14 +47,14 @@ public interface DomainApi { * * @return an account's associated domain objects. */ - Set listDomains(); + FluentIterable list(); /** * Get a specific domain. * * @return the requested domain object. */ - Domain getDomain(String domain); + Domain get(String domain); /** * Add a domain to the Glesys dns-system @@ -61,23 +63,23 @@ public interface DomainApi { * @param options optional parameters * @return information about the added domain */ - Domain addDomain(String domain, AddDomainOptions... options); + Domain create(String domain, AddDomainOptions... options); /** - * Edit a domain to the Glesys dns-system + * Update a domain to the Glesys dns-system * * @param domain the name of the domain to add. * @param options optional parameters * @return information about the modified domain */ - Domain editDomain(String domain, DomainOptions... options); + Domain update(String domain, DomainOptions options); /** * Remove a domain to the Glesys dns-system * * @param domain the name of the domain to remove */ - void deleteDomain(String domain); + void delete(String domain); /** * Retrieve the DNS records for a given domain @@ -92,7 +94,7 @@ public interface DomainApi { * @param domain the domain to add the record to * @param options optional settings for the record */ - DomainRecord addRecord(String domain, String host, String type, String data, AddRecordOptions... options); + DomainRecord createRecord(String domain, String host, String type, String data, AddRecordOptions... options); /** * Modify a specific DNS Record @@ -101,7 +103,7 @@ public interface DomainApi { * @param options the settings to change * @see #listRecords to retrieve the necessary ids */ - DomainRecord editRecord(String recordId, EditRecordOptions... options); + DomainRecord updateRecord(String recordId, UpdateRecordOptions options); /** * Delete a DNS record diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/features/DomainAsyncApi.java b/providers/glesys/src/main/java/org/jclouds/glesys/features/DomainAsyncApi.java similarity index 74% rename from labs/glesys/src/main/java/org/jclouds/glesys/features/DomainAsyncApi.java rename to providers/glesys/src/main/java/org/jclouds/glesys/features/DomainAsyncApi.java index 8fdbd19e95..ccf3f09031 100644 --- a/labs/glesys/src/main/java/org/jclouds/glesys/features/DomainAsyncApi.java +++ b/providers/glesys/src/main/java/org/jclouds/glesys/features/DomainAsyncApi.java @@ -31,14 +31,15 @@ import org.jclouds.glesys.domain.DomainRecord; import org.jclouds.glesys.options.AddDomainOptions; import org.jclouds.glesys.options.AddRecordOptions; import org.jclouds.glesys.options.DomainOptions; -import org.jclouds.glesys.options.EditRecordOptions; +import org.jclouds.glesys.options.UpdateRecordOptions; import org.jclouds.http.filters.BasicAuthentication; import org.jclouds.rest.annotations.ExceptionParser; import org.jclouds.rest.annotations.RequestFilters; import org.jclouds.rest.annotations.SelectJson; -import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404; +import org.jclouds.rest.functions.ReturnEmptyFluentIterableOnNotFoundOr404; import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; +import com.google.common.collect.FluentIterable; import com.google.common.util.concurrent.ListenableFuture; /** @@ -53,50 +54,50 @@ import com.google.common.util.concurrent.ListenableFuture; public interface DomainAsyncApi { /** - * @see org.jclouds.glesys.features.DomainApi#listDomains + * @see org.jclouds.glesys.features.DomainApi#list */ @POST @Path("/domain/list/format/json") @SelectJson("domains") @Consumes(MediaType.APPLICATION_JSON) - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> listDomains(); + @ExceptionParser(ReturnEmptyFluentIterableOnNotFoundOr404.class) + ListenableFuture> list(); /** - * @see org.jclouds.glesys.features.DomainApi#getDomain + * @see org.jclouds.glesys.features.DomainApi#get */ @POST @Path("/domain/details/format/json") @SelectJson("domain") @Consumes(MediaType.APPLICATION_JSON) @ExceptionParser(ReturnNullOnNotFoundOr404.class) - ListenableFuture getDomain(@FormParam("domainname") String name); + ListenableFuture get(@FormParam("domainname") String name); /** - * @see DomainApi#addDomain + * @see DomainApi#create */ @POST @Path("/domain/add/format/json") @SelectJson("domain") @Consumes(MediaType.APPLICATION_JSON) - ListenableFuture addDomain(@FormParam("domainname") String name, AddDomainOptions... options); + ListenableFuture create(@FormParam("domainname") String name, AddDomainOptions... options); /** - * @see DomainApi#editDomain + * @see DomainApi#update */ @POST @Path("/domain/edit/format/json") @SelectJson("domain") @Consumes(MediaType.APPLICATION_JSON) - ListenableFuture editDomain(@FormParam("domainname") String domain, DomainOptions... options); + ListenableFuture update(@FormParam("domainname") String domain, DomainOptions options); /** - * @see DomainApi#deleteDomain + * @see DomainApi#delete */ @POST @Path("/domain/delete/format/json") - ListenableFuture deleteDomain(@FormParam("domainname") String domain); + ListenableFuture delete(@FormParam("domainname") String domain); /** * @see DomainApi#listRecords @@ -108,24 +109,24 @@ public interface DomainAsyncApi { ListenableFuture> listRecords(@FormParam("domainname") String domain); /** - * @see DomainApi#addRecord + * @see DomainApi#createRecord */ @POST @Path("/domain/addrecord/format/json") @SelectJson("record") @Consumes(MediaType.APPLICATION_JSON) - ListenableFuture addRecord(@FormParam("domainname") String domain, @FormParam("host") String host, + ListenableFuture createRecord(@FormParam("domainname") String domain, @FormParam("host") String host, @FormParam("type") String type, @FormParam("data") String data, AddRecordOptions... options); /** - * @see DomainApi#editRecord + * @see DomainApi#updateRecord */ @POST @Path("/domain/updaterecord/format/json") @SelectJson("record") @Consumes(MediaType.APPLICATION_JSON) - ListenableFuture editRecord(@FormParam("recordid") String record_id, EditRecordOptions... options); + ListenableFuture updateRecord(@FormParam("recordid") String record_id, UpdateRecordOptions options); /** * @see DomainApi#deleteRecord diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/features/EmailApi.java b/providers/glesys/src/main/java/org/jclouds/glesys/features/EmailAccountApi.java similarity index 80% rename from labs/glesys/src/main/java/org/jclouds/glesys/features/EmailApi.java rename to providers/glesys/src/main/java/org/jclouds/glesys/features/EmailAccountApi.java index e8680435b6..e00725c4e1 100644 --- a/labs/glesys/src/main/java/org/jclouds/glesys/features/EmailApi.java +++ b/providers/glesys/src/main/java/org/jclouds/glesys/features/EmailAccountApi.java @@ -18,7 +18,6 @@ */ package org.jclouds.glesys.features; -import java.util.Set; import java.util.concurrent.TimeUnit; import org.jclouds.concurrent.Timeout; @@ -26,39 +25,41 @@ import org.jclouds.glesys.domain.EmailAccount; import org.jclouds.glesys.domain.EmailAlias; import org.jclouds.glesys.domain.EmailOverview; import org.jclouds.glesys.options.CreateAccountOptions; -import org.jclouds.glesys.options.EditAccountOptions; +import org.jclouds.glesys.options.UpdateAccountOptions; + +import com.google.common.collect.FluentIterable; /** * Provides synchronous access to E-Mail requests. *

* * @author Adam Lowe - * @see org.jclouds.glesys.features.EmailAsyncApi + * @see org.jclouds.glesys.features.EmailAccountAsyncApi * @see */ @Timeout(duration = 30, timeUnit = TimeUnit.SECONDS) -public interface EmailApi { +public interface EmailAccountApi { /** * Get a summary of e-mail accounts associated with this Glesys account * * @return the relevant summary data */ - EmailOverview getEmailOverview(); + EmailOverview getOverview(); /** * Get the set of detailed information about e-mail accounts * * @return the relevant set of details */ - Set listAccounts(String domain); + FluentIterable listDomain(String domain); /** * Get the set of details about e-mail aliases * * @return the relevant set of details */ - Set listAliases(String domain); + FluentIterable listAliasesInDomain(String domain); /** * Create a new e-mail account @@ -66,16 +67,16 @@ public interface EmailApi { * @param accountAddress the e-mail address to use (the domain should already exist) * @param password the password to use for the mailbox * @param options optional parameters - * @see DomainApi#addDomain + * @see DomainApi#create */ - EmailAccount createAccount(String accountAddress, String password, CreateAccountOptions... options); + EmailAccount createWithPassword(String accountAddress, String password, CreateAccountOptions... options); /** * Create an e-mail alias for an e-mail account * * @param aliasAddress the address to use for the alias (the domain should already exist) * @param toEmailAddress the existing e-mail account address the alias should forward to - * @see DomainApi#addDomain + * @see DomainApi#create */ EmailAlias createAlias(String aliasAddress, String toEmailAddress); @@ -85,7 +86,7 @@ public interface EmailApi { * @param accountAddress the existing e-mail account address * @param options optional parameters */ - EmailAccount editAccount(String accountAddress, EditAccountOptions... options); + EmailAccount update(String accountAddress, UpdateAccountOptions... options); /** * Adjust (re-target) an e-mail alias @@ -93,7 +94,7 @@ public interface EmailApi { * @param aliasAddress the existing alias e-mail address * @param toEmailAddress the existing e-mail account address the alias should forward to */ - EmailAlias editAlias(String aliasAddress, String toEmailAddress); + EmailAlias updateAlias(String aliasAddress, String toEmailAddress); /** * Delete an e-mail account or alias diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/features/EmailAsyncApi.java b/providers/glesys/src/main/java/org/jclouds/glesys/features/EmailAccountAsyncApi.java similarity index 63% rename from labs/glesys/src/main/java/org/jclouds/glesys/features/EmailAsyncApi.java rename to providers/glesys/src/main/java/org/jclouds/glesys/features/EmailAccountAsyncApi.java index 2470729864..aaedf50f83 100644 --- a/labs/glesys/src/main/java/org/jclouds/glesys/features/EmailAsyncApi.java +++ b/providers/glesys/src/main/java/org/jclouds/glesys/features/EmailAccountAsyncApi.java @@ -18,8 +18,6 @@ */ package org.jclouds.glesys.features; -import java.util.Set; - import javax.ws.rs.Consumes; import javax.ws.rs.FormParam; import javax.ws.rs.POST; @@ -30,14 +28,16 @@ import org.jclouds.glesys.domain.EmailAccount; import org.jclouds.glesys.domain.EmailAlias; import org.jclouds.glesys.domain.EmailOverview; import org.jclouds.glesys.options.CreateAccountOptions; -import org.jclouds.glesys.options.EditAccountOptions; +import org.jclouds.glesys.options.UpdateAccountOptions; import org.jclouds.http.filters.BasicAuthentication; +import org.jclouds.http.functions.ReturnTrueOn404; import org.jclouds.rest.annotations.ExceptionParser; import org.jclouds.rest.annotations.RequestFilters; import org.jclouds.rest.annotations.SelectJson; -import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404; +import org.jclouds.rest.functions.ReturnEmptyFluentIterableOnNotFoundOr404; import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; +import com.google.common.collect.FluentIterable; import com.google.common.util.concurrent.ListenableFuture; /** @@ -45,53 +45,53 @@ import com.google.common.util.concurrent.ListenableFuture; *

* * @author Adam Lowe - * @see org.jclouds.glesys.features.EmailApi + * @see org.jclouds.glesys.features.EmailAccountApi * @see */ @RequestFilters(BasicAuthentication.class) -public interface EmailAsyncApi { +public interface EmailAccountAsyncApi { /** - * @see org.jclouds.glesys.features.EmailApi#getEmailOverview + * @see org.jclouds.glesys.features.EmailAccountApi#getOverview */ @POST @Path("/email/overview/format/json") @SelectJson("overview") @Consumes(MediaType.APPLICATION_JSON) @ExceptionParser(ReturnNullOnNotFoundOr404.class) - ListenableFuture getEmailOverview(); + ListenableFuture getOverview(); /** - * @see org.jclouds.glesys.features.EmailApi#listAccounts + * @see org.jclouds.glesys.features.EmailAccountApi#listDomain */ @POST @Path("/email/list/format/json") @SelectJson("emailaccounts") @Consumes(MediaType.APPLICATION_JSON) - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> listAccounts(@FormParam("domainname") String domain); + @ExceptionParser(ReturnEmptyFluentIterableOnNotFoundOr404.class) + ListenableFuture> listDomain(@FormParam("domainname") String domain); /** - * @see org.jclouds.glesys.features.EmailApi#listAccounts + * @see org.jclouds.glesys.features.EmailAccountApi#listAliasesInDomain */ @POST @Path("/email/list/format/json") @SelectJson("emailaliases") @Consumes(MediaType.APPLICATION_JSON) - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> listAliases(@FormParam("domainname") String domain); + @ExceptionParser(ReturnEmptyFluentIterableOnNotFoundOr404.class) + ListenableFuture> listAliasesInDomain(@FormParam("domainname") String domain); /** - * @see org.jclouds.glesys.features.EmailApi#createAccount + * @see org.jclouds.glesys.features.EmailAccountApi#createWithPassword */ @POST @Consumes(MediaType.APPLICATION_JSON) @SelectJson("emailaccount") @Path("/email/createaccount/format/json") - ListenableFuture createAccount(@FormParam("emailaccount") String accountAddress, @FormParam("password") String password, CreateAccountOptions... options); + ListenableFuture createWithPassword(@FormParam("emailaccount") String accountAddress, @FormParam("password") String password, CreateAccountOptions... options); /** - * @see org.jclouds.glesys.features.EmailApi#createAlias + * @see org.jclouds.glesys.features.EmailAccountApi#createAlias */ @POST @Consumes(MediaType.APPLICATION_JSON) @@ -100,28 +100,29 @@ public interface EmailAsyncApi { ListenableFuture createAlias(@FormParam("emailalias") String aliasAddress, @FormParam("goto") String toEmailAddress); /** - * @see org.jclouds.glesys.features.EmailApi#editAccount + * @see org.jclouds.glesys.features.EmailAccountApi#update */ @POST @Consumes(MediaType.APPLICATION_JSON) @SelectJson("emailaccount") @Path("/email/editaccount/format/json") - ListenableFuture editAccount(@FormParam("emailaccount") String accountAddress, EditAccountOptions... options); + ListenableFuture update(@FormParam("emailaccount") String accountAddress, UpdateAccountOptions... options); /** - * @see org.jclouds.glesys.features.EmailApi#editAlias + * @see org.jclouds.glesys.features.EmailAccountApi#updateAlias */ @POST @Consumes(MediaType.APPLICATION_JSON) @SelectJson("alias") @Path("/email/editalias/format/json") - ListenableFuture editAlias(@FormParam("emailalias") String aliasAddress, @FormParam("goto") String toEmailAddress); + ListenableFuture updateAlias(@FormParam("emailalias") String aliasAddress, @FormParam("goto") String toEmailAddress); /** - * @see org.jclouds.glesys.features.EmailApi#delete + * @see org.jclouds.glesys.features.EmailAccountApi#delete */ @POST @Path("/email/delete/format/json") + @ExceptionParser(ReturnTrueOn404.class) ListenableFuture delete(@FormParam("email") String accountAddress); } diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/features/IpApi.java b/providers/glesys/src/main/java/org/jclouds/glesys/features/IpApi.java similarity index 87% rename from labs/glesys/src/main/java/org/jclouds/glesys/features/IpApi.java rename to providers/glesys/src/main/java/org/jclouds/glesys/features/IpApi.java index b81ee875bc..571be6b108 100644 --- a/labs/glesys/src/main/java/org/jclouds/glesys/features/IpApi.java +++ b/providers/glesys/src/main/java/org/jclouds/glesys/features/IpApi.java @@ -18,13 +18,14 @@ */ package org.jclouds.glesys.features; -import java.util.Set; import java.util.concurrent.TimeUnit; import org.jclouds.concurrent.Timeout; import org.jclouds.glesys.domain.IpDetails; import org.jclouds.glesys.options.ListIpOptions; +import com.google.common.collect.FluentIterable; + /** * Provides synchronous access to IP Addresses. *

@@ -43,7 +44,7 @@ public interface IpApi { * @param platform the platform * @return a set of free IP addresses */ - Set listFree(int ipVersion, String datacenter, String platform); + FluentIterable listFree(int ipVersion, String datacenter, String platform); /** * Take a free IP address and add it to this account. You can list free IP addresses with the function listFree(). @@ -67,7 +68,7 @@ public interface IpApi { * @param options options to filter the results (by IPV4/6, serverId, etc) * @return the set of IP addresses */ - Set listIps(ListIpOptions... options); + FluentIterable list(ListIpOptions... options); /** * Get details about the given IP address such as gateway and netmask. Different details are available @@ -76,7 +77,7 @@ public interface IpApi { * @param ipAddress the ip address * @return details about the given IP address */ - IpDetails getIp(String ipAddress); + IpDetails get(String ipAddress); /** * Add an IP address to an server. The IP has to be free, but reserved to this account. You are able to list such addresses @@ -87,27 +88,27 @@ public interface IpApi { * @param ipAddress the IP address to remove * @param serverId the server to add the IP address to */ - IpDetails addIpToServer(String ipAddress, String serverId); + IpDetails addToServer(String ipAddress, String serverId); /** * Remove an IP address from a server. This does not release it back to GleSYS pool of free ips. The address will be * kept on the account so that you can use it for other servers or the same server at a later time. To completely remove - * the IP address from this account, use removeIpFromServerAndRelease to do so + * the IP address from this account, use removeFromServerAndRelease to do so * * @param ipAddress the IP address to remove * @param serverId the server to remove the IP address from - * @see #removeIpFromServerAndRelease + * @see #removeFromServerAndRelease */ - IpDetails removeIpFromServer(String ipAddress, String serverId); + IpDetails removeFromServer(String ipAddress, String serverId); /** * Remove an IP address from a server and release it back to GleSYS pool of free ips. * * @param ipAddress the IP address to remove * @param serverId the server to remove the IP address from - * @see #removeIpFromServer + * @see #removeFromServer */ - IpDetails removeIpFromServerAndRelease(String ipAddress, String serverId); + IpDetails removeFromServerAndRelease(String ipAddress, String serverId); /** * Sets PTR data for an IP. Use ip/listown or ip/details to get current PTR data diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/features/IpAsyncApi.java b/providers/glesys/src/main/java/org/jclouds/glesys/features/IpAsyncApi.java similarity index 81% rename from labs/glesys/src/main/java/org/jclouds/glesys/features/IpAsyncApi.java rename to providers/glesys/src/main/java/org/jclouds/glesys/features/IpAsyncApi.java index 2e2a2837bf..3695f0d92a 100644 --- a/labs/glesys/src/main/java/org/jclouds/glesys/features/IpAsyncApi.java +++ b/providers/glesys/src/main/java/org/jclouds/glesys/features/IpAsyncApi.java @@ -18,8 +18,6 @@ */ package org.jclouds.glesys.features; -import java.util.Set; - import javax.ws.rs.Consumes; import javax.ws.rs.FormParam; import javax.ws.rs.GET; @@ -35,9 +33,10 @@ import org.jclouds.rest.annotations.ExceptionParser; import org.jclouds.rest.annotations.FormParams; import org.jclouds.rest.annotations.RequestFilters; import org.jclouds.rest.annotations.SelectJson; -import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404; +import org.jclouds.rest.functions.ReturnEmptyFluentIterableOnNotFoundOr404; import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; +import com.google.common.collect.FluentIterable; import com.google.common.util.concurrent.ListenableFuture; /** @@ -57,8 +56,8 @@ public interface IpAsyncApi { @Path("/ip/listfree/ipversion/{ipversion}/datacenter/{datacenter}/platform/{platform}/format/json") @Consumes(MediaType.APPLICATION_JSON) @SelectJson("ipaddresses") - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> listFree(@PathParam("ipversion") int ipversion, + @ExceptionParser(ReturnEmptyFluentIterableOnNotFoundOr404.class) + ListenableFuture> listFree(@PathParam("ipversion") int ipversion, @PathParam("datacenter") String datacenter, @PathParam("platform") String platform); @@ -81,54 +80,54 @@ public interface IpAsyncApi { ListenableFuture release(@FormParam("ipaddress") String ipAddress); /** - * @see IpApi#listIps + * @see IpApi#list */ @GET @Path("/ip/listown/format/json") @Consumes(MediaType.APPLICATION_JSON) @SelectJson("iplist") - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> listIps(ListIpOptions... options); + @ExceptionParser(ReturnEmptyFluentIterableOnNotFoundOr404.class) + ListenableFuture> list(ListIpOptions... options); /** - * @see IpApi#getIp + * @see IpApi#get */ @GET @Path("/ip/details/ipaddress/{ipaddress}/format/json") @SelectJson("details") @Consumes(MediaType.APPLICATION_JSON) @ExceptionParser(ReturnNullOnNotFoundOr404.class) - ListenableFuture getIp(@PathParam("ipaddress") String ipAddress); + ListenableFuture get(@PathParam("ipaddress") String ipAddress); /** - * @see IpApi#addIpToServer + * @see IpApi#addToServer */ @POST @Path("/ip/add/format/json") @SelectJson("details") @Consumes(MediaType.APPLICATION_JSON) - ListenableFuture addIpToServer(@FormParam("ipaddress") String ipAddress, + ListenableFuture addToServer(@FormParam("ipaddress") String ipAddress, @FormParam("serverid") String serverId); /** - * @see IpApi#removeIpFromServer + * @see IpApi#removeFromServer */ @POST @Path("/ip/remove/format/json") @SelectJson("details") @Consumes(MediaType.APPLICATION_JSON) - ListenableFuture removeIpFromServer(@FormParam("ipaddress") String ipAddress, + ListenableFuture removeFromServer(@FormParam("ipaddress") String ipAddress, @FormParam("serverid") String serverId); /** - * @see IpApi#removeIpFromServer + * @see IpApi#removeFromServer */ @POST @FormParams(keys = "release", values = "true") @Path("/ip/remove/format/json") @SelectJson("details") @Consumes(MediaType.APPLICATION_JSON) - ListenableFuture removeIpFromServerAndRelease(@FormParam("ipaddress") String ipAddress, + ListenableFuture removeFromServerAndRelease(@FormParam("ipaddress") String ipAddress, @FormParam("serverid") String serverId); /** diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/features/ServerApi.java b/providers/glesys/src/main/java/org/jclouds/glesys/features/ServerApi.java similarity index 84% rename from labs/glesys/src/main/java/org/jclouds/glesys/features/ServerApi.java rename to providers/glesys/src/main/java/org/jclouds/glesys/features/ServerApi.java index 370974fc77..da32f36beb 100644 --- a/labs/glesys/src/main/java/org/jclouds/glesys/features/ServerApi.java +++ b/providers/glesys/src/main/java/org/jclouds/glesys/features/ServerApi.java @@ -19,7 +19,6 @@ package org.jclouds.glesys.features; import java.util.Map; -import java.util.Set; import java.util.concurrent.TimeUnit; import org.jclouds.concurrent.Timeout; @@ -35,10 +34,11 @@ import org.jclouds.glesys.domain.ServerStatus; import org.jclouds.glesys.options.CloneServerOptions; import org.jclouds.glesys.options.CreateServerOptions; import org.jclouds.glesys.options.DestroyServerOptions; -import org.jclouds.glesys.options.EditServerOptions; +import org.jclouds.glesys.options.UpdateServerOptions; import org.jclouds.glesys.options.ServerStatusOptions; import com.google.common.annotations.Beta; +import com.google.common.collect.FluentIterable; /** * Provides synchronous access to Server. @@ -57,7 +57,7 @@ public interface ServerApi { * * @return an account's associated server objects. */ - Set listServers(); + FluentIterable list(); /** * Get detailed information about a server such as hostname, hardware @@ -67,7 +67,7 @@ public interface ServerApi { * @param id id of the server * @return server or null if not found */ - ServerDetails getServerDetails(String id); + ServerDetails get(String id); /** * Get detailed information about a server status including up-time and @@ -77,7 +77,7 @@ public interface ServerApi { * @param options optional parameters * @return the status of the server or null if not found */ - ServerStatus getServerStatus(String id, ServerStatusOptions... options); + ServerStatus getStatus(String id, ServerStatusOptions... options); /** * Get detailed information about a server's limits (for OpenVZ only). @@ -86,7 +86,7 @@ public interface ServerApi { * @param id id of the server * @return the requested information about the server or null if not found */ - Map getServerLimits(String id); + Map getLimits(String id); /** * Get information about how to connect to a server via VNC @@ -101,14 +101,14 @@ public interface ServerApi { * * @return the set of information about each template */ - Set listTemplates(); + FluentIterable listTemplates(); /** * Get information about valid arguments to #createServer for each platform * * @return a map of argument lists, keyed on platform */ - Map getAllowedArgumentsForCreateServerByPlatform(); + Map getAllowedArgumentsForCreateByPlatform(); /** * Reset the fail count for a server limit (for OpenVZ only). @@ -116,35 +116,35 @@ public interface ServerApi { * @param id id of the server * @param type the type of limit to reset */ - Map resetServerLimit(String id, String type); + Map resetLimit(String id, String type); /** * Reboot a server * * @param id id of the server */ - ServerDetails rebootServer(String id); + ServerDetails reboot(String id); /** * Start a server * * @param id id of the server */ - ServerDetails startServer(String id); + ServerDetails start(String id); /** * Stop a server * * @param id id of the server */ - ServerDetails stopServer(String id); + ServerDetails stop(String id); /** * hard stop a server * * @param id id of the server */ - ServerDetails hardStopServer(String id); + ServerDetails hardStop(String id); /** * Create a new server @@ -154,16 +154,16 @@ public interface ServerApi { * @param options optional settings ex. description */ @Timeout(duration = 180, timeUnit = TimeUnit.SECONDS) - ServerDetails createServerWithHostnameAndRootPassword(ServerSpec serverSpec, String hostname, String rootPassword, + ServerDetails createWithHostnameAndRootPassword(ServerSpec serverSpec, String hostname, String rootPassword, CreateServerOptions... options); /** - * Edit the configuration of a server + * Update the configuration of a server * * @param serverid the serverId of the server to edit * @param options the settings to change */ - ServerDetails editServer(String serverid, EditServerOptions... options); + ServerDetails update(String serverid, UpdateServerOptions options); /** * Clone a server @@ -173,7 +173,7 @@ public interface ServerApi { * @param options the settings to change */ @Timeout(duration = 180, timeUnit = TimeUnit.SECONDS) - ServerDetails cloneServer(String serverid, String hostname, CloneServerOptions... options); + ServerDetails clone(String serverid, String hostname, CloneServerOptions... options); /** * Destroy a server @@ -181,7 +181,7 @@ public interface ServerApi { * @param id the id of the server * @param keepIp if DestroyServerOptions.keepIp(true) the servers ip will be retained for use in your GleSYS account */ - ServerDetails destroyServer(String id, DestroyServerOptions keepIp); + ServerDetails destroy(String id, DestroyServerOptions keepIp); /** * Reset the root password of a server diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/features/ServerAsyncApi.java b/providers/glesys/src/main/java/org/jclouds/glesys/features/ServerAsyncApi.java similarity index 74% rename from labs/glesys/src/main/java/org/jclouds/glesys/features/ServerAsyncApi.java rename to providers/glesys/src/main/java/org/jclouds/glesys/features/ServerAsyncApi.java index 92a8ccdae7..8024622910 100644 --- a/labs/glesys/src/main/java/org/jclouds/glesys/features/ServerAsyncApi.java +++ b/providers/glesys/src/main/java/org/jclouds/glesys/features/ServerAsyncApi.java @@ -19,7 +19,6 @@ package org.jclouds.glesys.features; import java.util.Map; -import java.util.Set; import java.util.SortedMap; import javax.ws.rs.Consumes; @@ -42,7 +41,7 @@ import org.jclouds.glesys.functions.ParseTemplatesFromHttpResponse; import org.jclouds.glesys.options.CloneServerOptions; import org.jclouds.glesys.options.CreateServerOptions; import org.jclouds.glesys.options.DestroyServerOptions; -import org.jclouds.glesys.options.EditServerOptions; +import org.jclouds.glesys.options.UpdateServerOptions; import org.jclouds.glesys.options.ServerStatusOptions; import org.jclouds.http.filters.BasicAuthentication; import org.jclouds.rest.annotations.ExceptionParser; @@ -52,9 +51,10 @@ import org.jclouds.rest.annotations.PayloadParam; import org.jclouds.rest.annotations.RequestFilters; import org.jclouds.rest.annotations.ResponseParser; import org.jclouds.rest.annotations.SelectJson; -import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404; +import org.jclouds.rest.functions.ReturnEmptyFluentIterableOnNotFoundOr404; import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; +import com.google.common.collect.FluentIterable; import com.google.common.util.concurrent.ListenableFuture; /** @@ -70,17 +70,17 @@ import com.google.common.util.concurrent.ListenableFuture; public interface ServerAsyncApi { /** - * @see ServerApi#listServers + * @see ServerApi#list */ @POST @Path("/server/list/format/json") @SelectJson("servers") @Consumes(MediaType.APPLICATION_JSON) - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> listServers(); + @ExceptionParser(ReturnEmptyFluentIterableOnNotFoundOr404.class) + ListenableFuture> list(); /** - * @see ServerApi#getServerDetails + * @see ServerApi#get */ @POST @Path("/server/details/format/json") @@ -88,27 +88,27 @@ public interface ServerAsyncApi { @Consumes(MediaType.APPLICATION_JSON) @FormParams(keys = "includestate", values = "true") @ExceptionParser(ReturnNullOnNotFoundOr404.class) - ListenableFuture getServerDetails(@FormParam("serverid") String id); + ListenableFuture get(@FormParam("serverid") String id); /** - * @see ServerApi#getServerStatus + * @see ServerApi#getStatus */ @POST @Path("/server/status/format/json") @SelectJson("server") @Consumes(MediaType.APPLICATION_JSON) @ExceptionParser(ReturnNullOnNotFoundOr404.class) - ListenableFuture getServerStatus(@FormParam("serverid") String id, ServerStatusOptions... options); + ListenableFuture getStatus(@FormParam("serverid") String id, ServerStatusOptions... options); /** - * @see ServerApi#getServerLimits + * @see ServerApi#getLimits */ @POST @Path("/server/limits/format/json") @SelectJson("limits") @Consumes(MediaType.APPLICATION_JSON) @ExceptionParser(ReturnNullOnNotFoundOr404.class) - ListenableFuture> getServerLimits(@FormParam("serverid") String id); + ListenableFuture> getLimits(@FormParam("serverid") String id); /** * @see ServerApi#getConsole @@ -121,13 +121,13 @@ public interface ServerAsyncApi { ListenableFuture getConsole(@FormParam("serverid") String id); /** - * @see ServerApi#getAllowedArgumentsForCreateServerByPlatform + * @see ServerApi#getAllowedArgumentsForCreateByPlatform */ @GET @Path("/server/allowedarguments/format/json") @SelectJson("argumentslist") @Consumes(MediaType.APPLICATION_JSON) - ListenableFuture> getAllowedArgumentsForCreateServerByPlatform(); + ListenableFuture> getAllowedArgumentsForCreateByPlatform(); /** * @see ServerApi#listTemplates @@ -135,92 +135,93 @@ public interface ServerAsyncApi { @GET @Path("/server/templates/format/json") @ResponseParser(ParseTemplatesFromHttpResponse.class) + @ExceptionParser(ReturnEmptyFluentIterableOnNotFoundOr404.class) @Consumes(MediaType.APPLICATION_JSON) - ListenableFuture> listTemplates(); + ListenableFuture> listTemplates(); /** - * @see ServerApi#stopServer + * @see ServerApi#stop */ @POST @Path("/server/resetlimit/format/json") @Consumes(MediaType.APPLICATION_JSON) - ListenableFuture> resetServerLimit(@FormParam("serverid") String id, + ListenableFuture> resetLimit(@FormParam("serverid") String id, @FormParam("type") String type); /** - * @see ServerApi#rebootServer + * @see ServerApi#reboot */ @POST @SelectJson("server") @Path("/server/reboot/format/json") @Consumes(MediaType.APPLICATION_JSON) - ListenableFuture rebootServer(@FormParam("serverid") String id); + ListenableFuture reboot(@FormParam("serverid") String id); /** - * @see ServerApi#startServer + * @see ServerApi#start */ @POST @SelectJson("server") @Path("/server/start/format/json") @Consumes(MediaType.APPLICATION_JSON) - ListenableFuture startServer(@FormParam("serverid") String id); + ListenableFuture start(@FormParam("serverid") String id); /** - * @see ServerApi#stopServer + * @see ServerApi#stop */ @POST @SelectJson("server") @Path("/server/stop/format/json") @Consumes(MediaType.APPLICATION_JSON) - ListenableFuture stopServer(@FormParam("serverid") String id); + ListenableFuture stop(@FormParam("serverid") String id); /** - * @see ServerApi#hardStopServer + * @see ServerApi#hardStop */ @POST @SelectJson("server") @Path("/server/stop/format/json") @FormParams(keys = "type", values = "hard") @Consumes(MediaType.APPLICATION_JSON) - ListenableFuture hardStopServer(@FormParam("serverid") String id); + ListenableFuture hardStop(@FormParam("serverid") String id); /** - * @see ServerApi#createServerWithHostnameAndRootPassword + * @see ServerApi#createWithHostnameAndRootPassword */ @POST @SelectJson("server") @Path("/server/create/format/json") @Consumes(MediaType.APPLICATION_JSON) @MapBinder(CreateServerOptions.class) - ListenableFuture createServerWithHostnameAndRootPassword(ServerSpec serverSpec, + ListenableFuture createWithHostnameAndRootPassword(ServerSpec serverSpec, @PayloadParam("hostname") String hostname, @PayloadParam("rootpassword") String rootPassword, CreateServerOptions... options); /** - * @see ServerApi#cloneServer + * @see ServerApi#clone */ @POST @Path("/server/clone/format/json") @SelectJson("server") @Consumes(MediaType.APPLICATION_JSON) - ListenableFuture cloneServer(@FormParam("serverid") String serverid, + ListenableFuture clone(@FormParam("serverid") String serverid, @FormParam("hostname") String hostname, CloneServerOptions... options); /** - * @see ServerApi#editServer + * @see ServerApi#update */ @POST @Path("/server/edit/format/json") @SelectJson("server") @Consumes(MediaType.APPLICATION_JSON) - ListenableFuture editServer(@FormParam("serverid") String serverid, EditServerOptions... options); + ListenableFuture update(@FormParam("serverid") String serverid, UpdateServerOptions options); /** - * @see ServerApi#destroyServer + * @see ServerApi#destroy */ @POST @Path("/server/destroy/format/json") - ListenableFuture destroyServer(@FormParam("serverid") String id, DestroyServerOptions keepIp); + ListenableFuture destroy(@FormParam("serverid") String id, DestroyServerOptions keepIp); /** * @see ServerApi#resetPassword diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/functions/ParseTemplatesFromHttpResponse.java b/providers/glesys/src/main/java/org/jclouds/glesys/functions/ParseTemplatesFromHttpResponse.java similarity index 89% rename from labs/glesys/src/main/java/org/jclouds/glesys/functions/ParseTemplatesFromHttpResponse.java rename to providers/glesys/src/main/java/org/jclouds/glesys/functions/ParseTemplatesFromHttpResponse.java index c03f109e27..60738f3eb1 100644 --- a/labs/glesys/src/main/java/org/jclouds/glesys/functions/ParseTemplatesFromHttpResponse.java +++ b/providers/glesys/src/main/java/org/jclouds/glesys/functions/ParseTemplatesFromHttpResponse.java @@ -31,7 +31,7 @@ import org.jclouds.http.functions.ParseFirstJsonValueNamed; import org.jclouds.json.internal.GsonWrapper; import com.google.common.base.Function; -import com.google.common.collect.ImmutableSet; +import com.google.common.collect.FluentIterable; import com.google.common.collect.Iterables; import com.google.inject.Inject; import com.google.inject.TypeLiteral; @@ -40,7 +40,7 @@ import com.google.inject.TypeLiteral; * @author Adrian Cole */ @Singleton -public class ParseTemplatesFromHttpResponse implements Function> { +public class ParseTemplatesFromHttpResponse implements Function> { private final ParseFirstJsonValueNamed>> parser; @Inject @@ -50,10 +50,10 @@ public class ParseTemplatesFromHttpResponse implements Function apply(HttpResponse response) { + public FluentIterable apply(HttpResponse response) { checkNotNull(response, "response"); Map> toParse = parser.apply(response); checkNotNull(toParse, "parsed result from %s", response); - return ImmutableSet.copyOf(Iterables.concat(toParse.values())); + return FluentIterable.from(Iterables.concat(toParse.values())); } } diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/functions/internal/GleSYSTypeAdapters.java b/providers/glesys/src/main/java/org/jclouds/glesys/functions/internal/GleSYSTypeAdapters.java similarity index 94% rename from labs/glesys/src/main/java/org/jclouds/glesys/functions/internal/GleSYSTypeAdapters.java rename to providers/glesys/src/main/java/org/jclouds/glesys/functions/internal/GleSYSTypeAdapters.java index b460d2e28c..8391069d8d 100644 --- a/labs/glesys/src/main/java/org/jclouds/glesys/functions/internal/GleSYSTypeAdapters.java +++ b/providers/glesys/src/main/java/org/jclouds/glesys/functions/internal/GleSYSTypeAdapters.java @@ -42,6 +42,10 @@ public class GleSYSTypeAdapters { @Override public Server.State read(JsonReader reader) throws IOException { + if (reader.peek() == JsonToken.NULL) { + reader.nextNull(); + return Server.State.UNRECOGNIZED; + } return Server.State.fromValue(reader.nextString()); } } diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/handlers/GleSYSErrorHandler.java b/providers/glesys/src/main/java/org/jclouds/glesys/handlers/GleSYSErrorHandler.java similarity index 91% rename from labs/glesys/src/main/java/org/jclouds/glesys/handlers/GleSYSErrorHandler.java rename to providers/glesys/src/main/java/org/jclouds/glesys/handlers/GleSYSErrorHandler.java index 82afc0fc17..f6fd125956 100644 --- a/labs/glesys/src/main/java/org/jclouds/glesys/handlers/GleSYSErrorHandler.java +++ b/providers/glesys/src/main/java/org/jclouds/glesys/handlers/GleSYSErrorHandler.java @@ -56,12 +56,16 @@ public class GleSYSErrorHandler implements HttpErrorHandler { exception = new AuthorizationException(message, exception); break; case 400: - if (message.indexOf("Could not find") != -1) { + if (message.indexOf("not find") != -1) { exception = new ResourceNotFoundException(message, exception); } break; case 404: - exception = new ResourceNotFoundException(message, exception); + if (message.indexOf("Not supported") != -1) { + exception = new UnsupportedOperationException(message, exception); + } else { + exception = new ResourceNotFoundException(message, exception); + } break; case 500: if (message.indexOf("Locked") != -1) { diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/options/AddDomainOptions.java b/providers/glesys/src/main/java/org/jclouds/glesys/options/AddDomainOptions.java similarity index 100% rename from labs/glesys/src/main/java/org/jclouds/glesys/options/AddDomainOptions.java rename to providers/glesys/src/main/java/org/jclouds/glesys/options/AddDomainOptions.java diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/options/AddRecordOptions.java b/providers/glesys/src/main/java/org/jclouds/glesys/options/AddRecordOptions.java similarity index 100% rename from labs/glesys/src/main/java/org/jclouds/glesys/options/AddRecordOptions.java rename to providers/glesys/src/main/java/org/jclouds/glesys/options/AddRecordOptions.java diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/options/CloneServerOptions.java b/providers/glesys/src/main/java/org/jclouds/glesys/options/CloneServerOptions.java similarity index 95% rename from labs/glesys/src/main/java/org/jclouds/glesys/options/CloneServerOptions.java rename to providers/glesys/src/main/java/org/jclouds/glesys/options/CloneServerOptions.java index 07f423a538..4185c08516 100644 --- a/labs/glesys/src/main/java/org/jclouds/glesys/options/CloneServerOptions.java +++ b/providers/glesys/src/main/java/org/jclouds/glesys/options/CloneServerOptions.java @@ -21,7 +21,7 @@ package org.jclouds.glesys.options; /** * @author Adam Lowe */ -public class CloneServerOptions extends EditServerOptions { +public class CloneServerOptions extends UpdateServerOptions { public static class Builder { /** * @see org.jclouds.glesys.options.CloneServerOptions#diskSizeGB @@ -52,7 +52,7 @@ public class CloneServerOptions extends EditServerOptions { } /** - * @see org.jclouds.glesys.options.EditServerOptions#description + * @see org.jclouds.glesys.options.UpdateServerOptions#description */ public static CloneServerOptions description(String description) { return CloneServerOptions.class.cast(new CloneServerOptions().description(description)); diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/options/CreateAccountOptions.java b/providers/glesys/src/main/java/org/jclouds/glesys/options/CreateAccountOptions.java similarity index 100% rename from labs/glesys/src/main/java/org/jclouds/glesys/options/CreateAccountOptions.java rename to providers/glesys/src/main/java/org/jclouds/glesys/options/CreateAccountOptions.java diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/options/CreateServerOptions.java b/providers/glesys/src/main/java/org/jclouds/glesys/options/CreateServerOptions.java similarity index 100% rename from labs/glesys/src/main/java/org/jclouds/glesys/options/CreateServerOptions.java rename to providers/glesys/src/main/java/org/jclouds/glesys/options/CreateServerOptions.java diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/options/DestroyServerOptions.java b/providers/glesys/src/main/java/org/jclouds/glesys/options/DestroyServerOptions.java similarity index 100% rename from labs/glesys/src/main/java/org/jclouds/glesys/options/DestroyServerOptions.java rename to providers/glesys/src/main/java/org/jclouds/glesys/options/DestroyServerOptions.java diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/options/DomainOptions.java b/providers/glesys/src/main/java/org/jclouds/glesys/options/DomainOptions.java similarity index 100% rename from labs/glesys/src/main/java/org/jclouds/glesys/options/DomainOptions.java rename to providers/glesys/src/main/java/org/jclouds/glesys/options/DomainOptions.java diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/options/ListIpOptions.java b/providers/glesys/src/main/java/org/jclouds/glesys/options/ListIpOptions.java similarity index 100% rename from labs/glesys/src/main/java/org/jclouds/glesys/options/ListIpOptions.java rename to providers/glesys/src/main/java/org/jclouds/glesys/options/ListIpOptions.java diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/options/ServerStatusOptions.java b/providers/glesys/src/main/java/org/jclouds/glesys/options/ServerStatusOptions.java similarity index 100% rename from labs/glesys/src/main/java/org/jclouds/glesys/options/ServerStatusOptions.java rename to providers/glesys/src/main/java/org/jclouds/glesys/options/ServerStatusOptions.java diff --git a/providers/glesys/src/main/java/org/jclouds/glesys/options/UpdateAccountOptions.java b/providers/glesys/src/main/java/org/jclouds/glesys/options/UpdateAccountOptions.java new file mode 100644 index 0000000000..9c3c5a37ad --- /dev/null +++ b/providers/glesys/src/main/java/org/jclouds/glesys/options/UpdateAccountOptions.java @@ -0,0 +1,77 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.glesys.options; + + +/** + * @author Adam Lowe + * @see + */ +public class UpdateAccountOptions extends CreateAccountOptions { + + public static class Builder { + /** + * @see org.jclouds.glesys.options.UpdateAccountOptions#antispamLevel + */ + public static UpdateAccountOptions antispamLevel(int antispamLevel) { + return UpdateAccountOptions.class.cast(new UpdateAccountOptions().antispamLevel(antispamLevel)); + } + + /** + * @see org.jclouds.glesys.options.UpdateAccountOptions#antiVirus + */ + public static UpdateAccountOptions antiVirus(boolean antiVirus) { + return UpdateAccountOptions.class.cast(new UpdateAccountOptions().antiVirus(antiVirus)); + } + + /** + * @see org.jclouds.glesys.options.UpdateAccountOptions#autorespond + */ + public static UpdateAccountOptions autorespond(boolean autorespond) { + return UpdateAccountOptions.class.cast(new UpdateAccountOptions().autorespond(autorespond)); + } + + /** + * @see org.jclouds.glesys.options.UpdateAccountOptions#autorespondSaveEmail + */ + public static UpdateAccountOptions autorespondSaveEmail(boolean autorespondSaveEmail) { + return UpdateAccountOptions.class.cast(new UpdateAccountOptions().autorespondSaveEmail(autorespondSaveEmail)); + } + + /** + * @see org.jclouds.glesys.options.UpdateAccountOptions#autorespondMessage + */ + public static UpdateAccountOptions autorespondMessage(String autorespondMessage) { + return UpdateAccountOptions.class.cast(new UpdateAccountOptions().autorespondMessage(autorespondMessage)); + } + + /** + * @see org.jclouds.glesys.options.UpdateAccountOptions#password + */ + public static UpdateAccountOptions password(String password) { + return new UpdateAccountOptions().password(password); + } + } + + /** Reset the password for this account */ + public UpdateAccountOptions password(String password) { + formParameters.put("password", password); + return this; + } +} diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/options/EditRecordOptions.java b/providers/glesys/src/main/java/org/jclouds/glesys/options/UpdateRecordOptions.java similarity index 59% rename from labs/glesys/src/main/java/org/jclouds/glesys/options/EditRecordOptions.java rename to providers/glesys/src/main/java/org/jclouds/glesys/options/UpdateRecordOptions.java index be5b4de395..8fa7571d88 100644 --- a/labs/glesys/src/main/java/org/jclouds/glesys/options/EditRecordOptions.java +++ b/providers/glesys/src/main/java/org/jclouds/glesys/options/UpdateRecordOptions.java @@ -21,54 +21,59 @@ package org.jclouds.glesys.options; /** * @author Adam Lowe */ -public class EditRecordOptions extends AddRecordOptions { +public class UpdateRecordOptions extends AddRecordOptions { public static class Builder { /** - * @see EditRecordOptions#host + * @see UpdateRecordOptions#host */ - public static EditRecordOptions host(String host) { - return new EditRecordOptions().host(host); + public static UpdateRecordOptions host(String host) { + return new UpdateRecordOptions().host(host); } /** - * @see EditRecordOptions#type + * @see UpdateRecordOptions#type */ - public static EditRecordOptions type(String type) { - return new EditRecordOptions().type(type); + public static UpdateRecordOptions type(String type) { + return new UpdateRecordOptions().type(type); } /** - * @see EditRecordOptions#data + * @see UpdateRecordOptions#data */ - public static EditRecordOptions data(String data) { - return new EditRecordOptions().data(data); + public static UpdateRecordOptions data(String data) { + return new UpdateRecordOptions().data(data); } /** - * @see EditRecordOptions#ttl + * @see UpdateRecordOptions#ttl */ - public static EditRecordOptions ttl(int ttl) { - return EditRecordOptions.class.cast(new EditRecordOptions().ttl(ttl)); + public static UpdateRecordOptions ttl(int ttl) { + return UpdateRecordOptions.class.cast(new UpdateRecordOptions().ttl(ttl)); } } /** Configure the hostname attached to this record */ - public EditRecordOptions host(String host) { + public UpdateRecordOptions host(String host) { formParameters.put("host", host); return this; } /** Configure the type of record, ex. "A", "CNAME" or "MX" */ - public EditRecordOptions type(String type) { + public UpdateRecordOptions type(String type) { formParameters.put("type", type); return this; } /** Set the content of this record (depending on type, for an "A" record this would be an ip address) */ - public EditRecordOptions data(String data) { + public UpdateRecordOptions data(String data) { formParameters.put("data", data); return this; } + + @Override + public UpdateRecordOptions ttl(int ttl) { + return UpdateRecordOptions.class.cast(super.ttl(ttl)); + } } diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/options/EditServerOptions.java b/providers/glesys/src/main/java/org/jclouds/glesys/options/UpdateServerOptions.java similarity index 56% rename from labs/glesys/src/main/java/org/jclouds/glesys/options/EditServerOptions.java rename to providers/glesys/src/main/java/org/jclouds/glesys/options/UpdateServerOptions.java index 3b9d4d1892..c17516a934 100644 --- a/labs/glesys/src/main/java/org/jclouds/glesys/options/EditServerOptions.java +++ b/providers/glesys/src/main/java/org/jclouds/glesys/options/UpdateServerOptions.java @@ -24,87 +24,87 @@ import org.jclouds.http.options.BaseHttpRequestOptions; * * @author Adam Lowe */ -public class EditServerOptions extends BaseHttpRequestOptions { +public class UpdateServerOptions extends BaseHttpRequestOptions { public static class Builder { /** - * @see org.jclouds.glesys.options.EditServerOptions#diskSizeGB + * @see org.jclouds.glesys.options.UpdateServerOptions#diskSizeGB */ - public static EditServerOptions disksizeGB(int disksizeGB) { - return new EditServerOptions().diskSizeGB(disksizeGB); + public static UpdateServerOptions disksizeGB(int disksizeGB) { + return new UpdateServerOptions().diskSizeGB(disksizeGB); } /** - * @see org.jclouds.glesys.options.EditServerOptions#memorySizeMB + * @see org.jclouds.glesys.options.UpdateServerOptions#memorySizeMB */ - public static EditServerOptions memorysizeMB(int memorysizeMB) { - return new EditServerOptions().memorySizeMB(memorysizeMB); + public static UpdateServerOptions memorysizeMB(int memorysizeMB) { + return new UpdateServerOptions().memorySizeMB(memorysizeMB); } /** - * @see org.jclouds.glesys.options.EditServerOptions#cpuCores + * @see org.jclouds.glesys.options.UpdateServerOptions#cpuCores */ - public static EditServerOptions cpucores(int cpucores) { - EditServerOptions options = new EditServerOptions(); + public static UpdateServerOptions cpucores(int cpucores) { + UpdateServerOptions options = new UpdateServerOptions(); return options.cpuCores(cpucores); } /** - * @see org.jclouds.glesys.options.EditServerOptions#transferGB + * @see org.jclouds.glesys.options.UpdateServerOptions#transferGB */ - public static EditServerOptions transferGB(int transferGB) { - return new EditServerOptions().transferGB(transferGB); + public static UpdateServerOptions transferGB(int transferGB) { + return new UpdateServerOptions().transferGB(transferGB); } /** - * @see org.jclouds.glesys.options.EditServerOptions#hostname + * @see org.jclouds.glesys.options.UpdateServerOptions#hostname */ - public static EditServerOptions hostname(String hostname) { - EditServerOptions options = new EditServerOptions(); + public static UpdateServerOptions hostname(String hostname) { + UpdateServerOptions options = new UpdateServerOptions(); return options.hostname(hostname); } /** - * @see org.jclouds.glesys.options.EditServerOptions#description + * @see org.jclouds.glesys.options.UpdateServerOptions#description */ - public static EditServerOptions description(String description) { - EditServerOptions options = new EditServerOptions(); + public static UpdateServerOptions description(String description) { + UpdateServerOptions options = new UpdateServerOptions(); return options.description(description); } } /** Configure the size of the disk, in GB, of the server */ - public EditServerOptions diskSizeGB(int diskSizeGB) { + public UpdateServerOptions diskSizeGB(int diskSizeGB) { formParameters.put("disksize", Integer.toString(diskSizeGB)); return this; } /** Configure the amount of RAM, in MB, allocated to the server */ - public EditServerOptions memorySizeMB(int memorySizeMB) { + public UpdateServerOptions memorySizeMB(int memorySizeMB) { formParameters.put("memorysize", Integer.toString(memorySizeMB)); return this; } /** Configure the number of CPU cores allocated to the server */ - public EditServerOptions cpuCores(int cpucores) { + public UpdateServerOptions cpuCores(int cpucores) { formParameters.put("cpucores", Integer.toString(cpucores)); return this; } /** Configure the transfer setting for the server */ - public EditServerOptions transferGB(int transferGB) { + public UpdateServerOptions transferGB(int transferGB) { formParameters.put("transfer", Integer.toString(transferGB)); return this; } /** Configure the host name of the server (must be unique within the GleSYS account) */ - public EditServerOptions hostname(String hostname) { + public UpdateServerOptions hostname(String hostname) { formParameters.put("hostname", hostname); return this; } /** Configure the description of the server */ - public EditServerOptions description(String description) { + public UpdateServerOptions description(String description) { formParameters.put("description", description); return this; } diff --git a/labs/glesys/src/main/java/org/jclouds/glesys/reference/GleSYSConstants.java b/providers/glesys/src/main/java/org/jclouds/glesys/reference/GleSYSConstants.java similarity index 100% rename from labs/glesys/src/main/java/org/jclouds/glesys/reference/GleSYSConstants.java rename to providers/glesys/src/main/java/org/jclouds/glesys/reference/GleSYSConstants.java diff --git a/labs/glesys/src/main/resources/META-INF/services/org.jclouds.providers.ProviderMetadata b/providers/glesys/src/main/resources/META-INF/services/org.jclouds.providers.ProviderMetadata similarity index 100% rename from labs/glesys/src/main/resources/META-INF/services/org.jclouds.providers.ProviderMetadata rename to providers/glesys/src/main/resources/META-INF/services/org.jclouds.providers.ProviderMetadata diff --git a/labs/glesys/src/test/java/org/jclouds/glesys/GleSYSAsyncApiTest.java b/providers/glesys/src/test/java/org/jclouds/glesys/GleSYSAsyncApiTest.java similarity index 100% rename from labs/glesys/src/test/java/org/jclouds/glesys/GleSYSAsyncApiTest.java rename to providers/glesys/src/test/java/org/jclouds/glesys/GleSYSAsyncApiTest.java index db34cffecd..8f51ddbaf3 100644 --- a/labs/glesys/src/test/java/org/jclouds/glesys/GleSYSAsyncApiTest.java +++ b/providers/glesys/src/test/java/org/jclouds/glesys/GleSYSAsyncApiTest.java @@ -50,15 +50,15 @@ public class GleSYSAsyncApiTest extends BaseAsyncApiTest { public void testSync() throws SecurityException, NoSuchMethodException, InterruptedException, ExecutionException { assert syncApi.getServerApi() != null; assert syncApi.getIpApi() != null; - assert syncApi.getArchiveApi() != null; assert syncApi.getDomainApi() != null; + assert syncApi.getArchiveApi() != null; } public void testAsync() throws SecurityException, NoSuchMethodException, InterruptedException, ExecutionException { assert asyncApi.getServerApi() != null; assert asyncApi.getIpApi() != null; - assert asyncApi.getArchiveApi() != null; assert asyncApi.getDomainApi() != null; + assert asyncApi.getArchiveApi() != null; } @Override diff --git a/labs/glesys/src/test/java/org/jclouds/glesys/GleSYSErrorHandlerTest.java b/providers/glesys/src/test/java/org/jclouds/glesys/GleSYSErrorHandlerTest.java similarity index 100% rename from labs/glesys/src/test/java/org/jclouds/glesys/GleSYSErrorHandlerTest.java rename to providers/glesys/src/test/java/org/jclouds/glesys/GleSYSErrorHandlerTest.java diff --git a/labs/glesys/src/test/java/org/jclouds/glesys/GleSYSProviderTest.java b/providers/glesys/src/test/java/org/jclouds/glesys/GleSYSProviderTest.java similarity index 100% rename from labs/glesys/src/test/java/org/jclouds/glesys/GleSYSProviderTest.java rename to providers/glesys/src/test/java/org/jclouds/glesys/GleSYSProviderTest.java diff --git a/labs/glesys/src/test/java/org/jclouds/glesys/compute/GleSYSComputeServiceAdapterExpectTest.java b/providers/glesys/src/test/java/org/jclouds/glesys/compute/GleSYSComputeServiceAdapterExpectTest.java similarity index 100% rename from labs/glesys/src/test/java/org/jclouds/glesys/compute/GleSYSComputeServiceAdapterExpectTest.java rename to providers/glesys/src/test/java/org/jclouds/glesys/compute/GleSYSComputeServiceAdapterExpectTest.java diff --git a/labs/glesys/src/test/java/org/jclouds/glesys/compute/GleSYSComputeServiceLiveTest.java b/providers/glesys/src/test/java/org/jclouds/glesys/compute/GleSYSComputeServiceLiveTest.java similarity index 100% rename from labs/glesys/src/test/java/org/jclouds/glesys/compute/GleSYSComputeServiceLiveTest.java rename to providers/glesys/src/test/java/org/jclouds/glesys/compute/GleSYSComputeServiceLiveTest.java diff --git a/labs/glesys/src/test/java/org/jclouds/glesys/compute/GleSYSExperimentExpectTest.java b/providers/glesys/src/test/java/org/jclouds/glesys/compute/GleSYSExperimentExpectTest.java similarity index 100% rename from labs/glesys/src/test/java/org/jclouds/glesys/compute/GleSYSExperimentExpectTest.java rename to providers/glesys/src/test/java/org/jclouds/glesys/compute/GleSYSExperimentExpectTest.java diff --git a/labs/glesys/src/test/java/org/jclouds/glesys/compute/GleSYSExperimentLiveTest.java b/providers/glesys/src/test/java/org/jclouds/glesys/compute/GleSYSExperimentLiveTest.java similarity index 100% rename from labs/glesys/src/test/java/org/jclouds/glesys/compute/GleSYSExperimentLiveTest.java rename to providers/glesys/src/test/java/org/jclouds/glesys/compute/GleSYSExperimentLiveTest.java diff --git a/labs/glesys/src/test/java/org/jclouds/glesys/compute/GleSYSTemplateBuilderLiveTest.java b/providers/glesys/src/test/java/org/jclouds/glesys/compute/GleSYSTemplateBuilderLiveTest.java similarity index 94% rename from labs/glesys/src/test/java/org/jclouds/glesys/compute/GleSYSTemplateBuilderLiveTest.java rename to providers/glesys/src/test/java/org/jclouds/glesys/compute/GleSYSTemplateBuilderLiveTest.java index 0744fb632a..59d9e770a5 100644 --- a/labs/glesys/src/test/java/org/jclouds/glesys/compute/GleSYSTemplateBuilderLiveTest.java +++ b/providers/glesys/src/test/java/org/jclouds/glesys/compute/GleSYSTemplateBuilderLiveTest.java @@ -70,8 +70,8 @@ public class GleSYSTemplateBuilderLiveTest extends BaseTemplateBuilderLiveTest { return input.version.equals("") || input.version.equals("5") || input.version.equals("5.5") || input.version.equals("5.0") || input.version.equals("6.0"); case WINDOWS: - return input.version.equals("") || input.version.equals("2008") - || (input.version.equals("2008 R2") && input.is64Bit); + return (input.version.equals("") || input.version.equals("2008") + || input.version.equals("2008 R2")) && input.is64Bit; default: return false; } @@ -83,13 +83,13 @@ public class GleSYSTemplateBuilderLiveTest extends BaseTemplateBuilderLiveTest { @Test public void testDefaultTemplateBuilder() throws IOException { Template defaultTemplate = view.getComputeService().templateBuilder().build(); - assertEquals(defaultTemplate.getImage().getId(), "Ubuntu 12.04 LTS 64-bit"); + assertEquals(defaultTemplate.getImage().getId(), "Ubuntu 12.04 x64"); assertEquals(defaultTemplate.getImage().getOperatingSystem().getVersion(), "12.04"); assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), true); assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), OsFamily.UBUNTU); assertEquals(getCores(defaultTemplate.getHardware()), 1.0d); - assertEquals(defaultTemplate.getHardware().getRam(), 512); - assertEquals(defaultTemplate.getHardware().getHypervisor(), "OpenVZ"); + assertEquals(defaultTemplate.getHardware().getRam(), 768); + assertEquals(defaultTemplate.getHardware().getHypervisor(), "Xen"); assertEquals(getSpace(defaultTemplate.getHardware()), 5.0d); assertEquals(defaultTemplate.getHardware().getVolumes().get(0).getType(), Volume.Type.LOCAL); // test that we bound the correct templateoptions in guice diff --git a/labs/glesys/src/test/java/org/jclouds/glesys/compute/functions/ParseOsFamilyVersion64BitFromImageNameTest.java b/providers/glesys/src/test/java/org/jclouds/glesys/compute/functions/ParseOsFamilyVersion64BitFromImageNameTest.java similarity index 100% rename from labs/glesys/src/test/java/org/jclouds/glesys/compute/functions/ParseOsFamilyVersion64BitFromImageNameTest.java rename to providers/glesys/src/test/java/org/jclouds/glesys/compute/functions/ParseOsFamilyVersion64BitFromImageNameTest.java diff --git a/labs/glesys/src/test/java/org/jclouds/glesys/compute/functions/ServerDetailsToNodeMetadataTest.java b/providers/glesys/src/test/java/org/jclouds/glesys/compute/functions/ServerDetailsToNodeMetadataTest.java similarity index 96% rename from labs/glesys/src/test/java/org/jclouds/glesys/compute/functions/ServerDetailsToNodeMetadataTest.java rename to providers/glesys/src/test/java/org/jclouds/glesys/compute/functions/ServerDetailsToNodeMetadataTest.java index 5ca80eb8b5..771bcb22c8 100644 --- a/labs/glesys/src/test/java/org/jclouds/glesys/compute/functions/ServerDetailsToNodeMetadataTest.java +++ b/providers/glesys/src/test/java/org/jclouds/glesys/compute/functions/ServerDetailsToNodeMetadataTest.java @@ -79,9 +79,9 @@ public class ServerDetailsToNodeMetadataTest extends BaseGleSYSComputeServiceExp actual.toString(), new NodeMetadataBuilder() .ids("vz1840356") - .name("test-email-jclouds") - .hostname("test-email-jclouds") - .group("glesys-s") + .name("glesys-s") + .hostname("glesys-s") + .group("glesys") .imageId("Ubuntu 10.04 LTS 32-bit") .operatingSystem( OperatingSystem.builder().name("Ubuntu 10.04 LTS 32-bit").family(OsFamily.UBUNTU).version("10.04") diff --git a/labs/glesys/src/test/java/org/jclouds/glesys/compute/functions/ServerSpecToHardwareTest.java b/providers/glesys/src/test/java/org/jclouds/glesys/compute/functions/ServerSpecToHardwareTest.java similarity index 100% rename from labs/glesys/src/test/java/org/jclouds/glesys/compute/functions/ServerSpecToHardwareTest.java rename to providers/glesys/src/test/java/org/jclouds/glesys/compute/functions/ServerSpecToHardwareTest.java diff --git a/labs/glesys/src/test/java/org/jclouds/glesys/compute/internal/BaseGleSYSComputeServiceExpectTest.java b/providers/glesys/src/test/java/org/jclouds/glesys/compute/internal/BaseGleSYSComputeServiceExpectTest.java similarity index 100% rename from labs/glesys/src/test/java/org/jclouds/glesys/compute/internal/BaseGleSYSComputeServiceExpectTest.java rename to providers/glesys/src/test/java/org/jclouds/glesys/compute/internal/BaseGleSYSComputeServiceExpectTest.java diff --git a/labs/glesys/src/test/java/org/jclouds/glesys/compute/options/GleSYSTemplateOptionsTest.java b/providers/glesys/src/test/java/org/jclouds/glesys/compute/options/GleSYSTemplateOptionsTest.java similarity index 100% rename from labs/glesys/src/test/java/org/jclouds/glesys/compute/options/GleSYSTemplateOptionsTest.java rename to providers/glesys/src/test/java/org/jclouds/glesys/compute/options/GleSYSTemplateOptionsTest.java diff --git a/labs/glesys/src/test/java/org/jclouds/glesys/features/ArchiveApiExpectTest.java b/providers/glesys/src/test/java/org/jclouds/glesys/features/ArchiveApiExpectTest.java similarity index 91% rename from labs/glesys/src/test/java/org/jclouds/glesys/features/ArchiveApiExpectTest.java rename to providers/glesys/src/test/java/org/jclouds/glesys/features/ArchiveApiExpectTest.java index 6502cf295f..f8a300965e 100644 --- a/labs/glesys/src/test/java/org/jclouds/glesys/features/ArchiveApiExpectTest.java +++ b/providers/glesys/src/test/java/org/jclouds/glesys/features/ArchiveApiExpectTest.java @@ -22,7 +22,7 @@ import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; -import java.util.List; +import java.util.Set; import org.jclouds.glesys.domain.Archive; import org.jclouds.glesys.domain.ArchiveAllowedArguments; @@ -33,8 +33,8 @@ import org.jclouds.http.HttpResponseException; import org.jclouds.rest.ResourceNotFoundException; import org.testng.annotations.Test; -import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMultimap; +import com.google.common.collect.ImmutableSet; /** * Tests parsing of {@code ArchiveAsyncApi} @@ -52,10 +52,10 @@ public class ArchiveApiExpectTest extends BaseGleSYSApiExpectTest { HttpResponse.builder().statusCode(200).payload(payloadFromResource("/archive_list.json")).build()) .getArchiveApi(); - List expected = ImmutableList.of( + Set expected = ImmutableSet.of( Archive.builder().username("xxxxx_test1").freeSize("20 GB").totalSize("30 GB").locked(false).build()); - assertEquals(api.listArchives(), expected); + assertEquals(api.list().toImmutableSet(), expected); } public void testListArchivesWhenResponseIs4xxReturnsEmpty() { @@ -65,7 +65,7 @@ public class ArchiveApiExpectTest extends BaseGleSYSApiExpectTest { .addHeader("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build(), HttpResponse.builder().statusCode(404).build()).getArchiveApi(); - assertTrue(api.listArchives().isEmpty()); + assertTrue(api.list().isEmpty()); } public void testArchiveDetailsWhenResponseIs2xx() throws Exception { @@ -77,7 +77,7 @@ public class ArchiveApiExpectTest extends BaseGleSYSApiExpectTest { HttpResponse.builder().statusCode(200).payload(payloadFromResource("/archive_details.json")).build()) .getArchiveApi(); - assertEquals(api.getArchive("xxxxxx_test1"), detailsInArchiveDetails()); + assertEquals(api.get("xxxxxx_test1"), detailsInArchiveDetails()); } private Archive detailsInArchiveDetails() { @@ -92,7 +92,7 @@ public class ArchiveApiExpectTest extends BaseGleSYSApiExpectTest { .addFormParam("username", "xxxxxx_test1").build(), HttpResponse.builder().statusCode(404).build()) .getArchiveApi(); - assertNull(api.getArchive("xxxxxx_test1")); + assertNull(api.get("xxxxxx_test1")); } public void testCreateArchiveWhenResponseIs2xx() throws Exception { @@ -105,7 +105,7 @@ public class ArchiveApiExpectTest extends BaseGleSYSApiExpectTest { .put("size", "5") .put("password", "somepass").build()).build(), HttpResponse.builder().statusCode(200).payload(payloadFromResource("/archive_details.json")).build()).getArchiveApi(); - assertEquals(api.createArchive("xxxxxx_test1", "somepass", 5), detailsInArchiveDetails()); + assertEquals(api.createWithCredentialsAndSize("xxxxxx_test1", "somepass", 5), detailsInArchiveDetails()); } public void testDeleteArchiveWhenResponseIs2xx() throws Exception { @@ -115,7 +115,7 @@ public class ArchiveApiExpectTest extends BaseGleSYSApiExpectTest { .addFormParam("username", "xxxxxx_test1").build(), HttpResponse.builder().statusCode(200).build()).getArchiveApi(); - api.deleteArchive("xxxxxx_test1"); + api.delete("xxxxxx_test1"); } @Test(expectedExceptions = {HttpResponseException.class}) @@ -125,7 +125,7 @@ public class ArchiveApiExpectTest extends BaseGleSYSApiExpectTest { .addHeader("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==") .addFormParam("username", "xxxxxx_test1").build(), HttpResponse.builder().statusCode(402).build()).getArchiveApi(); - api.deleteArchive("xxxxxx_test1"); + api.delete("xxxxxx_test1"); } public void testResizeArchiveWhenResponseIs2xx() throws Exception { @@ -137,7 +137,7 @@ public class ArchiveApiExpectTest extends BaseGleSYSApiExpectTest { .addFormParam("size", "5").build(), HttpResponse.builder().statusCode(200).payload(payloadFromResource("/archive_details.json")).build()).getArchiveApi(); - assertEquals(api.resizeArchive("username1", 5), detailsInArchiveDetails()); + assertEquals(api.resize("username1", 5), detailsInArchiveDetails()); } @Test(expectedExceptions = {ResourceNotFoundException.class}) @@ -150,7 +150,7 @@ public class ArchiveApiExpectTest extends BaseGleSYSApiExpectTest { .addFormParam("size", "5").build(), HttpResponse.builder().statusCode(404).build()).getArchiveApi(); - api.resizeArchive("username1", 5); + api.resize("username1", 5); } public void testChangeArchivePasswordWhenResponseIs2xx() throws Exception { @@ -163,7 +163,7 @@ public class ArchiveApiExpectTest extends BaseGleSYSApiExpectTest { .addFormParam("password", "newpass").build(), HttpResponse.builder().statusCode(200).payload(payloadFromResource("/archive_details.json")).build()).getArchiveApi(); - assertEquals(api.changeArchivePassword("username", "newpass"), detailsInArchiveDetails()); + assertEquals(api.changePassword("username", "newpass"), detailsInArchiveDetails()); } @Test(expectedExceptions = {ResourceNotFoundException.class}) @@ -177,7 +177,7 @@ public class ArchiveApiExpectTest extends BaseGleSYSApiExpectTest { .addFormParam("password", "newpass").build(), HttpResponse.builder().statusCode(404).build()).getArchiveApi(); - api.changeArchivePassword("username", "newpass"); + api.changePassword("username", "newpass"); } public void testGetArchiveAllowedArgumentsWhenResponseIs2xx() throws Exception { @@ -189,7 +189,7 @@ public class ArchiveApiExpectTest extends BaseGleSYSApiExpectTest { HttpResponse.builder().statusCode(200).payload(payloadFromResource("/archive_allowed_arguments.json")).build()).getArchiveApi(); ArchiveAllowedArguments expected = ArchiveAllowedArguments.builder().archiveSizes(10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 125, 150, 175, 200, 225, 250, 275, 300, 325, 350, 375, 400, 425, 450, 475, 500, 550, 600, 650, 700, 750, 800, 850, 900, 950, 1000).build(); - assertEquals(api.getArchiveAllowedArguments(), expected); + assertEquals(api.getAllowedArguments(), expected); } public void testGetArchiveAllowedArguments4xxWhenResponseIs2xx() throws Exception { @@ -200,6 +200,6 @@ public class ArchiveApiExpectTest extends BaseGleSYSApiExpectTest { .addHeader("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build(), HttpResponse.builder().statusCode(404).build()).getArchiveApi(); - assertNull(api.getArchiveAllowedArguments()); + assertNull(api.getAllowedArguments()); } } diff --git a/labs/glesys/src/test/java/org/jclouds/glesys/features/ArchiveApiLiveTest.java b/providers/glesys/src/test/java/org/jclouds/glesys/features/ArchiveApiLiveTest.java similarity index 78% rename from labs/glesys/src/test/java/org/jclouds/glesys/features/ArchiveApiLiveTest.java rename to providers/glesys/src/test/java/org/jclouds/glesys/features/ArchiveApiLiveTest.java index fe34a30bef..d60d7852fc 100644 --- a/labs/glesys/src/test/java/org/jclouds/glesys/features/ArchiveApiLiveTest.java +++ b/providers/glesys/src/test/java/org/jclouds/glesys/features/ArchiveApiLiveTest.java @@ -29,7 +29,7 @@ import org.jclouds.glesys.domain.ArchiveAllowedArguments; import org.jclouds.glesys.internal.BaseGleSYSApiLiveTest; import org.jclouds.predicates.RetryablePredicate; import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeGroups; +import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.google.common.base.Predicate; @@ -42,7 +42,7 @@ import com.google.common.base.Predicate; @Test(groups = "live", testName = "ArchiveApiLiveTest", singleThreaded = true) public class ArchiveApiLiveTest extends BaseGleSYSApiLiveTest { - @BeforeGroups(groups = {"live"}) + @BeforeClass(groups = { "integration", "live" }) public void setupContext() { super.setupContext(); @@ -51,15 +51,15 @@ public class ArchiveApiLiveTest extends BaseGleSYSApiLiveTest { archiveCounter = new RetryablePredicate( new Predicate() { public boolean apply(Integer value){ - return api.listArchives().size() == value; + return api.list().size() == value; } }, 30, 1, TimeUnit.SECONDS); } @AfterClass(groups = { "integration", "live" }) protected void tearDownContext() { - int before = api.listArchives().size(); - api.deleteArchive(archiveUser); + int before = api.list().size(); + api.delete(archiveUser); assertTrue(archiveCounter.apply(before - 1)); super.tearDownContext(); @@ -71,12 +71,12 @@ public class ArchiveApiLiveTest extends BaseGleSYSApiLiveTest { @Test public void testAllowedArguments() throws Exception { - ArchiveAllowedArguments args = api.getArchiveAllowedArguments(); + ArchiveAllowedArguments args = api.getAllowedArguments(); assertNotNull(args); - assertNotNull(args.getArchiveSizes()); - assertTrue(args.getArchiveSizes().size() > 0); + assertNotNull(args.getSizes()); + assertTrue(args.getSizes().size() > 0); - for (int size : args.getArchiveSizes()) { + for (int size : args.getSizes()) { assertTrue(size > 0); } } @@ -84,37 +84,37 @@ public class ArchiveApiLiveTest extends BaseGleSYSApiLiveTest { @Test public void testCreateArchive() throws Exception { try { - api.deleteArchive(archiveUser); + api.delete(archiveUser); } catch(Exception ex) { } - int before = api.listArchives().size(); + int before = api.list().size(); - api.createArchive(archiveUser, "password", 10); + api.createWithCredentialsAndSize(archiveUser, "password", 10); assertTrue(archiveCounter.apply(before + 1)); } @Test(dependsOnMethods = "testCreateArchive") public void testArchiveDetails() throws Exception { - Archive details = api.getArchive(archiveUser); + Archive details = api.get(archiveUser); assertEquals(details.getUsername(), archiveUser); } @Test(dependsOnMethods = "testCreateArchive") public void testChangePassword() throws Exception { - api.changeArchivePassword(archiveUser, "newpassword"); + api.changePassword(archiveUser, "newpassword"); // TODO assert something useful! } @Test(dependsOnMethods = "testCreateArchive") public void testResizeArchive() throws Exception { - api.resizeArchive(archiveUser, 20); + api.resize(archiveUser, 20); assertTrue(new RetryablePredicate( new Predicate() { public boolean apply(String value){ - return api.getArchive(archiveUser) != null && value.equals(api.getArchive(archiveUser).getTotalSize()); + return api.get(archiveUser) != null && value.equals(api.get(archiveUser).getTotalSize()); } }, 30, 1, TimeUnit.SECONDS).apply("20 GB")); } diff --git a/labs/glesys/src/test/java/org/jclouds/glesys/features/DomainApiExpectTest.java b/providers/glesys/src/test/java/org/jclouds/glesys/features/DomainApiExpectTest.java similarity index 90% rename from labs/glesys/src/test/java/org/jclouds/glesys/features/DomainApiExpectTest.java rename to providers/glesys/src/test/java/org/jclouds/glesys/features/DomainApiExpectTest.java index 677afc82d2..93230fa95d 100644 --- a/labs/glesys/src/test/java/org/jclouds/glesys/features/DomainApiExpectTest.java +++ b/providers/glesys/src/test/java/org/jclouds/glesys/features/DomainApiExpectTest.java @@ -30,7 +30,8 @@ import org.jclouds.glesys.domain.Domain; import org.jclouds.glesys.domain.DomainRecord; import org.jclouds.glesys.internal.BaseGleSYSApiExpectTest; import org.jclouds.glesys.options.AddDomainOptions; -import org.jclouds.glesys.options.EditRecordOptions; +import org.jclouds.glesys.options.DomainOptions; +import org.jclouds.glesys.options.UpdateRecordOptions; import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpResponse; import org.jclouds.rest.ResourceNotFoundException; @@ -57,8 +58,8 @@ public class DomainApiExpectTest extends BaseGleSYSApiExpectTest { Domain expected = Domain.builder().domainName("testglesys.jclouds.org").createTime(dateService.iso8601SecondsDateParse("2012-01-31T12:19:03+01:00")).build(); - Domain actual = Iterables.getOnlyElement(api.listDomains()); - assertEquals(expected.getDomainName(), actual.getDomainName()); + Domain actual = Iterables.getOnlyElement(api.list()); + assertEquals(expected.getName(), actual.getName()); assertEquals(expected.getCreateTime(), actual.getCreateTime()); } @@ -69,7 +70,7 @@ public class DomainApiExpectTest extends BaseGleSYSApiExpectTest { .addHeader("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build(), HttpResponse.builder().statusCode(404).build()).getDomainApi(); - assertTrue(api.listDomains().isEmpty()); + assertTrue(api.list().isEmpty()); } public void testListDomainRecordsWhenResponseIs2xx() throws Exception { @@ -112,7 +113,7 @@ public class DomainApiExpectTest extends BaseGleSYSApiExpectTest { .addHeader("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build(), HttpResponse.builder().statusCode(404).build()).getDomainApi(); - assertTrue(api.listDomains().isEmpty()); + assertTrue(api.list().isEmpty()); } public void testAddDomainRecordsWhenResponseIs2xx() throws Exception { @@ -128,7 +129,7 @@ public class DomainApiExpectTest extends BaseGleSYSApiExpectTest { .payload(payloadFromResourceWithContentType("/domain_record.json", MediaType.APPLICATION_JSON)).build()) .getDomainApi(); - assertEquals(api.addRecord("jclouds.org", "jclouds.org", "A", ""), recordInDomainRecord()); + assertEquals(api.createRecord("jclouds.org", "jclouds.org", "A", ""), recordInDomainRecord()); } protected DomainRecord recordInDomainRecord() { @@ -147,10 +148,10 @@ public class DomainApiExpectTest extends BaseGleSYSApiExpectTest { .addFormParam("data", "").build(), HttpResponse.builder().statusCode(404).build()).getDomainApi(); - api.addRecord("jclouds.org", "jclouds.org", "A", ""); + api.createRecord("jclouds.org", "jclouds.org", "A", ""); } - public void testEditDomainRecordsWhenResponseIs2xx() throws Exception { + public void testUpdateDomainRecordsWhenResponseIs2xx() throws Exception { DomainApi api = requestSendsResponse( HttpRequest.builder().method("POST").endpoint("https://api.glesys.com/domain/updaterecord/format/json") .addHeader("Accept", "application/json") @@ -162,11 +163,11 @@ public class DomainApiExpectTest extends BaseGleSYSApiExpectTest { .payload(payloadFromResourceWithContentType("/domain_record.json", MediaType.APPLICATION_JSON)).build()) .getDomainApi(); - assertEquals(api.editRecord("256151", EditRecordOptions.Builder.host("somehost"), EditRecordOptions.Builder.ttl(1800)), recordInDomainRecord()); + assertEquals(api.updateRecord("256151", UpdateRecordOptions.Builder.host("somehost").ttl(1800)), recordInDomainRecord()); } @Test(expectedExceptions = ResourceNotFoundException.class) - public void testEditDomainRecordsWhenResponseIs4xx() throws Exception { + public void testUpdateDomainRecordsWhenResponseIs4xx() throws Exception { DomainApi api = requestSendsResponse( HttpRequest.builder().method("POST").endpoint("https://api.glesys.com/domain/updaterecord/format/json") .addHeader("Accept", "application/json") @@ -176,7 +177,7 @@ public class DomainApiExpectTest extends BaseGleSYSApiExpectTest { .addFormParam("ttl", "1800").build(), HttpResponse.builder().statusCode(404).build()).getDomainApi(); - api.editRecord("256151", EditRecordOptions.Builder.host("somehost"), EditRecordOptions.Builder.ttl(1800)); + api.updateRecord("256151", UpdateRecordOptions.Builder.host("somehost").ttl(1800)); } public void testDeleteDomainRecordsWhenResponseIs2xx() throws Exception { @@ -212,7 +213,7 @@ public class DomainApiExpectTest extends BaseGleSYSApiExpectTest { .payload(payloadFromResourceWithContentType("/domain_details.json", MediaType.APPLICATION_JSON)).build()) .getDomainApi(); - assertEquals(api.getDomain("cl66666_x"), domainInDomainDetails()); + assertEquals(api.get("cl66666_x"), domainInDomainDetails()); } @@ -225,7 +226,7 @@ public class DomainApiExpectTest extends BaseGleSYSApiExpectTest { HttpResponse.builder().statusCode(404).build()) .getDomainApi(); - assertNull(api.getDomain("cl66666_x")); + assertNull(api.get("cl66666_x")); } protected Domain domainInDomainDetails() { @@ -242,7 +243,7 @@ public class DomainApiExpectTest extends BaseGleSYSApiExpectTest { .payload(payloadFromResourceWithContentType("/domain_details.json", MediaType.APPLICATION_JSON)).build()) .getDomainApi(); - assertEquals(api.addDomain("cl66666_x"), domainInDomainDetails()); + assertEquals(api.create("cl66666_x"), domainInDomainDetails()); } public void testAddDomainWithOptsWhenResponseIs2xx() throws Exception { @@ -264,32 +265,34 @@ public class DomainApiExpectTest extends BaseGleSYSApiExpectTest { AddDomainOptions options = (AddDomainOptions) AddDomainOptions.Builder.primaryNameServer("ns1.somewhere.x") .expire(1).minimum(1).refresh(1).responsiblePerson("Tester").retry(1).ttl(1); - assertEquals(api.addDomain("cl66666_x", options), domainInDomainDetails()); + assertEquals(api.create("cl66666_x", options), domainInDomainDetails()); } - public void testEditDomainWhenResponseIs2xx() throws Exception { + public void testUpdateDomainWhenResponseIs2xx() throws Exception { DomainApi api = requestSendsResponse( HttpRequest.builder().method("POST").endpoint("https://api.glesys.com/domain/edit/format/json") .addHeader("Accept", "application/json") .addHeader("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==") - .addFormParam("domainname", "x").build(), + .addFormParam("domainname", "x") + .addFormParam("expire", "1").build(), HttpResponse.builder().statusCode(200) .payload(payloadFromResourceWithContentType("/domain_details.json", MediaType.APPLICATION_JSON)).build()) .getDomainApi(); - assertEquals(api.editDomain("x"), domainInDomainDetails()); + assertEquals(api.update("x", DomainOptions.Builder.expire(1)), domainInDomainDetails()); } @Test(expectedExceptions = {ResourceNotFoundException.class}) - public void testEditDomainWhenResponseIs4xxThrows() throws Exception { + public void testUpdateDomainWhenResponseIs4xxThrows() throws Exception { DomainApi api = requestSendsResponse( HttpRequest.builder().method("POST").endpoint("https://api.glesys.com/domain/edit/format/json") .addHeader("Accept", "application/json") .addHeader("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==") - .addFormParam("domainname", "x").build(), + .addFormParam("domainname", "x") + .addFormParam("expire", "1").build(), HttpResponse.builder().statusCode(404).build()).getDomainApi(); - api.editDomain("x"); + api.update("x", DomainOptions.Builder.expire(1)); } public void testDeleteDomainWhenResponseIs2xx() throws Exception { @@ -299,7 +302,7 @@ public class DomainApiExpectTest extends BaseGleSYSApiExpectTest { .addFormParam("domainname", "x").build(), HttpResponse.builder().statusCode(200).build()).getDomainApi(); - api.deleteDomain("x"); + api.delete("x"); } @Test(expectedExceptions = {ResourceNotFoundException.class}) @@ -310,6 +313,6 @@ public class DomainApiExpectTest extends BaseGleSYSApiExpectTest { .addFormParam("domainname", "x").build(), HttpResponse.builder().statusCode(404).build()).getDomainApi(); - api.deleteDomain("x"); + api.delete("x"); } } diff --git a/labs/glesys/src/test/java/org/jclouds/glesys/features/DomainApiLiveTest.java b/providers/glesys/src/test/java/org/jclouds/glesys/features/DomainApiLiveTest.java similarity index 82% rename from labs/glesys/src/test/java/org/jclouds/glesys/features/DomainApiLiveTest.java rename to providers/glesys/src/test/java/org/jclouds/glesys/features/DomainApiLiveTest.java index 61cacf3e8c..3a25d268c3 100644 --- a/labs/glesys/src/test/java/org/jclouds/glesys/features/DomainApiLiveTest.java +++ b/providers/glesys/src/test/java/org/jclouds/glesys/features/DomainApiLiveTest.java @@ -29,10 +29,10 @@ import org.jclouds.glesys.domain.Domain; import org.jclouds.glesys.domain.DomainRecord; import org.jclouds.glesys.internal.BaseGleSYSApiLiveTest; import org.jclouds.glesys.options.DomainOptions; -import org.jclouds.glesys.options.EditRecordOptions; +import org.jclouds.glesys.options.UpdateRecordOptions; import org.jclouds.predicates.RetryablePredicate; -import org.testng.annotations.AfterGroups; -import org.testng.annotations.BeforeGroups; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.google.common.base.Predicate; @@ -46,7 +46,7 @@ import com.google.common.base.Predicate; public class DomainApiLiveTest extends BaseGleSYSApiLiveTest { public String testDomain; - @BeforeGroups(groups = {"live"}) + @BeforeClass(groups = { "integration", "live" }) public void setupContext() { super.setupContext(); testDomain = identity.toLowerCase() + "-domain.jclouds.org"; @@ -54,7 +54,7 @@ public class DomainApiLiveTest extends BaseGleSYSApiLiveTest { domainCounter = new RetryablePredicate( new Predicate() { public boolean apply(Integer value) { - return api.listDomains().size() == value; + return api.list().size() == value; } }, 30, 1, TimeUnit.SECONDS); recordCounter = new RetryablePredicate( @@ -65,17 +65,17 @@ public class DomainApiLiveTest extends BaseGleSYSApiLiveTest { }, 30, 1, TimeUnit.SECONDS); try { - api.deleteDomain(testDomain); + api.delete(testDomain); } catch (Exception ex) { } createDomain(testDomain); } - @AfterGroups(groups = {"live"}) + @AfterClass(groups = { "integration", "live" }) public void tearDownContext() { - int before = api.listDomains().size(); - api.deleteDomain(testDomain); + int before = api.list().size(); + api.delete(testDomain); assertTrue(domainCounter.apply(before - 1)); super.tearDownContext(); @@ -87,16 +87,16 @@ public class DomainApiLiveTest extends BaseGleSYSApiLiveTest { @Test public void testGetDomain() throws Exception { - Domain domain = api.getDomain(testDomain); + Domain domain = api.get(testDomain); assertNotNull(domain); - assertEquals(domain.getDomainName(), testDomain); + assertEquals(domain.getName(), testDomain); assertNotNull(domain.getCreateTime()); } @Test - public void testEditDomain() throws Exception { - api.editDomain(testDomain, DomainOptions.Builder.responsiblePerson("another-tester.jclouds.org.")); - Domain domain = api.getDomain(testDomain); + public void testUpdateDomain() throws Exception { + api.update(testDomain, DomainOptions.Builder.responsiblePerson("another-tester.jclouds.org.")); + Domain domain = api.get(testDomain); assertEquals(domain.getResponsiblePerson(), "another-tester.jclouds.org."); } @@ -104,7 +104,7 @@ public class DomainApiLiveTest extends BaseGleSYSApiLiveTest { public void testCreateRecord() throws Exception { int before = api.listRecords(testDomain).size(); - api.addRecord(testDomain, "test", "A", "127.0.0.1"); + api.createRecord(testDomain, "test", "A", "127.0.0.1"); assertTrue(recordCounter.apply(before + 1)); @@ -117,10 +117,10 @@ public class DomainApiLiveTest extends BaseGleSYSApiLiveTest { } @Test - public void testEditRecord() throws Exception { + public void testUpdateRecord() throws Exception { int before = api.listRecords(testDomain).size(); - api.addRecord(testDomain, "testeditbefore", "A", "127.0.0.1"); + api.createRecord(testDomain, "testeditbefore", "A", "127.0.0.1"); assertTrue(recordCounter.apply(before + 1)); @@ -135,7 +135,7 @@ public class DomainApiLiveTest extends BaseGleSYSApiLiveTest { assertNotNull(recordId); - api.editRecord(recordId, EditRecordOptions.Builder.host("testeditafter")); + api.updateRecord(recordId, UpdateRecordOptions.Builder.host("testeditafter")); boolean found = false; for(DomainRecord record : api.listRecords(testDomain)) { diff --git a/labs/glesys/src/test/java/org/jclouds/glesys/features/EmailApiExpectTest.java b/providers/glesys/src/test/java/org/jclouds/glesys/features/EmailAccountApiExpectTest.java similarity index 80% rename from labs/glesys/src/test/java/org/jclouds/glesys/features/EmailApiExpectTest.java rename to providers/glesys/src/test/java/org/jclouds/glesys/features/EmailAccountApiExpectTest.java index 9145784cb8..30adf0dff8 100644 --- a/labs/glesys/src/test/java/org/jclouds/glesys/features/EmailApiExpectTest.java +++ b/providers/glesys/src/test/java/org/jclouds/glesys/features/EmailAccountApiExpectTest.java @@ -33,7 +33,7 @@ import org.jclouds.glesys.domain.EmailOverviewDomain; import org.jclouds.glesys.domain.EmailOverviewSummary; import org.jclouds.glesys.domain.EmailQuota; import org.jclouds.glesys.internal.BaseGleSYSApiExpectTest; -import org.jclouds.glesys.options.EditAccountOptions; +import org.jclouds.glesys.options.UpdateAccountOptions; import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpResponse; import org.jclouds.rest.AuthorizationException; @@ -44,20 +44,20 @@ import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; /** - * Tests annotation parsing of {@code EmailApi} + * Tests annotation parsing of {@code EmailAccountApi} * * @author Adam Lowe */ -@Test(groups = "unit", testName = "EmailAsyncApiTest") -public class EmailApiExpectTest extends BaseGleSYSApiExpectTest { +@Test(groups = "unit", testName = "EmailAccountAsyncApiTest") +public class EmailAccountApiExpectTest extends BaseGleSYSApiExpectTest { public void testListWhenResponseIs2xx() throws Exception { - EmailApi api = requestSendsResponse( + EmailAccountApi api = requestSendsResponse( HttpRequest.builder().method("POST").endpoint("https://api.glesys.com/email/list/format/json") .addHeader("Accept", "application/json") .addHeader("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==") .addFormParam("domainname", "cl13016.test.jclouds.org").build(), - HttpResponse.builder().statusCode(200).payload(payloadFromResource("/email_list.json")).build()).getEmailApi(); + HttpResponse.builder().statusCode(200).payload(payloadFromResource("/email_list.json")).build()).getEmailAccountApi(); EmailAccount.Builder builder = EmailAccount.builder().quota(EmailQuota.builder().max(200).unit("MB").build()).antispamLevel(3).antiVirus(true).autoRespond(false).autoRespondSaveEmail(true); Set expected = @@ -69,108 +69,108 @@ public class EmailApiExpectTest extends BaseGleSYSApiExpectTest { .modified(dateService.iso8601SecondsDateParse("2012-06-24T11:53:48+02:00")).build() ); - Set actual = api.listAccounts("cl13016.test.jclouds.org"); + Set actual = api.listDomain("cl13016.test.jclouds.org").toImmutableSet(); assertEquals(actual, expected); assertEquals(Iterables.get(actual, 0).toString(), Iterables.get(expected, 0).toString()); } public void testListWhenResponseIs404IsEmpty() throws Exception { - EmailApi api = requestSendsResponse( + EmailAccountApi api = requestSendsResponse( HttpRequest.builder().method("POST").endpoint("https://api.glesys.com/email/list/format/json") .addHeader("Accept", "application/json") .addHeader("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==") .addFormParam("domainname", "test").build(), - HttpResponse.builder().statusCode(404).build()).getEmailApi(); + HttpResponse.builder().statusCode(404).build()).getEmailAccountApi(); - assertTrue(api.listAccounts("test").isEmpty()); + assertTrue(api.listDomain("test").isEmpty()); } public void testListAliasesWhenResponseIs2xx() throws Exception { - EmailApi api = requestSendsResponse( + EmailAccountApi api = requestSendsResponse( HttpRequest.builder().method("POST").endpoint("https://api.glesys.com/email/list/format/json") .addHeader("Accept", "application/json") .addHeader("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==") .addFormParam("domainname", "cl13016.test.jclouds.org").build(), - HttpResponse.builder().statusCode(200).payload(payloadFromResource("/email_list.json")).build()).getEmailApi(); + HttpResponse.builder().statusCode(200).payload(payloadFromResource("/email_list.json")).build()).getEmailAccountApi(); EmailAlias expected = EmailAlias.builder().alias("test2@cl13016.test.jclouds.org").forwardTo("test2@cl13016.test.jclouds.org").build(); - EmailAlias actual = Iterables.getOnlyElement(api.listAliases("cl13016.test.jclouds.org")); + EmailAlias actual = Iterables.getOnlyElement(api.listAliasesInDomain("cl13016.test.jclouds.org")); assertEquals(actual, expected); } public void testListAliasesWhenResponseIs404IsEmpty() throws Exception { - EmailApi api = requestSendsResponse( + EmailAccountApi api = requestSendsResponse( HttpRequest.builder().method("POST").endpoint("https://api.glesys.com/email/list/format/json") .addHeader("Accept", "application/json") .addHeader("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==") .addFormParam("domainname", "test").build(), - HttpResponse.builder().statusCode(404).build()).getEmailApi(); + HttpResponse.builder().statusCode(404).build()).getEmailAccountApi(); - assertTrue(api.listAliases("test").isEmpty()); + assertTrue(api.listAliasesInDomain("test").isEmpty()); } public void testOverviewWhenResponseIs2xx() throws Exception { - EmailApi api = requestSendsResponse( + EmailAccountApi api = requestSendsResponse( HttpRequest.builder().method("POST").endpoint("https://api.glesys.com/email/overview/format/json") .addHeader("Accept", "application/json") .addHeader("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build(), - HttpResponse.builder().statusCode(200).payload(payloadFromResource("/email_overview.json")).build()).getEmailApi(); + HttpResponse.builder().statusCode(200).payload(payloadFromResource("/email_overview.json")).build()).getEmailAccountApi(); EmailOverviewSummary summary = EmailOverviewSummary.builder().accounts(2).maxAccounts(50).aliases(1).maxAliases(1000).build(); EmailOverviewDomain domain = EmailOverviewDomain.builder().domain("cl13016.test.jclouds.org").accounts(2).aliases(0).build(); EmailOverview expected = EmailOverview.builder().summary(summary).domains(domain).build(); - assertEquals(api.getEmailOverview(), expected); + assertEquals(api.getOverview(), expected); } public void testOverviewWhenResponseIs404ReturnsNull() throws Exception { - EmailApi api = requestSendsResponse( + EmailAccountApi api = requestSendsResponse( HttpRequest.builder().method("POST").endpoint("https://api.glesys.com/email/overview/format/json") .addHeader("Accept", "application/json") .addHeader("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build(), - HttpResponse.builder().statusCode(404).build()).getEmailApi(); + HttpResponse.builder().statusCode(404).build()).getEmailAccountApi(); - assertNull(api.getEmailOverview()); + assertNull(api.getOverview()); } public void testCreateAccountWhenResponseIs2xx() throws Exception { - EmailApi api = requestSendsResponse( + EmailAccountApi api = requestSendsResponse( HttpRequest.builder().method("POST").endpoint("https://api.glesys.com/email/createaccount/format/json") .addHeader("Accept", "application/json") .addHeader("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==") .addFormParam("emailaccount", "test@jclouds.org") .addFormParam("password", "newpass").build(), HttpResponse.builder().statusCode(200).payload(payloadFromResourceWithContentType("/email_details.json", MediaType.APPLICATION_JSON)).build()) - .getEmailApi(); + .getEmailAccountApi(); - assertEquals(api.createAccount("test@jclouds.org", "newpass").toString(), getEmailAccountInDetails().toString()); + assertEquals(api.createWithPassword("test@jclouds.org", "newpass").toString(), getEmailAccountInDetails().toString()); } - public void testEditAccountWhenResponseIs2xx() throws Exception { - EmailApi api = requestSendsResponse( + public void testUpdateAccountWhenResponseIs2xx() throws Exception { + EmailAccountApi api = requestSendsResponse( HttpRequest.builder().method("POST").endpoint("https://api.glesys.com/email/editaccount/format/json") .addHeader("Accept", "application/json") .addHeader("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==") .addFormParam("emailaccount", "test@jclouds.org") .addFormParam("password", "anotherpass").build(), HttpResponse.builder().statusCode(200).payload(payloadFromResourceWithContentType("/email_details.json", MediaType.APPLICATION_JSON)).build()) - .getEmailApi(); + .getEmailAccountApi(); - assertEquals(api.editAccount("test@jclouds.org", EditAccountOptions.Builder.password("anotherpass")).toString(), getEmailAccountInDetails().toString()); + assertEquals(api.update("test@jclouds.org", UpdateAccountOptions.Builder.password("anotherpass")).toString(), getEmailAccountInDetails().toString()); } @Test(expectedExceptions = ResourceNotFoundException.class) - public void testEditAccountWhenResponseIs4xx() throws Exception { - EmailApi api = requestSendsResponse( + public void testUpdateAccountWhenResponseIs4xx() throws Exception { + EmailAccountApi api = requestSendsResponse( HttpRequest.builder().method("POST").endpoint("https://api.glesys.com/email/editaccount/format/json") .addHeader("Accept", "application/json") .addHeader("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==") .addFormParam("emailaccount", "test@jclouds.org") .addFormParam("password", "anotherpass").build(), HttpResponse.builder().statusCode(404).build()) - .getEmailApi(); + .getEmailAccountApi(); - assertEquals(api.editAccount("test@jclouds.org", EditAccountOptions.Builder.password("anotherpass")).toString(), getEmailAccountInDetails().toString()); + assertEquals(api.update("test@jclouds.org", UpdateAccountOptions.Builder.password("anotherpass")).toString(), getEmailAccountInDetails().toString()); } private EmailAccount getEmailAccountInDetails() { @@ -184,84 +184,83 @@ public class EmailApiExpectTest extends BaseGleSYSApiExpectTest { @Test(expectedExceptions = {ResourceNotFoundException.class}) public void testCreateAccountWhenResponseIs4xxThrows() throws Exception { - EmailApi api = requestSendsResponse( + EmailAccountApi api = requestSendsResponse( HttpRequest.builder().method("POST").endpoint("https://api.glesys.com/email/createaccount/format/json") .addHeader("Accept", "application/json") .addHeader("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==") .addFormParam("emailaccount", "test@jclouds.org") .addFormParam("password", "newpass").build(), - HttpResponse.builder().statusCode(404).build()).getEmailApi(); + HttpResponse.builder().statusCode(404).build()).getEmailAccountApi(); - api.createAccount("test@jclouds.org", "newpass"); + api.createWithPassword("test@jclouds.org", "newpass"); } public void testCreateAliasWhenResponseIs2xx() throws Exception { - EmailApi api = requestSendsResponse( + EmailAccountApi api = requestSendsResponse( HttpRequest.builder().method("POST").endpoint("https://api.glesys.com/email/createalias/format/json") .addHeader("Accept", "application/json") .addHeader("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==") .addFormParam("emailalias", "test2@jclouds.org") .addFormParam("goto", "test@jclouds.org").build(), - HttpResponse.builder().statusCode(200).build()).getEmailApi(); + HttpResponse.builder().statusCode(200).build()).getEmailAccountApi(); api.createAlias("test2@jclouds.org", "test@jclouds.org"); } @Test(expectedExceptions = {AuthorizationException.class}) public void testCreateAliasWhenResponseIs4xxThrows() throws Exception { - EmailApi api = requestSendsResponse( + EmailAccountApi api = requestSendsResponse( HttpRequest.builder().method("POST").endpoint("https://api.glesys.com/email/createalias/format/json") .addHeader("Accept", "application/json") .addHeader("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==") .addFormParam("emailalias", "test2@jclouds.org") .addFormParam("goto", "test@jclouds.org").build(), - HttpResponse.builder().statusCode(401).build()).getEmailApi(); + HttpResponse.builder().statusCode(401).build()).getEmailAccountApi(); api.createAlias("test2@jclouds.org", "test@jclouds.org"); } - public void testEditAliasWhenResponseIs2xx() throws Exception { - EmailApi api = requestSendsResponse( + public void testUpdateAliasWhenResponseIs2xx() throws Exception { + EmailAccountApi api = requestSendsResponse( HttpRequest.builder().method("POST").endpoint("https://api.glesys.com/email/editalias/format/json") .addHeader("Accept", "application/json") .addHeader("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==") .addFormParam("emailalias", "test2@jclouds.org") .addFormParam("goto", "test@jclouds.org").build(), - HttpResponse.builder().statusCode(200).build()).getEmailApi(); + HttpResponse.builder().statusCode(200).build()).getEmailAccountApi(); - api.editAlias("test2@jclouds.org", "test@jclouds.org"); + api.updateAlias("test2@jclouds.org", "test@jclouds.org"); } @Test(expectedExceptions = {ResourceNotFoundException.class}) - public void testEditAliasWhenResponseIs4xxThrows() throws Exception { - EmailApi api = requestSendsResponse( + public void testUpdateAliasWhenResponseIs4xxThrows() throws Exception { + EmailAccountApi api = requestSendsResponse( HttpRequest.builder().method("POST").endpoint("https://api.glesys.com/email/editalias/format/json") .addHeader("Accept", "application/json") .addHeader("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==") .addFormParam("emailalias", "test2@jclouds.org") .addFormParam("goto", "test@jclouds.org").build(), - HttpResponse.builder().statusCode(404).build()).getEmailApi(); + HttpResponse.builder().statusCode(404).build()).getEmailAccountApi(); - api.editAlias("test2@jclouds.org", "test@jclouds.org"); + api.updateAlias("test2@jclouds.org", "test@jclouds.org"); } public void testDeleteWhenResponseIs2xx() throws Exception { - EmailApi api = requestSendsResponse( + EmailAccountApi api = requestSendsResponse( HttpRequest.builder().method("POST").endpoint("https://api.glesys.com/email/delete/format/json") .addHeader("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==") .addFormParam("email", "test2@jclouds.org").build(), - HttpResponse.builder().statusCode(200).build()).getEmailApi(); + HttpResponse.builder().statusCode(200).build()).getEmailAccountApi(); api.delete("test2@jclouds.org"); } - @Test(expectedExceptions = {ResourceNotFoundException.class}) - public void testDeleteWhenResponseIs4xxThrows() throws Exception { - EmailApi api = requestSendsResponse( + public void testDeleteWhenResponseIs4xxOk() throws Exception { + EmailAccountApi api = requestSendsResponse( HttpRequest.builder().method("POST").endpoint("https://api.glesys.com/email/delete/format/json") .addHeader("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==") .addFormParam("email", "test2@jclouds.org").build(), - HttpResponse.builder().statusCode(404).build()).getEmailApi(); + HttpResponse.builder().statusCode(404).build()).getEmailAccountApi(); api.delete("test2@jclouds.org"); } diff --git a/labs/glesys/src/test/java/org/jclouds/glesys/features/EmailApiLiveTest.java b/providers/glesys/src/test/java/org/jclouds/glesys/features/EmailAccountApiLiveTest.java similarity index 60% rename from labs/glesys/src/test/java/org/jclouds/glesys/features/EmailApiLiveTest.java rename to providers/glesys/src/test/java/org/jclouds/glesys/features/EmailAccountApiLiveTest.java index d050cab591..2fc3bbc53c 100644 --- a/labs/glesys/src/test/java/org/jclouds/glesys/features/EmailApiLiveTest.java +++ b/providers/glesys/src/test/java/org/jclouds/glesys/features/EmailAccountApiLiveTest.java @@ -23,137 +23,142 @@ import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; -import java.util.Set; import java.util.concurrent.TimeUnit; import org.jclouds.glesys.domain.EmailAccount; import org.jclouds.glesys.domain.EmailAlias; import org.jclouds.glesys.domain.EmailOverview; import org.jclouds.glesys.domain.EmailOverviewDomain; -import org.jclouds.glesys.internal.BaseGleSYSApiWithAServerLiveTest; +import org.jclouds.glesys.internal.BaseGleSYSApiLiveTest; import org.jclouds.glesys.options.CreateAccountOptions; -import org.jclouds.glesys.options.EditAccountOptions; +import org.jclouds.glesys.options.UpdateAccountOptions; import org.jclouds.predicates.RetryablePredicate; -import org.testng.annotations.AfterGroups; -import org.testng.annotations.BeforeGroups; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.google.common.base.Predicate; +import com.google.common.collect.FluentIterable; import com.google.common.collect.Iterables; /** - * Tests behavior of {@code EmailApi} - * + * Tests behavior of {@code EmailAccountApi} + * * @author Adam Lowe */ -@Test(groups = "live", testName = "EmailApiLiveTest", singleThreaded = true) -public class EmailApiLiveTest extends BaseGleSYSApiWithAServerLiveTest { +@Test(groups = "live", testName = "EmailAccountApiLiveTest", singleThreaded = true) +public class EmailAccountApiLiveTest extends BaseGleSYSApiLiveTest { + public EmailAccountApiLiveTest() { + hostName = hostName + "-email"; + } - @BeforeGroups(groups = {"live"}) - public void setupDomains() { - testDomain = identity + ".test.jclouds.org"; - api = gleContext.getApi().getEmailApi(); + @BeforeClass(groups = { "integration", "live" }) + @Override + public void setupContext() { + super.setupContext(); + testDomain = hostName + ".test.jclouds.org"; + api = gleContext.getApi().getEmailAccountApi(); + deleteAll(); createDomain(testDomain); - emailAccountCounter = new RetryablePredicate( - new Predicate() { - public boolean apply(Integer value) { - return api.listAccounts(testDomain).size() == value; - } - }, 180, 5, TimeUnit.SECONDS); + emailAccountCounter = new RetryablePredicate(new Predicate() { + public boolean apply(Integer value) { + return api.listDomain(testDomain).size() == value; + } + }, 180, 5, TimeUnit.SECONDS); assertTrue(emailAccountCounter.apply(0)); - - try { - api.delete("test2@" + testDomain); - } catch(Exception e) { - } + } - @AfterGroups(groups = {"live"}) - public void tearDownDomains() { + @AfterClass(groups = { "integration", "live" }) + @Override + public void tearDownContext() { + deleteAll(); + super.tearDownContext(); + } + + private void deleteAll() { api.delete("test@" + testDomain); api.delete("test1@" + testDomain); - assertTrue(emailAccountCounter.apply(0)); - gleContext.getApi().getDomainApi().deleteDomain(testDomain); } - private EmailApi api; + private EmailAccountApi api; private String testDomain; private RetryablePredicate emailAccountCounter; @Test public void testCreateEmail() { - api.createAccount("test@" + testDomain, "password", - CreateAccountOptions.Builder.antiVirus(true).autorespond(true).autorespondMessage("out of office")); + api.createWithPassword("test@" + testDomain, "password", CreateAccountOptions.Builder.antiVirus(true) + .autorespond(true).autorespondMessage("out of office")); assertTrue(emailAccountCounter.apply(1)); - api.createAccount("test1@" + testDomain, "password"); + api.createWithPassword("test1@" + testDomain, "password"); assertTrue(emailAccountCounter.apply(2)); } @Test(dependsOnMethods = "testCreateEmail") public void testAliases() { - assertTrue(api.listAliases(testDomain).isEmpty()); + assertTrue(api.listAliasesInDomain(testDomain).isEmpty()); EmailAlias alias = api.createAlias("test2@" + testDomain, "test@" + testDomain); assertEquals(alias.getAlias(), "test2@" + testDomain); assertEquals(alias.getForwardTo(), "test@" + testDomain); - EmailAlias aliasFromList = Iterables.getOnlyElement(api.listAliases(testDomain)); + EmailAlias aliasFromList = Iterables.getOnlyElement(api.listAliasesInDomain(testDomain)); assertEquals(aliasFromList, alias); - - EmailOverview overview = api.getEmailOverview(); + + EmailOverview overview = api.getOverview(); assertTrue(overview.getSummary().getAliases() == 1); - alias = api.editAlias("test2@" + testDomain, "test1@" + testDomain); - overview = api.getEmailOverview(); + alias = api.updateAlias("test2@" + testDomain, "test1@" + testDomain); + overview = api.getOverview(); assertTrue(overview.getSummary().getAliases() == 1); - - aliasFromList = Iterables.getOnlyElement(api.listAliases(testDomain)); + + aliasFromList = Iterables.getOnlyElement(api.listAliasesInDomain(testDomain)); assertEquals(aliasFromList, alias); api.delete("test2@" + testDomain); - overview = api.getEmailOverview(); + overview = api.getOverview(); assertTrue(overview.getSummary().getAliases() == 0); } @Test(dependsOnMethods = "testCreateEmail") public void testOverview() throws Exception { - EmailOverview overview = api.getEmailOverview(); + EmailOverview overview = api.getOverview(); assertNotNull(overview.getSummary()); assertTrue(overview.getSummary().getAccounts() > 0); assertTrue(overview.getSummary().getAliases() > -1); assertTrue(overview.getSummary().getMaxAccounts() > 0); assertTrue(overview.getSummary().getMaxAliases() > 0); - assertNotNull(overview.getDomains()); - assertFalse(overview.getDomains().isEmpty()); + assertNotNull(overview.gets()); + assertFalse(overview.gets().isEmpty()); EmailOverviewDomain domain = EmailOverviewDomain.builder().domain(testDomain).accounts(1).build(); - assertTrue(overview.getDomains().contains(domain)); + assertTrue(overview.gets().contains(domain)); } @Test(dependsOnMethods = "testCreateEmail") public void testListAccounts() throws Exception { - Set accounts = api.listAccounts(testDomain); + FluentIterable accounts = api.listDomain(testDomain); assertTrue(accounts.size() >= 1); } @Test(dependsOnMethods = "testCreateEmail") - public void testEditAccount() throws Exception { - Set accounts = api.listAccounts(testDomain); + public void testUpdateAccount() throws Exception { + FluentIterable accounts = api.listDomain(testDomain); for (EmailAccount account : accounts) { if (account.getAccount().equals("test@" + testDomain)) { assertTrue(account.isAntiVirus()); } } - api.editAccount("test@" + testDomain, EditAccountOptions.Builder.antiVirus(false)); + api.update("test@" + testDomain, UpdateAccountOptions.Builder.antiVirus(false)); - accounts = api.listAccounts(testDomain); + accounts = api.listDomain(testDomain); for (EmailAccount account : accounts) { if (account.getAccount().equals("test@" + testDomain)) { assertFalse(account.isAntiVirus()); diff --git a/labs/glesys/src/test/java/org/jclouds/glesys/features/IpApiExpectTest.java b/providers/glesys/src/test/java/org/jclouds/glesys/features/IpApiExpectTest.java similarity index 94% rename from labs/glesys/src/test/java/org/jclouds/glesys/features/IpApiExpectTest.java rename to providers/glesys/src/test/java/org/jclouds/glesys/features/IpApiExpectTest.java index e256def199..fc6a900ce4 100644 --- a/labs/glesys/src/test/java/org/jclouds/glesys/features/IpApiExpectTest.java +++ b/providers/glesys/src/test/java/org/jclouds/glesys/features/IpApiExpectTest.java @@ -18,7 +18,6 @@ */ package org.jclouds.glesys.features; -import static java.util.Collections.emptySet; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; @@ -58,7 +57,7 @@ public class IpApiExpectTest extends BaseGleSYSApiExpectTest { .nameServers("79.99.4.100", "79.99.4.101") .cost(Cost.builder().amount(2.0).currency("EUR").timePeriod("month").build()); - assertEquals(api.listIps().toString(), ImmutableSet.of( + assertEquals(api.list().toString(), ImmutableSet.of( builder.ptr("31-192-230-68-static.serverhotell.net.").address("31.192.230.68").serverId(null).build(), builder.ptr("31-192-231-148-static.serverhotell.net.").address("31.192.231.148").serverId("vz1609110").build()).toString()); } @@ -70,7 +69,7 @@ public class IpApiExpectTest extends BaseGleSYSApiExpectTest { .addHeader("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build(), HttpResponse.builder().statusCode(404).build()).getIpApi(); - assertTrue(api.listIps().isEmpty()); + assertTrue(api.list().isEmpty()); } public void testGetIpDetailsWhenResponseIs2xx() { @@ -81,7 +80,7 @@ public class IpApiExpectTest extends BaseGleSYSApiExpectTest { HttpResponse.builder().statusCode(200).payload(payloadFromResource("/ip_get_details.json")).build()) .getIpApi(); - assertEquals(api.getIp("31.192.227.113"), getIpInIpDetails()); + assertEquals(api.get("31.192.227.113"), getIpInIpDetails()); } protected IpDetails getIpInIpDetails() { @@ -100,7 +99,7 @@ public class IpApiExpectTest extends BaseGleSYSApiExpectTest { .addHeader("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build(), HttpResponse.builder().statusCode(404).build()).getIpApi(); - assertEquals(api.getIp("31.192.227.37"), null); + assertEquals(api.get("31.192.227.37"), null); } public void testTakeWhenResponseIs2xx() { @@ -159,7 +158,7 @@ public class IpApiExpectTest extends BaseGleSYSApiExpectTest { HttpResponse.builder().statusCode(200).payload(payloadFromResource("/ip_list_free.json")).build()) .getIpApi(); - assertEquals(api.listFree(4, "Falkenberg", "OpenVZ"), ParseIpAddressFromResponseTest.EXPECTED_IPS); + assertEquals(api.listFree(4, "Falkenberg", "OpenVZ").toImmutableSet(), ParseIpAddressFromResponseTest.EXPECTED_IPS); } public void testListFreeWhenResponseIs404ReturnsEmptySet() { @@ -170,7 +169,7 @@ public class IpApiExpectTest extends BaseGleSYSApiExpectTest { HttpResponse.builder().statusCode(404).build()) .getIpApi(); - assertEquals(api.listFree(6, "Falkenberg", "OpenVZ"), emptySet()); + assertEquals(api.listFree(6, "Falkenberg", "OpenVZ").toImmutableSet(), ImmutableSet.of()); } public void testAddWhenResponseIs2xx() { @@ -183,7 +182,7 @@ public class IpApiExpectTest extends BaseGleSYSApiExpectTest { HttpResponse.builder().statusCode(200).build()) .getIpApi(); - api.addIpToServer("31.192.227.37", "vz1946889"); + api.addToServer("31.192.227.37", "vz1946889"); } @Test(expectedExceptions = AuthorizationException.class) @@ -196,7 +195,7 @@ public class IpApiExpectTest extends BaseGleSYSApiExpectTest { .addFormParam("serverid", "vz1946889").build(), HttpResponse.builder().statusCode(401).build()) .getIpApi(); - api.addIpToServer("31.192.227.37", "vz1946889"); + api.addToServer("31.192.227.37", "vz1946889"); } public void testRemoveWhenResponseIs2xx() { @@ -209,7 +208,7 @@ public class IpApiExpectTest extends BaseGleSYSApiExpectTest { HttpResponse.builder().statusCode(200).build()) .getIpApi(); - api.removeIpFromServer("31.192.227.37", "vz1946889"); + api.removeFromServer("31.192.227.37", "vz1946889"); } @Test(expectedExceptions = HttpResponseException.class) @@ -223,7 +222,7 @@ public class IpApiExpectTest extends BaseGleSYSApiExpectTest { HttpResponse.builder().statusCode(400).build()) .getIpApi(); - api.removeIpFromServer("31.192.227.37", "vz1946889"); + api.removeFromServer("31.192.227.37", "vz1946889"); } public void testRemoveAndReleaseWhenResponseIs2xx() { @@ -237,7 +236,7 @@ public class IpApiExpectTest extends BaseGleSYSApiExpectTest { HttpResponse.builder().statusCode(200).build()) .getIpApi(); - api.removeIpFromServerAndRelease("31.192.227.37", "vz1946889"); + api.removeFromServerAndRelease("31.192.227.37", "vz1946889"); } @Test(expectedExceptions = HttpResponseException.class) @@ -252,7 +251,7 @@ public class IpApiExpectTest extends BaseGleSYSApiExpectTest { HttpResponse.builder().statusCode(400).build()) .getIpApi(); - api.removeIpFromServerAndRelease("31.192.227.37", "vz1946889"); + api.removeFromServerAndRelease("31.192.227.37", "vz1946889"); } public void testSetPrtWhenResponseIs2xx() { diff --git a/labs/glesys/src/test/java/org/jclouds/glesys/features/IpApiLiveTest.java b/providers/glesys/src/test/java/org/jclouds/glesys/features/IpApiLiveTest.java similarity index 73% rename from labs/glesys/src/test/java/org/jclouds/glesys/features/IpApiLiveTest.java rename to providers/glesys/src/test/java/org/jclouds/glesys/features/IpApiLiveTest.java index f07240e014..aa6c5c359c 100644 --- a/labs/glesys/src/test/java/org/jclouds/glesys/features/IpApiLiveTest.java +++ b/providers/glesys/src/test/java/org/jclouds/glesys/features/IpApiLiveTest.java @@ -29,31 +29,39 @@ import java.util.Set; import org.jclouds.glesys.domain.IpDetails; import org.jclouds.glesys.internal.BaseGleSYSApiWithAServerLiveTest; import org.jclouds.glesys.options.ListIpOptions; -import org.testng.annotations.AfterGroups; -import org.testng.annotations.BeforeMethod; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; +import com.google.common.collect.FluentIterable; import com.google.common.collect.Iterables; import com.google.common.collect.Sets; /** * Tests behavior of {@code IpApi} - * + * * @author Adrian Cole, Mattias Holmqvist */ @Test(groups = "live", testName = "IpApiLiveTest", singleThreaded = true) public class IpApiLiveTest extends BaseGleSYSApiWithAServerLiveTest { + public IpApiLiveTest() { + hostName = hostName + "-ip"; + } - @BeforeMethod - public void setupApi() { + @BeforeClass(groups = { "integration", "live" }) + @Override + public void setupContext() { + super.setupContext(); api = gleContext.getApi().getIpApi(); } - @AfterGroups(groups = {"live"}) - public void releaseIp() { + @AfterClass(groups = { "integration", "live" }) + @Override + public void tearDownContext() { if (reservedIp != null) { api.release(reservedIp.getAddress()); } + super.tearDownContext(); } private IpApi api; @@ -61,13 +69,13 @@ public class IpApiLiveTest extends BaseGleSYSApiWithAServerLiveTest { @Test public void testListFree() throws Exception { - Set freeIps = api.listFree(4, "Falkenberg", "Xen"); + FluentIterable freeIps = api.listFree(4, "Falkenberg", "Xen"); assertFalse(freeIps.isEmpty()); } @Test public void reserveIp() throws Exception { - Set openVzIps = api.listFree(4, "Falkenberg", "OpenVZ"); + FluentIterable openVzIps = api.listFree(4, "Falkenberg", "OpenVZ"); assertFalse(openVzIps.isEmpty()); reservedIp = api.take(Iterables.get(openVzIps, 0)); assertTrue(reservedIp.isReserved()); @@ -79,31 +87,31 @@ public class IpApiLiveTest extends BaseGleSYSApiWithAServerLiveTest { IpDetails details = api.release(reservedIp.getAddress()); assertEquals(details.getAddress(), reservedIp.getAddress()); assertFalse(details.isReserved()); - + // reserve an address again! reserveIp(); } @Test(dependsOnMethods = "reserveIp") public void testList() throws Exception { - Set ownIps = api.listIps(); + FluentIterable ownIps = api.list(); assertTrue(ownIps.contains(reservedIp)); - ownIps = api.listIps(ListIpOptions.Builder.datacenter(reservedIp.getDatacenter())); + ownIps = api.list(ListIpOptions.Builder.datacenter(reservedIp.getDatacenter())); assertTrue(ownIps.contains(reservedIp)); - ownIps = api.listIps(ListIpOptions.Builder.platform(reservedIp.getPlatform())); + ownIps = api.list(ListIpOptions.Builder.platform(reservedIp.getPlatform())); assertTrue(ownIps.contains(reservedIp)); - ownIps = api.listIps(ListIpOptions.Builder.ipVersion(reservedIp.getVersion())); + ownIps = api.list(ListIpOptions.Builder.ipVersion(reservedIp.getVersion())); assertTrue(ownIps.contains(reservedIp)); - ownIps = api.listIps(ListIpOptions.Builder.datacenter(reservedIp.getDatacenter()), - ListIpOptions.Builder.platform(reservedIp.getPlatform()), - ListIpOptions.Builder.ipVersion(reservedIp.getVersion())); + ownIps = api.list(ListIpOptions.Builder.datacenter(reservedIp.getDatacenter()), + ListIpOptions.Builder.platform(reservedIp.getPlatform()), + ListIpOptions.Builder.ipVersion(reservedIp.getVersion())); assertTrue(ownIps.contains(reservedIp)); - ownIps = api.listIps(ListIpOptions.Builder.serverId("xmthisisnotaserverid")); + ownIps = api.list(ListIpOptions.Builder.serverId("xmthisisnotaserverid")); assertTrue(ownIps.isEmpty()); } - + private void checkOpenVZDefailsInFalkenberg(IpDetails ipDetails) { assertEquals(ipDetails.getDatacenter(), "Falkenberg"); assertEquals(ipDetails.getPlatform(), "OpenVZ"); @@ -112,23 +120,23 @@ public class IpApiLiveTest extends BaseGleSYSApiWithAServerLiveTest { // broadcast, gateway and netmask are null for OpenVZ assertFalse(ipDetails.getNameServers().isEmpty()); } - + @Test public void testGetOpenVZDetails() throws Exception { - Set openVzIps = api.listFree(4, "Falkenberg", "OpenVZ"); + FluentIterable openVzIps = api.listFree(4, "Falkenberg", "OpenVZ"); assertFalse(openVzIps.isEmpty()); String openVzIp = openVzIps.iterator().next(); - IpDetails ipDetails = api.getIp(openVzIp); + IpDetails ipDetails = api.get(openVzIp); checkOpenVZDefailsInFalkenberg(ipDetails); assertEquals(ipDetails.getAddress(), openVzIp); } @Test public void testGetXenDetails() throws Exception { - Set xenVzIps = api.listFree(4, "Falkenberg", "Xen"); + FluentIterable xenVzIps = api.listFree(4, "Falkenberg", "Xen"); assertFalse(xenVzIps.isEmpty()); String xenIp = xenVzIps.iterator().next(); - IpDetails ipDetails = api.getIp(xenIp); + IpDetails ipDetails = api.get(xenIp); assertEquals(ipDetails.getDatacenter(), "Falkenberg"); assertEquals(ipDetails.getPlatform(), "Xen"); assertEquals(ipDetails.getVersion(), 4); @@ -145,28 +153,28 @@ public class IpApiLiveTest extends BaseGleSYSApiWithAServerLiveTest { IpDetails original = reservedIp; IpDetails modified = api.setPtr(reservedIp.getAddress(), "wibble."); - IpDetails modified2 = api.getIp(reservedIp.getAddress()); + IpDetails modified2 = api.get(reservedIp.getAddress()); assertEquals(modified.getPtr(), "wibble."); assertEquals(modified2, modified); - + reservedIp = api.resetPtr(reservedIp.getAddress()); - + assertEquals(reservedIp, original); - } + } @Test(dependsOnMethods = "reserveIp") public void testAddRemove() throws Exception { - IpDetails added = api.addIpToServer(reservedIp.getAddress(), serverId); + IpDetails added = api.addToServer(reservedIp.getAddress(), serverId); assertEquals(added.getAddress(), reservedIp.getAddress()); assertEquals(added.getPtr(), reservedIp.getPtr()); assertEquals(added.getServerId(), serverId); - - IpDetails again = api.getIp(reservedIp.getAddress()); + + IpDetails again = api.get(reservedIp.getAddress()); assertEquals(again, added); - IpDetails removed = api.removeIpFromServer(reservedIp.getAddress(), serverId); + IpDetails removed = api.removeFromServer(reservedIp.getAddress(), serverId); assertEquals(removed, added.toBuilder().serverId(null).build()); assertEquals(removed, reservedIp); @@ -174,17 +182,16 @@ public class IpApiLiveTest extends BaseGleSYSApiWithAServerLiveTest { Set openVzIps = Sets.newHashSet(api.listFree(4, "Falkenberg", "OpenVZ")); openVzIps.remove(reservedIp.getAddress()); assertFalse(openVzIps.isEmpty()); - - added = api.addIpToServer(reservedIp.getAddress(), serverId); - + + added = api.addToServer(reservedIp.getAddress(), serverId); + assertEquals(added.getServerId(), serverId); - removed = api.removeIpFromServerAndRelease(reservedIp.getAddress(), serverId); - + removed = api.removeFromServerAndRelease(reservedIp.getAddress(), serverId); + assertNull(removed.getServerId()); assertFalse(removed.isReserved()); - - + // reserve an address again! reserveIp(); } diff --git a/labs/glesys/src/test/java/org/jclouds/glesys/features/ServerApiExpectTest.java b/providers/glesys/src/test/java/org/jclouds/glesys/features/ServerApiExpectTest.java similarity index 93% rename from labs/glesys/src/test/java/org/jclouds/glesys/features/ServerApiExpectTest.java rename to providers/glesys/src/test/java/org/jclouds/glesys/features/ServerApiExpectTest.java index ac6c40ff2d..f0053efc57 100644 --- a/labs/glesys/src/test/java/org/jclouds/glesys/features/ServerApiExpectTest.java +++ b/providers/glesys/src/test/java/org/jclouds/glesys/features/ServerApiExpectTest.java @@ -45,7 +45,7 @@ import org.jclouds.glesys.internal.BaseGleSYSApiExpectTest; import org.jclouds.glesys.options.CloneServerOptions; import org.jclouds.glesys.options.CreateServerOptions; import org.jclouds.glesys.options.DestroyServerOptions; -import org.jclouds.glesys.options.EditServerOptions; +import org.jclouds.glesys.options.UpdateServerOptions; import org.jclouds.glesys.options.ServerStatusOptions; import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpResponse; @@ -72,7 +72,7 @@ public class ServerApiExpectTest extends BaseGleSYSApiExpectTest { HttpResponse.builder().statusCode(204).payload(payloadFromResource("/server_list.json")).build()).getServerApi(); Server expected = Server.builder().id("vz1541880").hostname("mammamia").datacenter("Falkenberg").platform("OpenVZ").build(); - assertEquals(api.listServers(), ImmutableSet.of(expected)); + assertEquals(api.list().toImmutableSet(), ImmutableSet.of(expected)); } public void testListServersWhenReponseIs404IsEmpty() { @@ -82,7 +82,7 @@ public class ServerApiExpectTest extends BaseGleSYSApiExpectTest { .addHeader("Authorization", "Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==").build(), HttpResponse.builder().statusCode(404).build()).getServerApi(); - assertTrue(api.listServers().isEmpty()); + assertTrue(api.list().isEmpty()); } public void testGetAllowedArgumentsWhenResponseIs2xx() throws Exception { @@ -117,7 +117,7 @@ public class ServerApiExpectTest extends BaseGleSYSApiExpectTest { .build(); expected.put("Xen", xen); expected.put("OpenVZ", openvz); - assertEquals(api.getAllowedArgumentsForCreateServerByPlatform(), expected); + assertEquals(api.getAllowedArgumentsForCreateByPlatform(), expected); } public void testGetTemplatesWhenResponseIs2xx() throws Exception { @@ -147,7 +147,7 @@ public class ServerApiExpectTest extends BaseGleSYSApiExpectTest { expectedBuilder.add(OSTemplate.builder().name(name).minDiskSize(20).minMemSize(1024).os("windows").platform("Xen").build()); } - assertEquals(api.listTemplates(), expectedBuilder.build()); + assertEquals(api.listTemplates().toImmutableSet(), expectedBuilder.build()); } public void testGetServerDetailsWhenResponseIs2xx() throws Exception { @@ -159,14 +159,14 @@ public class ServerApiExpectTest extends BaseGleSYSApiExpectTest { .addFormParam("serverid", "xm3276891").build(), HttpResponse.builder().statusCode(200).payload(payloadFromResource("/server_details.json")).build()).getServerApi(); - ServerDetails actual = api.getServerDetails("xm3276891"); + ServerDetails actual = api.get("xm3276891"); assertEquals(actual.toString(), expectedServerDetails().toString()); } public static ServerDetails expectedServerDetails() { Ip ip = Ip.builder().version4().ip("31.192.231.254").version4().cost(2.0).currency("EUR").build(); Cost cost = Cost.builder().amount(10.22).currency("EUR").timePeriod("month").build(); - return ServerDetails.builder().id("vz1840356").transferGB(50).hostname("test-email-jclouds").cpuCores(1).memorySizeMB(512) + return ServerDetails.builder().id("vz1840356").transferGB(50).hostname("glesys-s").cpuCores(1).memorySizeMB(512) .diskSizeGB(5).datacenter("Falkenberg").description("glesys-s-6dd").platform("OpenVZ") .templateName("Ubuntu 10.04 LTS 32-bit").state(Server.State.RUNNING).cost(cost).ips(ip).build(); } @@ -181,7 +181,7 @@ public class ServerApiExpectTest extends BaseGleSYSApiExpectTest { .addFormParam("serverid", "xm3276891").build(), HttpResponse.builder().statusCode(404).build()).getServerApi(); - assertNull(api.getServerDetails("xm3276891")); + assertNull(api.get("xm3276891")); } @Test @@ -206,7 +206,7 @@ public class ServerApiExpectTest extends BaseGleSYSApiExpectTest { .templateName("Ubuntu 11.04 64-bit").description("description").cpuCores(1).memorySizeMB(128).diskSizeGB(5).transferGB(50).cost(cost).build(); assertEquals( - api.createServerWithHostnameAndRootPassword( + api.createWithHostnameAndRootPassword( ServerSpec.builder().datacenter("Falkenberg").platform("OpenVZ").templateName("Ubuntu 32-bit") .diskSizeGB(5).memorySizeMB(512).cpuCores(1).transferGB(50).build(), "jclouds-test", "password").toString(), expected.toString()); @@ -233,13 +233,13 @@ public class ServerApiExpectTest extends BaseGleSYSApiExpectTest { CreateServerOptions options = CreateServerOptions.Builder.description("Description-of-server").ip("10.0.0.1"); - assertEquals(api.createServerWithHostnameAndRootPassword(ServerSpec.builder().datacenter("Falkenberg") + assertEquals(api.createWithHostnameAndRootPassword(ServerSpec.builder().datacenter("Falkenberg") .platform("OpenVZ").templateName("Ubuntu 32-bit").diskSizeGB(5).memorySizeMB(512).cpuCores(1).transferGB(50) .build(), "jclouds-test", "password", options), expectedServerDetails()); } @Test - public void testEditServerWhenResponseIs2xx() throws Exception { + public void testUpdateServerWhenResponseIs2xx() throws Exception { ServerApi api = requestSendsResponse( HttpRequest.builder().method("POST").endpoint("https://api.glesys.com/server/edit/format/json") .addHeader("Accept", "application/json") @@ -249,12 +249,11 @@ public class ServerApiExpectTest extends BaseGleSYSApiExpectTest { .addFormParam("hostname", "new-hostname").build(), HttpResponse.builder().statusCode(206).build()).getServerApi(); - api.editServer("xm3276891", EditServerOptions.Builder.description("this is a different description!"), - EditServerOptions.Builder.hostname("new-hostname")); + api.update("xm3276891", UpdateServerOptions.Builder.description("this is a different description!").hostname("new-hostname")); } @Test - public void testEditServerWithOptsWhenResponseIs2xx() throws Exception { + public void testUpdateServerWithOptsWhenResponseIs2xx() throws Exception { ServerApi api = requestSendsResponse( HttpRequest.builder().method("POST").endpoint("https://api.glesys.com/server/edit/format/json") .addHeader("Accept", "application/json") @@ -267,10 +266,10 @@ public class ServerApiExpectTest extends BaseGleSYSApiExpectTest { .addFormParam("hostname", "jclouds-test").build(), HttpResponse.builder().statusCode(200).build()).getServerApi(); - EditServerOptions options = - EditServerOptions.Builder.description("Description-of-server").diskSizeGB(1).memorySizeMB(512).cpuCores(1).hostname("jclouds-test"); + UpdateServerOptions options = + UpdateServerOptions.Builder.description("Description-of-server").diskSizeGB(1).memorySizeMB(512).cpuCores(1).hostname("jclouds-test"); - api.editServer("xm3276891", options); + api.update("xm3276891", options); } @Test @@ -283,7 +282,7 @@ public class ServerApiExpectTest extends BaseGleSYSApiExpectTest { .addFormParam("hostname", "hostname1").build(), HttpResponse.builder().statusCode(200).payload(payloadFromResource("/server_details.json")).build()).getServerApi(); - assertEquals(api.cloneServer("xm3276891", "hostname1"), expectedServerDetails()); + assertEquals(api.clone("xm3276891", "hostname1"), expectedServerDetails()); } @Test @@ -301,7 +300,7 @@ public class ServerApiExpectTest extends BaseGleSYSApiExpectTest { HttpResponse.builder().statusCode(200).payload(payloadFromResource("/server_details.json")).build()).getServerApi(); CloneServerOptions options = (CloneServerOptions) CloneServerOptions.Builder.description("Description-of-server").diskSizeGB(1).memorySizeMB(512).cpuCores(1); - assertEquals(api.cloneServer("xm3276891", "hostname1", options), expectedServerDetails()); + assertEquals(api.clone("xm3276891", "hostname1", options), expectedServerDetails()); } @Test(expectedExceptions = {ResourceNotFoundException.class}) @@ -314,7 +313,7 @@ public class ServerApiExpectTest extends BaseGleSYSApiExpectTest { .addFormParam("hostname", "hostname1").build(), HttpResponse.builder().statusCode(404).build()).getServerApi(); - api.cloneServer("xm3276891", "hostname1"); + api.clone("xm3276891", "hostname1"); } public void testGetServerStatusWhenResponseIs2xx() throws Exception { @@ -326,7 +325,7 @@ public class ServerApiExpectTest extends BaseGleSYSApiExpectTest { HttpResponse.builder().statusCode(206).payload(payloadFromResource("/server_status.json")).build()) .getServerApi(); - assertEquals(api.getServerStatus("xm3276891"), expectedServerStatus()); + assertEquals(api.getStatus("xm3276891"), expectedServerStatus()); } public void testGetServerStatusWithOptsWhenResponseIs2xx() throws Exception { @@ -339,7 +338,7 @@ public class ServerApiExpectTest extends BaseGleSYSApiExpectTest { HttpResponse.builder().statusCode(206).payload(payloadFromResource("/server_status.json")).build()) .getServerApi(); - assertEquals(api.getServerStatus("server321", ServerStatusOptions.Builder.state()), expectedServerStatus()); + assertEquals(api.getStatus("server321", ServerStatusOptions.Builder.state()), expectedServerStatus()); } public void testGetServerStatusWhenResponseIs4xx() throws Exception { @@ -352,7 +351,7 @@ public class ServerApiExpectTest extends BaseGleSYSApiExpectTest { HttpResponse.builder().statusCode(404).build()) .getServerApi(); - assertNull(api.getServerStatus("server321", ServerStatusOptions.Builder.state())); + assertNull(api.getStatus("server321", ServerStatusOptions.Builder.state())); } public void testGetServerLimitsWhenResponseIs2xx() throws Exception { @@ -364,7 +363,7 @@ public class ServerApiExpectTest extends BaseGleSYSApiExpectTest { HttpResponse.builder().statusCode(200).payload(payloadFromResource("/server_limits.json")).build()) .getServerApi(); - api.getServerLimits("server321"); + api.getLimits("server321"); } public void testGetConsoleWhenResponseIs2xx() throws Exception { @@ -402,7 +401,7 @@ public class ServerApiExpectTest extends BaseGleSYSApiExpectTest { HttpResponse.builder().statusCode(200).build()) .getServerApi(); - api.startServer("server777"); + api.start("server777"); } @Test(expectedExceptions = {AuthorizationException.class}) @@ -415,7 +414,7 @@ public class ServerApiExpectTest extends BaseGleSYSApiExpectTest { HttpResponse.builder().statusCode(401).build()) .getServerApi(); - api.startServer("server777"); + api.start("server777"); } public void testStopServerWhenResponseIs2xx() throws Exception { @@ -427,7 +426,7 @@ public class ServerApiExpectTest extends BaseGleSYSApiExpectTest { HttpResponse.builder().statusCode(200).build()) .getServerApi(); - api.stopServer("server777"); + api.stop("server777"); } public void testHardStopServerWhenResponseIs2xx() throws Exception { @@ -440,7 +439,7 @@ public class ServerApiExpectTest extends BaseGleSYSApiExpectTest { HttpResponse.builder().statusCode(200).build()) .getServerApi(); - api.hardStopServer("server777"); + api.hardStop("server777"); } @Test(expectedExceptions = {AuthorizationException.class}) @@ -453,7 +452,7 @@ public class ServerApiExpectTest extends BaseGleSYSApiExpectTest { HttpResponse.builder().statusCode(401).build()) .getServerApi(); - api.stopServer("server777"); + api.stop("server777"); } public void testRebootServerWhenResponseIs2xx() throws Exception { @@ -465,7 +464,7 @@ public class ServerApiExpectTest extends BaseGleSYSApiExpectTest { HttpResponse.builder().statusCode(200).build()) .getServerApi(); - api.rebootServer("server777"); + api.reboot("server777"); } @Test(expectedExceptions = {AuthorizationException.class}) @@ -478,7 +477,7 @@ public class ServerApiExpectTest extends BaseGleSYSApiExpectTest { HttpResponse.builder().statusCode(401).build()) .getServerApi(); - api.rebootServer("server777"); + api.reboot("server777"); } public void testDestroyServerWhenResponseIs2xx() throws Exception { @@ -490,7 +489,7 @@ public class ServerApiExpectTest extends BaseGleSYSApiExpectTest { HttpResponse.builder().statusCode(200).build()) .getServerApi(); - api.destroyServer("server777", DestroyServerOptions.Builder.keepIp()); + api.destroy("server777", DestroyServerOptions.Builder.keepIp()); } @Test(expectedExceptions = {AuthorizationException.class}) @@ -503,7 +502,7 @@ public class ServerApiExpectTest extends BaseGleSYSApiExpectTest { HttpResponse.builder().statusCode(401).build()) .getServerApi(); - api.destroyServer("server777", DestroyServerOptions.Builder.discardIp()); + api.destroy("server777", DestroyServerOptions.Builder.discardIp()); } public void testResourceUsageWhenResponseIs2xx() throws Exception { diff --git a/labs/glesys/src/test/java/org/jclouds/glesys/features/ServerApiLiveTest.java b/providers/glesys/src/test/java/org/jclouds/glesys/features/ServerApiLiveTest.java similarity index 78% rename from labs/glesys/src/test/java/org/jclouds/glesys/features/ServerApiLiveTest.java rename to providers/glesys/src/test/java/org/jclouds/glesys/features/ServerApiLiveTest.java index f555708e89..3de28e41a6 100644 --- a/labs/glesys/src/test/java/org/jclouds/glesys/features/ServerApiLiveTest.java +++ b/providers/glesys/src/test/java/org/jclouds/glesys/features/ServerApiLiveTest.java @@ -23,7 +23,6 @@ import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import java.util.Map; -import java.util.Set; import java.util.concurrent.TimeUnit; import org.jclouds.glesys.domain.AllowedArgumentsForCreateServer; @@ -38,14 +37,16 @@ import org.jclouds.glesys.domain.ServerStatus; import org.jclouds.glesys.internal.BaseGleSYSApiWithAServerLiveTest; import org.jclouds.glesys.options.CloneServerOptions; import org.jclouds.glesys.options.DestroyServerOptions; -import org.jclouds.glesys.options.EditServerOptions; import org.jclouds.glesys.options.ServerStatusOptions; +import org.jclouds.glesys.options.UpdateServerOptions; import org.jclouds.predicates.RetryablePredicate; -import org.testng.annotations.AfterGroups; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.google.common.base.Predicate; +import com.google.common.collect.FluentIterable; /** * Tests behavior of {@code ServerApi} @@ -57,16 +58,21 @@ import com.google.common.base.Predicate; public class ServerApiLiveTest extends BaseGleSYSApiWithAServerLiveTest { public static final String testHostName2 = "jclouds-test2"; - @BeforeMethod - public void setupApi() { + @BeforeClass(groups = { "integration", "live" }) + @Override + public void setupContext() { + hostName = hostName + "-server"; + super.setupContext(); api = gleContext.getApi().getServerApi(); } - @AfterGroups(groups = {"live"}) - public void deleteExtraServer() { + @AfterClass(groups = { "integration", "live" }) + @Override + public void tearDownContext() { if (testServerId2 != null) { - api.destroyServer(testServerId2, DestroyServerOptions.Builder.discardIp()); + api.destroy(testServerId2, DestroyServerOptions.Builder.discardIp()); } + super.tearDownContext(); } private ServerApi api; @@ -79,7 +85,7 @@ public class ServerApiLiveTest extends BaseGleSYSApiWithAServerLiveTest { @Test public void testAllowedArguments() throws Exception { - Map templates = api.getAllowedArgumentsForCreateServerByPlatform(); + Map templates = api.getAllowedArgumentsForCreateByPlatform(); assertTrue(templates.containsKey("OpenVZ")); assertTrue(templates.containsKey("Xen")); @@ -101,7 +107,7 @@ public class ServerApiLiveTest extends BaseGleSYSApiWithAServerLiveTest { } public void testListTemplates() throws Exception { - Set oSTemplates = api.listTemplates(); + FluentIterable oSTemplates = api.listTemplates(); for(OSTemplate oSTemplate : oSTemplates) { checkTemplate(oSTemplate); @@ -119,12 +125,12 @@ public class ServerApiLiveTest extends BaseGleSYSApiWithAServerLiveTest { } public void testListServers() throws Exception { - Set response = api.listServers(); + FluentIterable response = api.list(); assertNotNull(response); assertTrue(response.size() > 0); for (Server server : response) { - ServerDetails newDetails = api.getServerDetails(server.getId()); + ServerDetails newDetails = api.get(server.getId()); assertEquals(newDetails.getId(), server.getId()); assertEquals(newDetails.getHostname(), server.getHostname()); assertEquals(newDetails.getPlatform(), server.getPlatform()); @@ -134,7 +140,7 @@ public class ServerApiLiveTest extends BaseGleSYSApiWithAServerLiveTest { } public void testServerDetails() throws Exception { - ServerDetails details = api.getServerDetails(serverId); + ServerDetails details = api.get(serverId); checkServer(details); assertEquals("Ubuntu 10.04 LTS 32-bit", details.getTemplateName()); assertEquals("Falkenberg", details.getDatacenter()); @@ -146,22 +152,22 @@ public class ServerApiLiveTest extends BaseGleSYSApiWithAServerLiveTest { } public void testServerStatus() throws Exception { - ServerStatus newStatus = api.getServerStatus(serverId); + ServerStatus newStatus = api.getStatus(serverId); checkStatus(newStatus); } - public void testEditServer() throws Exception { - ServerDetails edited = api.editServer(serverId, EditServerOptions.Builder.description("this is a different description!")); + public void testUpdateServer() throws Exception { + ServerDetails edited = api.update(serverId, UpdateServerOptions.Builder.description("this is a different description!")); assertEquals(edited.getDescription(), "this is a different description!"); - edited = api.editServer(serverId, EditServerOptions.Builder.description("another description!"), EditServerOptions.Builder.hostname("host-name1")); + edited = api.update(serverId, UpdateServerOptions.Builder.description("another description!").hostname("host-name1")); assertEquals(edited.getDescription(), "another description!"); assertEquals(edited.getHostname(), "host-name1"); edited = api.resetPassword(serverId, "anotherpass"); assertEquals(edited.getHostname(), "host-name1"); - edited = api.editServer(serverId, EditServerOptions.Builder.hostname(hostName)); + edited = api.update(serverId, UpdateServerOptions.Builder.hostname(hostName)); assertEquals(edited.getHostname(), hostName); } @@ -169,7 +175,7 @@ public class ServerApiLiveTest extends BaseGleSYSApiWithAServerLiveTest { public void testRebootServer() throws Exception { assertTrue(serverStatusChecker.apply(Server.State.RUNNING)); - api.rebootServer(serverId); + api.reboot(serverId); assertTrue(serverStatusChecker.apply(Server.State.RUNNING)); } @@ -178,17 +184,17 @@ public class ServerApiLiveTest extends BaseGleSYSApiWithAServerLiveTest { public void testStopAndStartServer() throws Exception { assertTrue(serverStatusChecker.apply(Server.State.RUNNING)); - api.stopServer(serverId); + api.stop(serverId); assertTrue(serverStatusChecker.apply(Server.State.STOPPED)); - api.startServer(serverId); + api.start(serverId); assertTrue(serverStatusChecker.apply(Server.State.RUNNING)); } public void testServerLimits() throws Exception { - Map limits = api.getServerLimits(serverId); + Map limits = api.getLimits(serverId); assertNotNull(limits); for (Map.Entry entry : limits.entrySet()) { assertNotNull(entry.getKey()); @@ -204,14 +210,21 @@ public class ServerApiLiveTest extends BaseGleSYSApiWithAServerLiveTest { public void testResourceUsage() throws Exception { // test server has only been in existence for less than a minute - check all servers - for (Server server : api.listServers()) { - ResourceUsage usage = api.getResourceUsage(server.getId(), "diskioread", "minute"); - assertEquals(usage.getInfo().getResource(), "diskioread"); - assertEquals(usage.getInfo().getResolution(), "minute"); + for (Server server : api.list()) { + try { + ResourceUsage usage = api.getResourceUsage(server.getId(), "diskioread", "minute"); + assertEquals(usage.getInfo().getResource(), "diskioread"); + assertEquals(usage.getInfo().getResolution(), "minute"); + } catch (UnsupportedOperationException e) { - usage = api.getResourceUsage(server.getId(), "cpuusage", "minute"); - assertEquals(usage.getInfo().getResource(), "cpuusage"); - assertEquals(usage.getInfo().getResolution(), "minute"); + } + try { + ResourceUsage usage = api.getResourceUsage(server.getId(), "cpuusage", "minute"); + assertEquals(usage.getInfo().getResource(), "cpuusage"); + assertEquals(usage.getInfo().getResolution(), "minute"); + } catch (UnsupportedOperationException e) { + + } } } @@ -226,7 +239,7 @@ public class ServerApiLiveTest extends BaseGleSYSApiWithAServerLiveTest { // takes a few minutes and requires an extra server (used 1 already) @Test(enabled=false) public void testCloneServer() throws Exception { - ServerDetails testServer2 = api.cloneServer(serverId, testHostName2, CloneServerOptions.Builder.cpucores(1)); + ServerDetails testServer2 = api.clone(serverId, testHostName2, CloneServerOptions.Builder.cpucores(1)); assertNotNull(testServer2.getId()); assertEquals(testServer2.getHostname(), "jclouds-test2"); @@ -237,19 +250,19 @@ public class ServerApiLiveTest extends BaseGleSYSApiWithAServerLiveTest { RetryablePredicate cloneChecker = new ServerStatusChecker(api, testServerId2, 300, 10, TimeUnit.SECONDS); assertTrue(cloneChecker.apply(Server.State.STOPPED)); - api.startServer(testServer2.getId()); + api.start(testServer2.getId()); // TODO ServerStatus==STOPPED suggests the previous call to start should have worked cloneChecker = new RetryablePredicate( new Predicate() { public boolean apply(Server.State value) { - ServerStatus status = api.getServerStatus(testServerId2, ServerStatusOptions.Builder.state()); + ServerStatus status = api.getStatus(testServerId2, ServerStatusOptions.Builder.state()); if (status.getState() == value) { return true; } - api.startServer(testServerId2); + api.start(testServerId2); return false; } diff --git a/labs/glesys/src/test/java/org/jclouds/glesys/internal/BaseGleSYSApiExpectTest.java b/providers/glesys/src/test/java/org/jclouds/glesys/internal/BaseGleSYSApiExpectTest.java similarity index 100% rename from labs/glesys/src/test/java/org/jclouds/glesys/internal/BaseGleSYSApiExpectTest.java rename to providers/glesys/src/test/java/org/jclouds/glesys/internal/BaseGleSYSApiExpectTest.java diff --git a/labs/glesys/src/test/java/org/jclouds/glesys/internal/BaseGleSYSApiLiveTest.java b/providers/glesys/src/test/java/org/jclouds/glesys/internal/BaseGleSYSApiLiveTest.java similarity index 87% rename from labs/glesys/src/test/java/org/jclouds/glesys/internal/BaseGleSYSApiLiveTest.java rename to providers/glesys/src/test/java/org/jclouds/glesys/internal/BaseGleSYSApiLiveTest.java index 25fedade54..83f74fa4eb 100644 --- a/labs/glesys/src/test/java/org/jclouds/glesys/internal/BaseGleSYSApiLiveTest.java +++ b/providers/glesys/src/test/java/org/jclouds/glesys/internal/BaseGleSYSApiLiveTest.java @@ -23,12 +23,12 @@ import static org.testng.Assert.assertTrue; import java.util.concurrent.TimeUnit; import org.jclouds.compute.internal.BaseComputeServiceContextLiveTest; -import org.jclouds.glesys.GleSYSAsyncApi; import org.jclouds.glesys.GleSYSApi; +import org.jclouds.glesys.GleSYSAsyncApi; import org.jclouds.glesys.features.DomainApi; import org.jclouds.predicates.RetryablePredicate; import org.jclouds.rest.RestContext; -import org.testng.annotations.BeforeGroups; +import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.google.common.base.Predicate; @@ -40,6 +40,7 @@ import com.google.common.base.Predicate; */ @Test(groups = "live") public class BaseGleSYSApiLiveTest extends BaseComputeServiceContextLiveTest { + protected String hostName = System.getProperty("user.name").replace('.','-').toLowerCase(); protected RestContext gleContext; @@ -47,7 +48,7 @@ public class BaseGleSYSApiLiveTest extends BaseComputeServiceContextLiveTest { provider = "glesys"; } - @BeforeGroups(groups = { "integration", "live" }) + @BeforeClass(groups = { "integration", "live" }) @Override public void setupContext() { super.setupContext(); @@ -56,11 +57,11 @@ public class BaseGleSYSApiLiveTest extends BaseComputeServiceContextLiveTest { protected void createDomain(String domain) { final DomainApi api = gleContext.getApi().getDomainApi(); - int before = api.listDomains().size(); - api.addDomain(domain); + int before = api.list().size(); + api.create(domain); RetryablePredicate result = new RetryablePredicate(new Predicate() { public boolean apply(Integer value) { - return api.listDomains().size() == value; + return api.list().size() == value; } }, 30, 1, TimeUnit.SECONDS); diff --git a/labs/glesys/src/test/java/org/jclouds/glesys/internal/BaseGleSYSApiWithAServerLiveTest.java b/providers/glesys/src/test/java/org/jclouds/glesys/internal/BaseGleSYSApiWithAServerLiveTest.java similarity index 83% rename from labs/glesys/src/test/java/org/jclouds/glesys/internal/BaseGleSYSApiWithAServerLiveTest.java rename to providers/glesys/src/test/java/org/jclouds/glesys/internal/BaseGleSYSApiWithAServerLiveTest.java index 75366af467..a73942edc2 100644 --- a/labs/glesys/src/test/java/org/jclouds/glesys/internal/BaseGleSYSApiWithAServerLiveTest.java +++ b/providers/glesys/src/test/java/org/jclouds/glesys/internal/BaseGleSYSApiWithAServerLiveTest.java @@ -36,8 +36,8 @@ import org.jclouds.glesys.features.ServerApi; import org.jclouds.glesys.options.DestroyServerOptions; import org.jclouds.glesys.options.ServerStatusOptions; import org.jclouds.predicates.RetryablePredicate; -import org.testng.annotations.AfterGroups; -import org.testng.annotations.BeforeGroups; +import org.testng.annotations.AfterClass; +import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.google.common.base.Predicate; @@ -50,36 +50,35 @@ import com.google.common.base.Predicate; @Test(groups = "live", singleThreaded = true) public class BaseGleSYSApiWithAServerLiveTest extends BaseGleSYSApiLiveTest { protected String serverId; - protected String hostName = "test-server-jclouds"; protected ServerStatusChecker serverStatusChecker; public BaseGleSYSApiWithAServerLiveTest() { provider = "glesys"; } - @BeforeGroups(groups = { "integration", "live" }) + @BeforeClass(groups = { "integration", "live" }) @Override - public final void setupContext() { + public void setupContext() { assertNull(serverId, "This method should be called EXACTLY once per run"); super.setupContext(); serverStatusChecker = createServer(hostName); serverId = serverStatusChecker.getServerId(); } - @AfterGroups(groups = {"integration", "live"}) + @AfterClass(groups = { "integration", "live" }) @Override - public final void tearDownContext() { - gleContext.getApi().getServerApi().destroyServer(serverId, DestroyServerOptions.Builder.discardIp()); + public void tearDownContext() { + gleContext.getApi().getServerApi().destroy(serverId, DestroyServerOptions.Builder.discardIp()); super.tearDownContext(); } protected void createDomain(String domain) { final DomainApi api = gleContext.getApi().getDomainApi(); - int before = api.listDomains().size(); - api.addDomain(domain); + int before = api.list().size(); + api.create(domain); RetryablePredicate result = new RetryablePredicate(new Predicate() { public boolean apply(Integer value) { - return api.listDomains().size() == value; + return api.list().size() == value; } }, 30, 1, TimeUnit.SECONDS); @@ -89,7 +88,7 @@ public class BaseGleSYSApiWithAServerLiveTest extends BaseGleSYSApiLiveTest { protected ServerStatusChecker createServer(String hostName) { ServerApi api = gleContext.getApi().getServerApi(); - ServerDetails testServer = api.createServerWithHostnameAndRootPassword( + ServerDetails testServer = api.createWithHostnameAndRootPassword( ServerSpec.builder().datacenter("Falkenberg").platform("OpenVZ").templateName("Ubuntu 10.04 LTS 32-bit") .diskSizeGB(5).memorySizeMB(512).cpuCores(1).transferGB(50).build(), hostName, UUID.randomUUID() .toString().replace("-","")); @@ -98,7 +97,7 @@ public class BaseGleSYSApiWithAServerLiveTest extends BaseGleSYSApiLiveTest { assertEquals(testServer.getHostname(), hostName); assertFalse(testServer.getIps().isEmpty()); - ServerStatusChecker runningServerCounter = new ServerStatusChecker(api, testServer.getId(), 180, 10, + ServerStatusChecker runningServerCounter = new ServerStatusChecker(api, testServer.getId(), 300, 10, TimeUnit.SECONDS); assertTrue(runningServerCounter.apply(Server.State.RUNNING)); @@ -117,7 +116,7 @@ public class BaseGleSYSApiWithAServerLiveTest extends BaseGleSYSApiLiveTest { super(new Predicate() { public boolean apply(Server.State value) { - ServerStatus status = api.getServerStatus(serverId, ServerStatusOptions.Builder.state()); + ServerStatus status = api.getStatus(serverId, ServerStatusOptions.Builder.state()); return status.getState() == value; } diff --git a/labs/glesys/src/test/java/org/jclouds/glesys/parse/ParseFullIpDetailsTest.java b/providers/glesys/src/test/java/org/jclouds/glesys/parse/ParseFullIpDetailsTest.java similarity index 100% rename from labs/glesys/src/test/java/org/jclouds/glesys/parse/ParseFullIpDetailsTest.java rename to providers/glesys/src/test/java/org/jclouds/glesys/parse/ParseFullIpDetailsTest.java diff --git a/labs/glesys/src/test/java/org/jclouds/glesys/parse/ParseIpAddressFromResponseTest.java b/providers/glesys/src/test/java/org/jclouds/glesys/parse/ParseIpAddressFromResponseTest.java similarity index 100% rename from labs/glesys/src/test/java/org/jclouds/glesys/parse/ParseIpAddressFromResponseTest.java rename to providers/glesys/src/test/java/org/jclouds/glesys/parse/ParseIpAddressFromResponseTest.java diff --git a/labs/glesys/src/test/resources/archive_allowed_arguments.json b/providers/glesys/src/test/resources/archive_allowed_arguments.json similarity index 100% rename from labs/glesys/src/test/resources/archive_allowed_arguments.json rename to providers/glesys/src/test/resources/archive_allowed_arguments.json diff --git a/labs/glesys/src/test/resources/archive_details.json b/providers/glesys/src/test/resources/archive_details.json similarity index 100% rename from labs/glesys/src/test/resources/archive_details.json rename to providers/glesys/src/test/resources/archive_details.json diff --git a/labs/glesys/src/test/resources/archive_list.json b/providers/glesys/src/test/resources/archive_list.json similarity index 100% rename from labs/glesys/src/test/resources/archive_list.json rename to providers/glesys/src/test/resources/archive_list.json diff --git a/labs/glesys/src/test/resources/domain_details.json b/providers/glesys/src/test/resources/domain_details.json similarity index 100% rename from labs/glesys/src/test/resources/domain_details.json rename to providers/glesys/src/test/resources/domain_details.json diff --git a/labs/glesys/src/test/resources/domain_list.json b/providers/glesys/src/test/resources/domain_list.json similarity index 100% rename from labs/glesys/src/test/resources/domain_list.json rename to providers/glesys/src/test/resources/domain_list.json diff --git a/labs/glesys/src/test/resources/domain_list_records.json b/providers/glesys/src/test/resources/domain_list_records.json similarity index 100% rename from labs/glesys/src/test/resources/domain_list_records.json rename to providers/glesys/src/test/resources/domain_list_records.json diff --git a/labs/glesys/src/test/resources/domain_record.json b/providers/glesys/src/test/resources/domain_record.json similarity index 100% rename from labs/glesys/src/test/resources/domain_record.json rename to providers/glesys/src/test/resources/domain_record.json diff --git a/labs/glesys/src/test/resources/email_details.json b/providers/glesys/src/test/resources/email_details.json similarity index 100% rename from labs/glesys/src/test/resources/email_details.json rename to providers/glesys/src/test/resources/email_details.json diff --git a/labs/glesys/src/test/resources/email_list.json b/providers/glesys/src/test/resources/email_list.json similarity index 100% rename from labs/glesys/src/test/resources/email_list.json rename to providers/glesys/src/test/resources/email_list.json diff --git a/labs/glesys/src/test/resources/email_overview.json b/providers/glesys/src/test/resources/email_overview.json similarity index 100% rename from labs/glesys/src/test/resources/email_overview.json rename to providers/glesys/src/test/resources/email_overview.json diff --git a/labs/glesys/src/test/resources/ip_get_details.json b/providers/glesys/src/test/resources/ip_get_details.json similarity index 100% rename from labs/glesys/src/test/resources/ip_get_details.json rename to providers/glesys/src/test/resources/ip_get_details.json diff --git a/labs/glesys/src/test/resources/ip_get_details_xen.json b/providers/glesys/src/test/resources/ip_get_details_xen.json similarity index 100% rename from labs/glesys/src/test/resources/ip_get_details_xen.json rename to providers/glesys/src/test/resources/ip_get_details_xen.json diff --git a/labs/glesys/src/test/resources/ip_list_free.json b/providers/glesys/src/test/resources/ip_list_free.json similarity index 100% rename from labs/glesys/src/test/resources/ip_list_free.json rename to providers/glesys/src/test/resources/ip_list_free.json diff --git a/labs/glesys/src/test/resources/ip_list_own.json b/providers/glesys/src/test/resources/ip_list_own.json similarity index 100% rename from labs/glesys/src/test/resources/ip_list_own.json rename to providers/glesys/src/test/resources/ip_list_own.json diff --git a/labs/glesys/src/test/resources/ip_release.json b/providers/glesys/src/test/resources/ip_release.json similarity index 100% rename from labs/glesys/src/test/resources/ip_release.json rename to providers/glesys/src/test/resources/ip_release.json diff --git a/labs/glesys/src/test/resources/ip_take.json b/providers/glesys/src/test/resources/ip_take.json similarity index 100% rename from labs/glesys/src/test/resources/ip_take.json rename to providers/glesys/src/test/resources/ip_take.json diff --git a/labs/glesys/src/test/resources/log4j.xml b/providers/glesys/src/test/resources/log4j.xml similarity index 100% rename from labs/glesys/src/test/resources/log4j.xml rename to providers/glesys/src/test/resources/log4j.xml diff --git a/labs/glesys/src/test/resources/osmatches.json b/providers/glesys/src/test/resources/osmatches.json similarity index 100% rename from labs/glesys/src/test/resources/osmatches.json rename to providers/glesys/src/test/resources/osmatches.json diff --git a/labs/glesys/src/test/resources/server_allowed_arguments.json b/providers/glesys/src/test/resources/server_allowed_arguments.json similarity index 100% rename from labs/glesys/src/test/resources/server_allowed_arguments.json rename to providers/glesys/src/test/resources/server_allowed_arguments.json diff --git a/labs/glesys/src/test/resources/server_console.json b/providers/glesys/src/test/resources/server_console.json similarity index 100% rename from labs/glesys/src/test/resources/server_console.json rename to providers/glesys/src/test/resources/server_console.json diff --git a/labs/glesys/src/test/resources/server_details.json b/providers/glesys/src/test/resources/server_details.json similarity index 94% rename from labs/glesys/src/test/resources/server_details.json rename to providers/glesys/src/test/resources/server_details.json index 55a79c498d..e2e25c5497 100644 --- a/labs/glesys/src/test/resources/server_details.json +++ b/providers/glesys/src/test/resources/server_details.json @@ -1,7 +1,7 @@ {"response":{"status":{"code":200,"timestamp":"2012-06-21T14:10:57+02:00","text":"OK"}, "server":{ "serverid":"vz1840356", - "hostname":"test-email-jclouds", + "hostname":"glesys-s", "description":"glesys-s-6dd", "cpucores":1, "memorysize":512, diff --git a/labs/glesys/src/test/resources/server_limits.json b/providers/glesys/src/test/resources/server_limits.json similarity index 100% rename from labs/glesys/src/test/resources/server_limits.json rename to providers/glesys/src/test/resources/server_limits.json diff --git a/labs/glesys/src/test/resources/server_list.json b/providers/glesys/src/test/resources/server_list.json similarity index 100% rename from labs/glesys/src/test/resources/server_list.json rename to providers/glesys/src/test/resources/server_list.json diff --git a/labs/glesys/src/test/resources/server_noip.json b/providers/glesys/src/test/resources/server_noip.json similarity index 100% rename from labs/glesys/src/test/resources/server_noip.json rename to providers/glesys/src/test/resources/server_noip.json diff --git a/labs/glesys/src/test/resources/server_resource_usage.json b/providers/glesys/src/test/resources/server_resource_usage.json similarity index 100% rename from labs/glesys/src/test/resources/server_resource_usage.json rename to providers/glesys/src/test/resources/server_resource_usage.json diff --git a/labs/glesys/src/test/resources/server_status.json b/providers/glesys/src/test/resources/server_status.json similarity index 100% rename from labs/glesys/src/test/resources/server_status.json rename to providers/glesys/src/test/resources/server_status.json diff --git a/labs/glesys/src/test/resources/server_templates.json b/providers/glesys/src/test/resources/server_templates.json similarity index 100% rename from labs/glesys/src/test/resources/server_templates.json rename to providers/glesys/src/test/resources/server_templates.json diff --git a/providers/go2cloud-jhb1/pom.xml b/providers/go2cloud-jhb1/pom.xml index 81e9026401..45be6d4ab5 100644 --- a/providers/go2cloud-jhb1/pom.xml +++ b/providers/go2cloud-jhb1/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider diff --git a/providers/gogrid/pom.xml b/providers/gogrid/pom.xml index 97b7d7fdc9..b51f088acc 100644 --- a/providers/gogrid/pom.xml +++ b/providers/gogrid/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider diff --git a/providers/gogrid/src/test/java/org/jclouds/gogrid/options/AddServerOptionsTest.java b/providers/gogrid/src/test/java/org/jclouds/gogrid/options/AddServerOptionsTest.java index b8f01b1499..68c477fe50 100644 --- a/providers/gogrid/src/test/java/org/jclouds/gogrid/options/AddServerOptionsTest.java +++ b/providers/gogrid/src/test/java/org/jclouds/gogrid/options/AddServerOptionsTest.java @@ -22,7 +22,7 @@ import static org.jclouds.gogrid.options.AddServerOptions.Builder.asSandboxType; import static org.jclouds.gogrid.options.AddServerOptions.Builder.withDescription; import static org.testng.Assert.assertEquals; -import java.util.Collections; +import com.google.common.collect.ImmutableList; import org.jclouds.http.options.HttpRequestOptions; import org.testng.annotations.Test; @@ -46,8 +46,8 @@ public class AddServerOptionsTest { public void testWithDescription() { AddServerOptions options = new AddServerOptions(); options.withDescription("test"); - assertEquals(options.buildQueryParameters().get("description"), Collections - .singletonList("test")); + assertEquals(options.buildQueryParameters().get("description"), + ImmutableList.of("test")); } @Test(expectedExceptions = IllegalArgumentException.class) @@ -75,21 +75,21 @@ public class AddServerOptionsTest { String description = builder.toString(); options.withDescription(description); - assertEquals(options.buildQueryParameters().get("description"), Collections - .singletonList(description)); + assertEquals(options.buildQueryParameters().get("description"), + ImmutableList.of(description)); } @Test public void testNullWithDescription() { AddServerOptions options = new AddServerOptions(); - assertEquals(options.buildQueryParameters().get("description"), Collections.EMPTY_LIST); + assertEquals(options.buildQueryParameters().get("description"), ImmutableList.of()); } @Test public void testWithDescriptionStatic() { AddServerOptions options = withDescription("test"); - assertEquals(options.buildQueryParameters().get("description"), Collections - .singletonList("test")); + assertEquals(options.buildQueryParameters().get("description"), + ImmutableList.of("test")); } @Test(expectedExceptions = NullPointerException.class) @@ -101,15 +101,15 @@ public class AddServerOptionsTest { public void testAsSandboxType() { AddServerOptions options = new AddServerOptions(); options.asSandboxType(); - assertEquals(options.buildQueryParameters().get("isSandbox"), Collections - .singletonList("true")); + assertEquals(options.buildQueryParameters().get("isSandbox"), + ImmutableList.of("true")); } @Test public void testAsSandboxTypeStatic() { AddServerOptions options = asSandboxType(); - assertEquals(options.buildQueryParameters().get("isSandbox"), Collections - .singletonList("true")); + assertEquals(options.buildQueryParameters().get("isSandbox"), + ImmutableList.of("true")); } } diff --git a/providers/gogrid/src/test/java/org/jclouds/gogrid/options/SaveImageOptionsTest.java b/providers/gogrid/src/test/java/org/jclouds/gogrid/options/SaveImageOptionsTest.java index fd38ff5b7a..764b347332 100644 --- a/providers/gogrid/src/test/java/org/jclouds/gogrid/options/SaveImageOptionsTest.java +++ b/providers/gogrid/src/test/java/org/jclouds/gogrid/options/SaveImageOptionsTest.java @@ -21,7 +21,7 @@ package org.jclouds.gogrid.options; import static org.jclouds.gogrid.options.SaveImageOptions.Builder.withDescription; import static org.testng.Assert.assertEquals; -import java.util.Collections; +import com.google.common.collect.ImmutableList; import org.jclouds.http.options.HttpRequestOptions; import org.testng.annotations.Test; @@ -45,8 +45,8 @@ public class SaveImageOptionsTest { public void testWithDescription() { SaveImageOptions options = new SaveImageOptions(); options.withDescription("test"); - assertEquals(options.buildQueryParameters().get("description"), Collections - .singletonList("test")); + assertEquals(options.buildQueryParameters().get("description"), + ImmutableList.of("test")); } @Test(expectedExceptions = IllegalArgumentException.class) @@ -74,21 +74,21 @@ public class SaveImageOptionsTest { String description = builder.toString(); options.withDescription(description); - assertEquals(options.buildQueryParameters().get("description"), Collections - .singletonList(description)); + assertEquals(options.buildQueryParameters().get("description"), + ImmutableList.of(description)); } @Test public void testNullWithDescription() { SaveImageOptions options = new SaveImageOptions(); - assertEquals(options.buildQueryParameters().get("description"), Collections.EMPTY_LIST); + assertEquals(options.buildQueryParameters().get("description"), ImmutableList.of()); } @Test public void testWithDescriptionStatic() { SaveImageOptions options = withDescription("test"); - assertEquals(options.buildQueryParameters().get("description"), Collections - .singletonList("test")); + assertEquals(options.buildQueryParameters().get("description"), + ImmutableList.of("test")); } @Test(expectedExceptions = NullPointerException.class) diff --git a/providers/greenhousedata-element-vcloud/pom.xml b/providers/greenhousedata-element-vcloud/pom.xml index 640bcf0924..3db017ed9e 100644 --- a/providers/greenhousedata-element-vcloud/pom.xml +++ b/providers/greenhousedata-element-vcloud/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider diff --git a/providers/hpcloud-compute/pom.xml b/providers/hpcloud-compute/pom.xml index 6f1ee52bee..f4b26b3f16 100644 --- a/providers/hpcloud-compute/pom.xml +++ b/providers/hpcloud-compute/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider @@ -37,6 +37,11 @@ https://region-a.geo-1.identity.hpcloudsvc.com:35357/v2.0/ 1.1 + FIXME_IDENTITY FIXME_CREDENTIAL @@ -76,6 +81,13 @@ test-jar test + + org.jclouds.api + openstack-keystone + ${project.version} + test-jar + test + org.jclouds.driver jclouds-slf4j diff --git a/providers/hpcloud-compute/src/main/java/org/jclouds/hpcloud/compute/HPCloudComputeProviderMetadata.java b/providers/hpcloud-compute/src/main/java/org/jclouds/hpcloud/compute/HPCloudComputeProviderMetadata.java index 796269d83f..c7a547043e 100644 --- a/providers/hpcloud-compute/src/main/java/org/jclouds/hpcloud/compute/HPCloudComputeProviderMetadata.java +++ b/providers/hpcloud-compute/src/main/java/org/jclouds/hpcloud/compute/HPCloudComputeProviderMetadata.java @@ -31,6 +31,7 @@ import org.jclouds.hpcloud.compute.config.HPCloudComputeServiceContextModule; import org.jclouds.openstack.keystone.v2_0.config.KeystoneAuthenticationModule; import org.jclouds.openstack.keystone.v2_0.config.KeystoneAuthenticationModule.ZoneModule; import org.jclouds.openstack.nova.v2_0.NovaApiMetadata; +import org.jclouds.openstack.nova.v2_0.config.NovaParserModule; import org.jclouds.openstack.nova.v2_0.config.NovaRestClientModule; import org.jclouds.providers.ProviderMetadata; import org.jclouds.providers.internal.BaseProviderMetadata; @@ -88,6 +89,7 @@ public class HPCloudComputeProviderMetadata extends BaseProviderMetadata { .defaultModules(ImmutableSet.>builder() .add(KeystoneAuthenticationModule.class) .add(ZoneModule.class) + .add(NovaParserModule.class) .add(NovaRestClientModule.class) .add(HPCloudComputeServiceContextModule.class).build()) .build()) diff --git a/providers/hpcloud-compute/src/test/java/org/jclouds/hpcloud/compute/HPCloudComputeProviderMetadataExpectTest.java b/providers/hpcloud-compute/src/test/java/org/jclouds/hpcloud/compute/HPCloudComputeProviderMetadataExpectTest.java new file mode 100644 index 0000000000..3391e0d5f6 --- /dev/null +++ b/providers/hpcloud-compute/src/test/java/org/jclouds/hpcloud/compute/HPCloudComputeProviderMetadataExpectTest.java @@ -0,0 +1,64 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.hpcloud.compute; + +import static org.testng.Assert.assertEquals; + +import org.jclouds.http.HttpRequest; +import org.jclouds.http.HttpResponse; +import org.jclouds.openstack.nova.v2_0.NovaApi; +import org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiExpectTest; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableSet; + +/** + * This test ensures that the wiring in {@link HPCloudComputeProviderMetadata} is correct. + * + * @author Adrian Cole + */ +@Test(groups = "unit", testName = "HPCloudComputeProviderMetadataExpectTest") +public class HPCloudComputeProviderMetadataExpectTest extends BaseNovaApiExpectTest { + + public HPCloudComputeProviderMetadataExpectTest() { + this.provider = "hpcloud-compute"; + this.identity = "tenant:username"; + this.credential = "password"; + } + + public void testCanGetConfiguredZones() { + + HttpRequest authenticate = HttpRequest.builder().method("POST") + .endpoint("https://region-a.geo-1.identity.hpcloudsvc.com:35357/v2.0/tokens") + .addHeader("Accept", "application/json") + .payload(payloadFromStringWithContentType( + "{\"auth\":{\"passwordCredentials\":{\"username\":\"username\",\"password\":\"password\"},\"tenantName\":\"tenant\"}}" + , "application/json")).build(); + + + HttpResponse authenticationResponse = HttpResponse.builder().statusCode(200) + .payload(payloadFromResourceWithContentType("/access_hpcloud.json", "application/json")).build(); + + NovaApi whenNovaRegionExists = requestSendsResponse(authenticate, authenticationResponse); + + assertEquals(whenNovaRegionExists.getConfiguredZones(), ImmutableSet.of("az-3.region-a.geo-1", "az-2.region-a.geo-1", "az-1.region-a.geo-1")); + + } + +} diff --git a/providers/hpcloud-compute/src/test/resources/access_hpcloud.json b/providers/hpcloud-compute/src/test/resources/access_hpcloud.json new file mode 100644 index 0000000000..d444d93a31 --- /dev/null +++ b/providers/hpcloud-compute/src/test/resources/access_hpcloud.json @@ -0,0 +1,225 @@ +{"access": { + "token": { + "expires": "2012-09-30T12:56:12.481Z", + "id": "HPAuth_e2b86593f73366704ed4f9e4441a2467f1a67568d5363e561a72f36a96da3b4a", + "tenant": { + "id": "37936628937291", + "name": "adrian@jclouds.org" + } + }, + "user": { + "id": "54297837463082", + "name": "adrian@jclouds.org", + "roles": [ + { + "id": "00000000004016", + "serviceId": "120", + "name": "netadmin", + "tenantId": "37936628937291" + }, + { + "id": "00000000004025", + "serviceId": "120", + "name": "sysadmin", + "tenantId": "37936628937291" + }, + { + "id": "00000000004014", + "serviceId": "150", + "name": "cdn-admin", + "tenantId": "37936628937291" + }, + { + "id": "00000000004013", + "serviceId": "130", + "name": "block-admin", + "tenantId": "37936628937291" + }, + { + "id": "00000000004022", + "serviceId": "110", + "name": "Admin", + "tenantId": "37936628937291" + }, + { + "id": "00000000004016", + "serviceId": "120", + "name": "netadmin", + "tenantId": "37936628937291" + }, + { + "id": "00000000004024", + "serviceId": "140", + "name": "user", + "tenantId": "37936628937291" + }, + { + "id": "00000000004013", + "serviceId": "130", + "name": "block-admin", + "tenantId": "37936628937291" + }, + { + "id": "00000000004003", + "serviceId": "100", + "name": "domainadmin" + }, + { + "id": "00000000004025", + "serviceId": "120", + "name": "sysadmin", + "tenantId": "37936628937291" + }, + { + "id": "00000000004024", + "serviceId": "140", + "name": "user", + "tenantId": "37936628937291" + }, + { + "id": "00000000004004", + "serviceId": "100", + "name": "domainuser" + } + ] + }, + "serviceCatalog": [ + { + "name": "CDN", + "type": "hpext:cdn", + "endpoints": [{ + "tenantId": "37936628937291", + "publicURL": "https:\/\/region-a.geo-1.cdnmgmt.hpcloudsvc.com\/v1.0\/AUTH_651c939f-04f0-4fbf-bd50-27f114ccaa15", + "region": "region-a.geo-1", + "versionId": "1.0", + "versionInfo": "https:\/\/region-a.geo-1.cdnmgmt.hpcloudsvc.com\/v1.0\/", + "versionList": "https:\/\/region-a.geo-1.cdnmgmt.hpcloudsvc.com\/" + }] + }, + { + "name": "Object Storage", + "type": "object-store", + "endpoints": [{ + "tenantId": "37936628937291", + "publicURL": "https:\/\/region-a.geo-1.objects.hpcloudsvc.com\/v1.0\/AUTH_651c939f-04f0-4fbf-bd50-27f114ccaa15", + "region": "region-a.geo-1", + "versionId": "1.0", + "versionInfo": "https:\/\/region-a.geo-1.objects.hpcloudsvc.com\/v1.0\/", + "versionList": "https:\/\/region-a.geo-1.objects.hpcloudsvc.com" + }] + }, + { + "name": "Identity", + "type": "identity", + "endpoints": [ + { + "publicURL": "https:\/\/region-b.geo-1.identity.hpcloudsvc.com:35357\/v2.0\/", + "region": "region-b.geo-1", + "versionId": "2.0", + "versionInfo": "https:\/\/region-b.geo-1.identity.hpcloudsvc.com:35357\/v2.0\/", + "versionList": "https:\/\/region-b.geo-1.identity.hpcloudsvc.com:35357" + }, + { + "publicURL": "https:\/\/region-a.geo-1.identity.hpcloudsvc.com:35357\/v2.0\/", + "region": "region-a.geo-1", + "versionId": "2.0", + "versionInfo": "https:\/\/region-a.geo-1.identity.hpcloudsvc.com:35357\/v2.0\/", + "versionList": "https:\/\/region-a.geo-1.identity.hpcloudsvc.com:35357" + } + ] + }, + { + "name": "Image Management", + "type": "image", + "endpoints": [ + { + "tenantId": "37936628937291", + "publicURL": "https:\/\/glance2.uswest.hpcloud.net:9292\/v1.0", + "region": "az-2.region-a.geo-1", + "versionId": "1.0", + "versionInfo": "https:\/\/glance2.uswest.hpcloud.net:9292\/v1.0\/", + "versionList": "https:\/\/glance2.uswest.hpcloud.net:9292" + }, + { + "tenantId": "37936628937291", + "publicURL": "https:\/\/glance3.uswest.hpcloud.net:9292\/v1.0", + "region": "az-3.region-a.geo-1", + "versionId": "1.0", + "versionInfo": "https:\/\/glance3.uswest.hpcloud.net:9292\/v1.0\/", + "versionList": "https:\/\/glance3.uswest.hpcloud.net:9292" + }, + { + "tenantId": "37936628937291", + "publicURL": "https:\/\/glance1.uswest.hpcloud.net:9292\/v1.0", + "region": "az-1.region-a.geo-1", + "versionId": "1.0", + "versionInfo": "https:\/\/glance1.uswest.hpcloud.net:9292\/v1.0\/", + "versionList": "https:\/\/glance1.uswest.hpcloud.net:9292" + } + ] + }, + { + "name": "Block Storage", + "type": "volume", + "endpoints": [ + { + "tenantId": "37936628937291", + "publicURL": "https:\/\/az-1.region-a.geo-1.compute.hpcloudsvc.com\/v1.1\/37936628937291", + "region": "az-1.region-a.geo-1", + "versionId": "1.1", + "versionInfo": "https:\/\/az-1.region-a.geo-1.compute.hpcloudsvc.com\/v1.1\/", + "versionList": "https:\/\/az-1.region-a.geo-1.compute.hpcloudsvc.com" + }, + { + "tenantId": "37936628937291", + "publicURL": "https:\/\/az-3.region-a.geo-1.compute.hpcloudsvc.com\/v1.1\/37936628937291", + "region": "az-3.region-a.geo-1", + "versionId": "1.1", + "versionInfo": "https:\/\/az-3.region-a.geo-1.compute.hpcloudsvc.com\/v1.1\/", + "versionList": "https:\/\/az-3.region-a.geo-1.compute.hpcloudsvc.com" + }, + { + "tenantId": "37936628937291", + "publicURL": "https:\/\/az-2.region-a.geo-1.compute.hpcloudsvc.com\/v1.1\/37936628937291", + "region": "az-2.region-a.geo-1", + "versionId": "1.1", + "versionInfo": "https:\/\/az-2.region-a.geo-1.compute.hpcloudsvc.com\/v1.1\/", + "versionList": "https:\/\/az-2.region-a.geo-1.compute.hpcloudsvc.com" + } + ] + }, + { + "name": "Compute", + "type": "compute", + "endpoints": [ + { + "tenantId": "37936628937291", + "publicURL": "https:\/\/az-3.region-a.geo-1.compute.hpcloudsvc.com\/v1.1\/37936628937291", + "publicURL2": "https:\/\/az-3.region-a.geo-1.ec2-compute.hpcloudsvc.com\/services\/Cloud", + "region": "az-3.region-a.geo-1", + "versionId": "1.1", + "versionInfo": "https:\/\/az-3.region-a.geo-1.compute.hpcloudsvc.com\/v1.1\/", + "versionList": "https:\/\/az-3.region-a.geo-1.compute.hpcloudsvc.com" + }, + { + "tenantId": "37936628937291", + "publicURL": "https:\/\/az-2.region-a.geo-1.compute.hpcloudsvc.com\/v1.1\/37936628937291", + "publicURL2": "https:\/\/az-2.region-a.geo-1.ec2-compute.hpcloudsvc.com\/services\/Cloud", + "region": "az-2.region-a.geo-1", + "versionId": "1.1", + "versionInfo": "https:\/\/az-2.region-a.geo-1.compute.hpcloudsvc.com\/v1.1\/", + "versionList": "https:\/\/az-2.region-a.geo-1.compute.hpcloudsvc.com" + }, + { + "tenantId": "37936628937291", + "publicURL": "https:\/\/az-1.region-a.geo-1.compute.hpcloudsvc.com\/v1.1\/37936628937291", + "publicURL2": "https:\/\/az-1.region-a.geo-1.ec2-compute.hpcloudsvc.com\/services\/Cloud", + "region": "az-1.region-a.geo-1", + "versionId": "1.1", + "versionInfo": "https:\/\/az-1.region-a.geo-1.compute.hpcloudsvc.com\/v1.1\/", + "versionList": "https:\/\/az-1.region-a.geo-1.compute.hpcloudsvc.com" + } + ] + } + ] +}} diff --git a/providers/hpcloud-objectstorage/pom.xml b/providers/hpcloud-objectstorage/pom.xml index 67e11e156e..bf2f2c77b5 100644 --- a/providers/hpcloud-objectstorage/pom.xml +++ b/providers/hpcloud-objectstorage/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider @@ -37,6 +37,11 @@ https://region-a.geo-1.identity.hpcloudsvc.com:35357/v2.0/ 1.0 + FIXME_IDENTITY FIXME_CREDENTIAL diff --git a/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/HPCloudObjectStorageClient.java b/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/HPCloudObjectStorageApi.java similarity index 79% rename from providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/HPCloudObjectStorageClient.java rename to providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/HPCloudObjectStorageApi.java index 92dc16c51c..80395a11c8 100644 --- a/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/HPCloudObjectStorageClient.java +++ b/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/HPCloudObjectStorageApi.java @@ -18,15 +18,18 @@ */ package org.jclouds.hpcloud.objectstorage; +import java.util.Set; import java.util.concurrent.TimeUnit; import org.jclouds.concurrent.Timeout; -import org.jclouds.hpcloud.objectstorage.extensions.HPCloudCDNClient; +import org.jclouds.hpcloud.objectstorage.extensions.CDNContainerApi; +import org.jclouds.location.Region; import org.jclouds.openstack.swift.CommonSwiftClient; import org.jclouds.rest.annotations.Delegate; import com.google.common.base.Optional; import com.google.common.util.concurrent.ListenableFuture; +import com.google.inject.Provides; /** * Provides synchronous access to HP Cloud Object Storage via the REST API. @@ -36,17 +39,24 @@ import com.google.common.util.concurrent.ListenableFuture; * will be backend in an {@link java.util.concurrent.ExecutionException} as documented in * {@link ListenableFuture#get()}. * - * @see org.jclouds.hpcloud.objectstorage.HPCloudObjectStorageClient + * @see HPCloudObjectStorageAsyncApi * @see HP Cloud Object * Storage API * @author Jeremy Daggett */ @Timeout(duration = 120, timeUnit = TimeUnit.SECONDS) -public interface HPCloudObjectStorageClient extends CommonSwiftClient { +public interface HPCloudObjectStorageApi extends CommonSwiftClient { + /** + * + * @return the Region codes configured + */ + @Provides + @Region + Set getConfiguredRegions(); /** * Provides synchronous access to CDN features. */ @Delegate - Optional getCDNExtension(); + Optional getCDNExtension(); } diff --git a/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/HPCloudObjectStorageApiMetadata.java b/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/HPCloudObjectStorageApiMetadata.java index 522bd4c164..2387fea15e 100644 --- a/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/HPCloudObjectStorageApiMetadata.java +++ b/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/HPCloudObjectStorageApiMetadata.java @@ -18,15 +18,22 @@ */ package org.jclouds.hpcloud.objectstorage; +import static org.jclouds.rest.config.BinderUtils.bindClientAndAsyncClient; + import java.net.URI; import java.util.Properties; import org.jclouds.apis.ApiMetadata; +import org.jclouds.blobstore.BlobRequestSigner; +import org.jclouds.hpcloud.objectstorage.blobstore.HPCloudObjectStorageBlobRequestSigner; import org.jclouds.hpcloud.objectstorage.blobstore.config.HPCloudObjectStorageBlobStoreContextModule; import org.jclouds.hpcloud.objectstorage.config.HPCloudObjectStorageRestClientModule; import org.jclouds.openstack.keystone.v2_0.config.KeystoneAuthenticationModule.RegionModule; import org.jclouds.openstack.swift.SwiftKeystoneApiMetadata; +import org.jclouds.openstack.swift.blobstore.config.TemporaryUrlExtensionModule; import org.jclouds.openstack.swift.config.SwiftRestClientModule.KeystoneStorageEndpointModule; +import org.jclouds.openstack.swift.extensions.KeystoneTemporaryUrlKeyAsyncApi; +import org.jclouds.openstack.swift.extensions.TemporaryUrlKeyApi; import org.jclouds.rest.RestContext; import com.google.common.collect.ImmutableSet; @@ -34,15 +41,15 @@ import com.google.common.reflect.TypeToken; import com.google.inject.Module; /** * Implementation of {@link org.jclouds.providers.ProviderMetadata} for HP Cloud Services Object Storage - * + * * @author Jeremy Daggett */ public class HPCloudObjectStorageApiMetadata extends SwiftKeystoneApiMetadata { /** The serialVersionUID */ private static final long serialVersionUID = 820062881469203616L; - - public static final TypeToken> CONTEXT_TOKEN = new TypeToken>() { + + public static final TypeToken> CONTEXT_TOKEN = new TypeToken>() { private static final long serialVersionUID = -5070937833892503232L; }; @@ -70,7 +77,7 @@ public class HPCloudObjectStorageApiMetadata extends SwiftKeystoneApiMetadata { public static class Builder extends SwiftKeystoneApiMetadata.Builder { protected Builder(){ - super(HPCloudObjectStorageClient.class, HPCloudObjectStorageAsyncClient.class); + super(HPCloudObjectStorageApi.class, HPCloudObjectStorageAsyncApi.class); id("hpcloud-objectstorage") .endpointName("identity service url ending in /v2.0/") .defaultEndpoint("https://region-a.geo-1.identity.hpcloudsvc.com:35357/v2.0/") @@ -82,7 +89,8 @@ public class HPCloudObjectStorageApiMetadata extends SwiftKeystoneApiMetadata { .add(KeystoneStorageEndpointModule.class) .add(RegionModule.class) .add(HPCloudObjectStorageRestClientModule.class) - .add(HPCloudObjectStorageBlobStoreContextModule.class).build()); + .add(HPCloudObjectStorageBlobStoreContextModule.class) + .add(HPCloudObjectStorageTemporaryUrlExtensionModule.class).build()); } @Override @@ -96,4 +104,23 @@ public class HPCloudObjectStorageApiMetadata extends SwiftKeystoneApiMetadata { return this; } } + + /** + * Ensures keystone auth is used instead of swift auth + * + */ + public static class HPCloudObjectStorageTemporaryUrlExtensionModule extends + TemporaryUrlExtensionModule { + + @Override + protected void bindRequestSigner() { + bind(BlobRequestSigner.class).to(HPCloudObjectStorageBlobRequestSigner.class); + } + + @Override + protected void bindTemporaryUrlKeyApi() { + bindClientAndAsyncClient(binder(), TemporaryUrlKeyApi.class, KeystoneTemporaryUrlKeyAsyncApi.class); + } + + } } diff --git a/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/HPCloudObjectStorageAsyncClient.java b/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/HPCloudObjectStorageAsyncApi.java similarity index 85% rename from providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/HPCloudObjectStorageAsyncClient.java rename to providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/HPCloudObjectStorageAsyncApi.java index ae49064228..19b647516b 100644 --- a/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/HPCloudObjectStorageAsyncClient.java +++ b/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/HPCloudObjectStorageAsyncApi.java @@ -27,7 +27,8 @@ import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.core.MediaType; -import org.jclouds.hpcloud.objectstorage.extensions.HPCloudCDNAsyncClient; +import org.jclouds.hpcloud.objectstorage.extensions.CDNContainerAsyncApi; +import org.jclouds.location.Region; import org.jclouds.openstack.keystone.v2_0.filters.AuthenticateRequest; import org.jclouds.openstack.swift.CommonSwiftAsyncClient; import org.jclouds.openstack.swift.Storage; @@ -43,6 +44,7 @@ import org.jclouds.rest.annotations.SkipEncoding; import com.google.common.base.Optional; import com.google.common.util.concurrent.ListenableFuture; +import com.google.inject.Provides; /** * Provides asynchronous access to HP Cloud Object Storage via the REST API. @@ -52,7 +54,7 @@ import com.google.common.util.concurrent.ListenableFuture; * will be backend in an {@link java.util.concurrent.ExecutionException} as documented in * {@link ListenableFuture#get()}. * - * @see HPCloudObjectStorageClient + * @see HPCloudObjectStorageApi * @see HP Cloud Object * Storage API * @author Jeremy Daggett @@ -60,7 +62,14 @@ import com.google.common.util.concurrent.ListenableFuture; @SkipEncoding('/') @RequestFilters(AuthenticateRequest.class) @Endpoint(Storage.class) -public interface HPCloudObjectStorageAsyncClient extends CommonSwiftAsyncClient { +public interface HPCloudObjectStorageAsyncApi extends CommonSwiftAsyncClient { + /** + * + * @return the Region codes configured + */ + @Provides + @Region + Set getConfiguredRegions(); /** * @see org.jclouds.openstack.swift.CommonSwiftClient#listContainers @@ -80,9 +89,9 @@ public interface HPCloudObjectStorageAsyncClient extends CommonSwiftAsyncClient ListenableFuture deleteContainerIfEmpty(@PathParam("container") String container); /** - * Provides synchronous access to CDN features. + * Provides asynchronous access to CDN features. */ @Delegate - Optional getCDNExtension(); + Optional getCDNExtension(); } diff --git a/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/HPCloudObjectStorageProviderMetadata.java b/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/HPCloudObjectStorageProviderMetadata.java index 8a8262ce34..f8930000e8 100644 --- a/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/HPCloudObjectStorageProviderMetadata.java +++ b/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/HPCloudObjectStorageProviderMetadata.java @@ -18,8 +18,6 @@ */ package org.jclouds.hpcloud.objectstorage; -import static org.jclouds.openstack.keystone.v2_0.config.CredentialTypes.API_ACCESS_KEY_CREDENTIALS; -import static org.jclouds.openstack.keystone.v2_0.config.KeystoneProperties.CREDENTIAL_TYPE; import static org.jclouds.openstack.keystone.v2_0.config.KeystoneProperties.REQUIRES_TENANT; import java.net.URI; @@ -57,7 +55,6 @@ public class HPCloudObjectStorageProviderMetadata extends BaseProviderMetadata { public static Properties defaultProperties() { Properties properties = new Properties(); - properties.setProperty(CREDENTIAL_TYPE, API_ACCESS_KEY_CREDENTIALS); properties.setProperty(REQUIRES_TENANT, "true"); return properties; } diff --git a/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/blobstore/HPCloudObjectStorageAsyncBlobStore.java b/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/blobstore/HPCloudObjectStorageAsyncBlobStore.java index 847eb686ea..15f95a099b 100644 --- a/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/blobstore/HPCloudObjectStorageAsyncBlobStore.java +++ b/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/blobstore/HPCloudObjectStorageAsyncBlobStore.java @@ -35,8 +35,8 @@ import org.jclouds.blobstore.util.BlobUtils; import org.jclouds.collect.Memoized; import org.jclouds.concurrent.Futures; import org.jclouds.domain.Location; -import org.jclouds.hpcloud.objectstorage.HPCloudObjectStorageAsyncClient; -import org.jclouds.hpcloud.objectstorage.HPCloudObjectStorageClient; +import org.jclouds.hpcloud.objectstorage.HPCloudObjectStorageAsyncApi; +import org.jclouds.hpcloud.objectstorage.HPCloudObjectStorageApi; import org.jclouds.hpcloud.objectstorage.blobstore.functions.EnableCDNAndCache; import org.jclouds.openstack.swift.blobstore.SwiftAsyncBlobStore; import org.jclouds.openstack.swift.blobstore.functions.BlobStoreListContainerOptionsToListContainerOptions; @@ -57,22 +57,22 @@ import com.google.common.util.concurrent.ListenableFuture; */ @Singleton public class HPCloudObjectStorageAsyncBlobStore extends SwiftAsyncBlobStore { - private final EnableCDNAndCache enableCDNAndCache; + private final EnableCDNAndCache enableAndCache; @Inject protected HPCloudObjectStorageAsyncBlobStore(BlobStoreContext context, BlobUtils blobUtils, @Named(Constants.PROPERTY_USER_THREADS) ExecutorService service, Supplier defaultLocation, - @Memoized Supplier> locations, HPCloudObjectStorageClient sync, HPCloudObjectStorageAsyncClient async, + @Memoized Supplier> locations, HPCloudObjectStorageApi sync, HPCloudObjectStorageAsyncApi async, ContainerToResourceMetadata container2ResourceMd, BlobStoreListContainerOptionsToListContainerOptions container2ContainerListOptions, ContainerToResourceList container2ResourceList, ObjectToBlob object2Blob, BlobToObject blob2Object, ObjectToBlobMetadata object2BlobMd, BlobToHttpGetOptions blob2ObjectGetOptions, - Provider fetchBlobMetadataProvider, EnableCDNAndCache enableCDNAndCache, + Provider fetchBlobMetadataProvider, EnableCDNAndCache enableAndCache, Provider multipartUploadStrategy) { super(context, blobUtils, service, defaultLocation, locations, sync, async, container2ResourceMd, container2ContainerListOptions, container2ResourceList, object2Blob, blob2Object, object2BlobMd, blob2ObjectGetOptions, fetchBlobMetadataProvider, multipartUploadStrategy); - this.enableCDNAndCache = enableCDNAndCache; + this.enableAndCache = enableAndCache; } @Override @@ -86,7 +86,7 @@ public class HPCloudObjectStorageAsyncBlobStore extends SwiftAsyncBlobStore { @Override public Boolean apply(Boolean input) { if (Boolean.TRUE.equals(input)) { - return enableCDNAndCache.apply(container) != null; + return enableAndCache.apply(container) != null; } return false; } diff --git a/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/blobstore/HPCloudObjectStorageBlobRequestSigner.java b/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/blobstore/HPCloudObjectStorageBlobRequestSigner.java index 556ff74416..a321211caa 100644 --- a/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/blobstore/HPCloudObjectStorageBlobRequestSigner.java +++ b/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/blobstore/HPCloudObjectStorageBlobRequestSigner.java @@ -1,29 +1,76 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package org.jclouds.hpcloud.objectstorage.blobstore; +import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Predicates.instanceOf; +import static com.google.common.base.Predicates.not; +import static com.google.common.collect.Iterables.filter; import static org.jclouds.blobstore.util.BlobStoreUtils.cleanRequest; import java.lang.reflect.Method; +import java.security.InvalidKeyException; +import javax.annotation.PostConstruct; import javax.inject.Inject; import javax.inject.Singleton; +import com.google.common.base.Supplier; +import com.google.common.base.Throwables; +import com.google.inject.Provider; import org.jclouds.blobstore.BlobRequestSigner; import org.jclouds.blobstore.domain.Blob; import org.jclouds.blobstore.functions.BlobToHttpGetOptions; -import org.jclouds.hpcloud.objectstorage.HPCloudObjectStorageAsyncClient; +import org.jclouds.crypto.Crypto; +import org.jclouds.crypto.CryptoStreams; +import org.jclouds.date.TimeStamp; +import org.jclouds.hpcloud.objectstorage.HPCloudObjectStorageAsyncApi; import org.jclouds.http.HttpRequest; import org.jclouds.http.options.GetOptions; +import org.jclouds.openstack.keystone.v2_0.domain.Access; +import org.jclouds.openstack.keystone.v2_0.filters.AuthenticateRequest; +import org.jclouds.openstack.swift.TemporaryUrlKey; import org.jclouds.openstack.swift.blobstore.functions.BlobToObject; import org.jclouds.openstack.swift.domain.SwiftObject; +import org.jclouds.rest.annotations.Credential; +import org.jclouds.rest.annotations.Identity; import org.jclouds.rest.internal.RestAnnotationProcessor; /** - * @author Adrian Cole + * Signer for HP's variant of temporary signed URLs. They prefix the signature + * with the tenant id. + * + * @author Andrew Gaul */ @Singleton public class HPCloudObjectStorageBlobRequestSigner implements BlobRequestSigner { - private final RestAnnotationProcessor processor; + + private final RestAnnotationProcessor processor; + private final Crypto crypto; + + private final Provider unixEpochTimestampProvider; + private final Supplier access; + private String tenantId; + private final String accessKeyId; + private final String secretKey; + private final BlobToObject blobToObject; private final BlobToHttpGetOptions blob2HttpGetOptions; @@ -32,15 +79,34 @@ public class HPCloudObjectStorageBlobRequestSigner implements BlobRequestSigner private final Method createMethod; @Inject - public HPCloudObjectStorageBlobRequestSigner(RestAnnotationProcessor processor, BlobToObject blobToObject, - BlobToHttpGetOptions blob2HttpGetOptions) throws SecurityException, NoSuchMethodException { + public HPCloudObjectStorageBlobRequestSigner(RestAnnotationProcessor processor, BlobToObject blobToObject, + BlobToHttpGetOptions blob2HttpGetOptions, + Crypto crypto, @TimeStamp Provider unixEpochTimestampProvider, + Supplier access, + @Identity String accessKey, @Credential String secretKey) + throws SecurityException, NoSuchMethodException { this.processor = checkNotNull(processor, "processor"); + this.crypto = checkNotNull(crypto, "crypto"); + + this.unixEpochTimestampProvider = checkNotNull(unixEpochTimestampProvider, "unixEpochTimestampProvider"); + this.access = checkNotNull(access, "access"); + // accessKey is of the form tenantName:accessKeyId (not tenantId) + this.accessKeyId = accessKey.substring(accessKey.indexOf(':') + 1); + this.secretKey = secretKey; + this.blobToObject = checkNotNull(blobToObject, "blobToObject"); this.blob2HttpGetOptions = checkNotNull(blob2HttpGetOptions, "blob2HttpGetOptions"); - this.getMethod = HPCloudObjectStorageAsyncClient.class.getMethod("getObject", String.class, String.class, + + this.getMethod = HPCloudObjectStorageAsyncApi.class.getMethod("getObject", String.class, String.class, GetOptions[].class); - this.deleteMethod = HPCloudObjectStorageAsyncClient.class.getMethod("removeObject", String.class, String.class); - this.createMethod = HPCloudObjectStorageAsyncClient.class.getMethod("putObject", String.class, SwiftObject.class); + this.deleteMethod = HPCloudObjectStorageAsyncApi.class.getMethod("removeObject", String.class, String.class); + this.createMethod = HPCloudObjectStorageAsyncApi.class.getMethod("putObject", String.class, SwiftObject.class); + } + + @PostConstruct + public void populateTenantId() { + // Defer call from constructor since access.get issues an RPC. + this.tenantId = access.get().getToken().getTenant().getId(); } @Override @@ -50,7 +116,13 @@ public class HPCloudObjectStorageBlobRequestSigner implements BlobRequestSigner @Override public HttpRequest signGetBlob(String container, String name, long timeInSeconds) { - throw new UnsupportedOperationException(); + HttpRequest request = processor.createRequest(getMethod, container, name); + return cleanRequest(signForTemporaryAccess(request, timeInSeconds)); + } + + @Override + public HttpRequest signGetBlob(String container, String name, org.jclouds.blobstore.options.GetOptions options) { + return cleanRequest(processor.createRequest(getMethod, container, name, blob2HttpGetOptions.apply(options))); } @Override @@ -60,7 +132,8 @@ public class HPCloudObjectStorageBlobRequestSigner implements BlobRequestSigner @Override public HttpRequest signPutBlob(String container, Blob blob, long timeInSeconds) { - throw new UnsupportedOperationException(); + HttpRequest request = processor.createRequest(createMethod, container, blobToObject.apply(blob)); + return cleanRequest(signForTemporaryAccess(request, timeInSeconds)); } @Override @@ -68,8 +141,35 @@ public class HPCloudObjectStorageBlobRequestSigner implements BlobRequestSigner return cleanRequest(processor.createRequest(deleteMethod, container, name)); } - @Override - public HttpRequest signGetBlob(String container, String name, org.jclouds.blobstore.options.GetOptions options) { - return cleanRequest(processor.createRequest(getMethod, container, name, blob2HttpGetOptions.apply(options))); + private HttpRequest signForTemporaryAccess(HttpRequest request, long timeInSeconds) { + HttpRequest.Builder builder = request.toBuilder(); + // HP Cloud does not use X-Auth-Token for temporary signed URLs and + // leaking this allows clients arbitrary privileges until token timeout. + builder.filters(filter(request.getFilters(), not(instanceOf(AuthenticateRequest.class)))); + + long expiresInSeconds = unixEpochTimestampProvider.get() + timeInSeconds; + String signature = createSignature(secretKey, createStringToSign( + request.getMethod().toUpperCase(), request, expiresInSeconds)); + + builder.addQueryParam("temp_url_sig", + String.format("%s:%s:%s", tenantId, accessKeyId, signature)); + builder.addQueryParam("temp_url_expires", "" + expiresInSeconds); + + return builder.build(); + } + + private String createStringToSign(String method, HttpRequest request, long expiresInSeconds) { + checkArgument(method.equalsIgnoreCase("GET") || method.equalsIgnoreCase("PUT")); + return String.format("%s\n%d\n%s", method.toUpperCase(), expiresInSeconds, + request.getEndpoint().getPath()); + } + + private String createSignature(String key, String stringToSign) { + try { + return CryptoStreams.hex(crypto.hmacSHA1(key.getBytes()).doFinal(stringToSign.getBytes())); + + } catch (InvalidKeyException e) { + throw Throwables.propagate(e); + } } } diff --git a/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/blobstore/HPCloudObjectStorageBlobStore.java b/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/blobstore/HPCloudObjectStorageBlobStore.java index 365cb294d0..eeb058c439 100644 --- a/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/blobstore/HPCloudObjectStorageBlobStore.java +++ b/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/blobstore/HPCloudObjectStorageBlobStore.java @@ -31,7 +31,7 @@ import org.jclouds.blobstore.strategy.internal.FetchBlobMetadata; import org.jclouds.blobstore.util.BlobUtils; import org.jclouds.collect.Memoized; import org.jclouds.domain.Location; -import org.jclouds.hpcloud.objectstorage.HPCloudObjectStorageClient; +import org.jclouds.hpcloud.objectstorage.HPCloudObjectStorageApi; import org.jclouds.hpcloud.objectstorage.blobstore.functions.EnableCDNAndCache; import org.jclouds.openstack.swift.blobstore.SwiftBlobStore; import org.jclouds.openstack.swift.blobstore.functions.BlobStoreListContainerOptionsToListContainerOptions; @@ -51,21 +51,21 @@ import com.google.common.base.Supplier; @Singleton public class HPCloudObjectStorageBlobStore extends SwiftBlobStore { - private EnableCDNAndCache enableCDNAndCache; + private EnableCDNAndCache enableAndCache; @Inject protected HPCloudObjectStorageBlobStore(BlobStoreContext context, BlobUtils blobUtils, Supplier defaultLocation, @Memoized Supplier> locations, - HPCloudObjectStorageClient sync, ContainerToResourceMetadata container2ResourceMd, + HPCloudObjectStorageApi sync, ContainerToResourceMetadata container2ResourceMd, BlobStoreListContainerOptionsToListContainerOptions container2ContainerListOptions, ContainerToResourceList container2ResourceList, ObjectToBlob object2Blob, BlobToObject blob2Object, ObjectToBlobMetadata object2BlobMd, BlobToHttpGetOptions blob2ObjectGetOptions, - Provider fetchBlobMetadataProvider, EnableCDNAndCache enableCDNAndCache, + Provider fetchBlobMetadataProvider, EnableCDNAndCache enableAndCache, Provider multipartUploadStrategy) { super(context, blobUtils, defaultLocation, locations, sync, container2ResourceMd, container2ContainerListOptions, container2ResourceList, object2Blob, blob2Object, object2BlobMd, blob2ObjectGetOptions, fetchBlobMetadataProvider, multipartUploadStrategy); - this.enableCDNAndCache = enableCDNAndCache; + this.enableAndCache = enableAndCache; } @@ -75,7 +75,7 @@ public class HPCloudObjectStorageBlobStore extends SwiftBlobStore { return createContainerInLocation(location, container); } finally { if (options.isPublicRead()) - enableCDNAndCache.apply(container); + enableAndCache.apply(container); } } diff --git a/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/blobstore/config/HPCloudObjectStorageBlobStoreContextModule.java b/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/blobstore/config/HPCloudObjectStorageBlobStoreContextModule.java index bfc73bd50e..716d305bf6 100644 --- a/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/blobstore/config/HPCloudObjectStorageBlobStoreContextModule.java +++ b/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/blobstore/config/HPCloudObjectStorageBlobStoreContextModule.java @@ -29,17 +29,15 @@ import javax.inject.Inject; import javax.inject.Singleton; import org.jclouds.blobstore.AsyncBlobStore; -import org.jclouds.blobstore.BlobRequestSigner; import org.jclouds.blobstore.BlobStore; import org.jclouds.blobstore.attr.ConsistencyModel; import org.jclouds.blobstore.config.BlobStoreMapModule; -import org.jclouds.hpcloud.objectstorage.HPCloudObjectStorageClient; +import org.jclouds.hpcloud.objectstorage.HPCloudObjectStorageApi; import org.jclouds.hpcloud.objectstorage.blobstore.HPCloudObjectStorageAsyncBlobStore; -import org.jclouds.hpcloud.objectstorage.blobstore.HPCloudObjectStorageBlobRequestSigner; import org.jclouds.hpcloud.objectstorage.blobstore.HPCloudObjectStorageBlobStore; import org.jclouds.hpcloud.objectstorage.blobstore.functions.HPCloudObjectStorageObjectToBlobMetadata; -import org.jclouds.hpcloud.objectstorage.domain.ContainerCDNMetadata; -import org.jclouds.hpcloud.objectstorage.extensions.HPCloudCDNClient; +import org.jclouds.hpcloud.objectstorage.domain.CDNContainer; +import org.jclouds.hpcloud.objectstorage.extensions.CDNContainerApi; import org.jclouds.http.HttpResponseException; import org.jclouds.logging.Logger; import org.jclouds.openstack.swift.blobstore.config.SwiftBlobStoreContextModule; @@ -53,30 +51,30 @@ import com.google.common.cache.LoadingCache; import com.google.inject.Provides; /** - * + * * @author Adrian Cole */ public class HPCloudObjectStorageBlobStoreContextModule extends SwiftBlobStoreContextModule { - @Beta - @Singleton - public static final class GetCDNMetadata extends CacheLoader { - @Resource - protected Logger logger = Logger.NULL; + @Beta + @Singleton + public static final class GetCDNMetadata extends CacheLoader { + @Resource + protected Logger logger = Logger.NULL; - private final HPCloudObjectStorageClient client; + private final HPCloudObjectStorageApi client; @Inject - public GetCDNMetadata(HPCloudObjectStorageClient client) { + public GetCDNMetadata(HPCloudObjectStorageApi client) { this.client = client; } @Override public URI load(String container) { - Optional cdnExtension = client.getCDNExtension(); + Optional cdnExtension = client.getCDNExtension(); checkArgument(cdnExtension.isPresent(), "CDN is required, but the extension is not available!"); try { - ContainerCDNMetadata md = cdnExtension.get().getCDNMetadata(container); + CDNContainer md = cdnExtension.get().get(container); return md != null ? md.getCDNUri() : null; } catch (HttpResponseException e) { // TODO: this is due to beta status @@ -90,7 +88,7 @@ public class HPCloudObjectStorageBlobStoreContextModule extends SwiftBlobStoreCo @Override public String toString() { - return "getCDNMetadata()"; + return "get()"; } } @@ -99,7 +97,7 @@ public class HPCloudObjectStorageBlobStoreContextModule extends SwiftBlobStoreCo protected LoadingCache cdnContainer(GetCDNMetadata loader) { return CacheBuilder.newBuilder().expireAfterWrite(30, TimeUnit.SECONDS).build(loader); } - + @Override protected void configure() { install(new BlobStoreMapModule()); @@ -107,6 +105,5 @@ public class HPCloudObjectStorageBlobStoreContextModule extends SwiftBlobStoreCo bind(AsyncBlobStore.class).to(HPCloudObjectStorageAsyncBlobStore.class); bind(BlobStore.class).to(HPCloudObjectStorageBlobStore.class); bind(ObjectToBlobMetadata.class).to(HPCloudObjectStorageObjectToBlobMetadata.class); - bind(BlobRequestSigner.class).to(HPCloudObjectStorageBlobRequestSigner.class); } } diff --git a/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/blobstore/functions/EnableCDNAndCache.java b/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/blobstore/functions/EnableCDNAndCache.java index c24d3f4d80..74c7585a1c 100644 --- a/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/blobstore/functions/EnableCDNAndCache.java +++ b/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/blobstore/functions/EnableCDNAndCache.java @@ -25,8 +25,8 @@ import java.net.URI; import javax.inject.Inject; import javax.inject.Singleton; -import org.jclouds.hpcloud.objectstorage.HPCloudObjectStorageClient; -import org.jclouds.hpcloud.objectstorage.extensions.HPCloudCDNClient; +import org.jclouds.hpcloud.objectstorage.HPCloudObjectStorageApi; +import org.jclouds.hpcloud.objectstorage.extensions.CDNContainerApi; import com.google.common.base.Function; import com.google.common.base.Optional; @@ -39,19 +39,19 @@ import com.google.common.cache.LoadingCache; @Singleton public class EnableCDNAndCache implements Function { private final LoadingCache cdnContainer; - private final HPCloudObjectStorageClient sync; + private final HPCloudObjectStorageApi sync; @Inject - public EnableCDNAndCache(HPCloudObjectStorageClient sync, LoadingCache cdnContainer) { + public EnableCDNAndCache(HPCloudObjectStorageApi sync, LoadingCache cdnContainer) { this.sync = sync; this.cdnContainer = cdnContainer; } @Override public URI apply(String input) { - Optional cdnExtension = sync.getCDNExtension(); + Optional cdnExtension = sync.getCDNExtension(); checkArgument(cdnExtension.isPresent(), "CDN is required, but the extension is not available!"); - URI uri = cdnExtension.get().enableCDN(input); + URI uri = cdnExtension.get().enable(input); cdnContainer.put(input, uri); return uri; } diff --git a/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/config/HPCloudObjectStorageRestClientModule.java b/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/config/HPCloudObjectStorageRestClientModule.java index 38fc722774..4db5bda2a5 100644 --- a/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/config/HPCloudObjectStorageRestClientModule.java +++ b/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/config/HPCloudObjectStorageRestClientModule.java @@ -25,10 +25,10 @@ import java.util.Map; import javax.inject.Singleton; -import org.jclouds.hpcloud.objectstorage.HPCloudObjectStorageAsyncClient; -import org.jclouds.hpcloud.objectstorage.HPCloudObjectStorageClient; -import org.jclouds.hpcloud.objectstorage.extensions.HPCloudCDNAsyncClient; -import org.jclouds.hpcloud.objectstorage.extensions.HPCloudCDNClient; +import org.jclouds.hpcloud.objectstorage.HPCloudObjectStorageApi; +import org.jclouds.hpcloud.objectstorage.HPCloudObjectStorageAsyncApi; +import org.jclouds.hpcloud.objectstorage.extensions.CDNContainerApi; +import org.jclouds.hpcloud.objectstorage.extensions.CDNContainerAsyncApi; import org.jclouds.hpcloud.services.HPExtensionCDN; import org.jclouds.hpcloud.services.HPExtensionServiceType; import org.jclouds.location.suppliers.RegionIdToURISupplier; @@ -45,25 +45,25 @@ import com.google.inject.Provides; import com.google.inject.Scopes; /** - * + * * @author Adrian Cole */ @ConfiguresRestClient public class HPCloudObjectStorageRestClientModule extends - SwiftRestClientModule { + SwiftRestClientModule { public static final Map, Class> DELEGATE_MAP = ImmutableMap., Class> builder().put( - HPCloudCDNClient.class, HPCloudCDNAsyncClient.class).build(); + CDNContainerApi.class, CDNContainerAsyncApi.class).build(); public HPCloudObjectStorageRestClientModule() { - super(TypeToken.of(HPCloudObjectStorageClient.class), TypeToken.of(HPCloudObjectStorageAsyncClient.class), + super(TypeToken.of(HPCloudObjectStorageApi.class), TypeToken.of(HPCloudObjectStorageAsyncApi.class), DELEGATE_MAP); } protected void bindResolvedClientsToCommonSwift() { - bind(CommonSwiftClient.class).to(HPCloudObjectStorageClient.class).in(Scopes.SINGLETON); - bind(CommonSwiftAsyncClient.class).to(HPCloudObjectStorageAsyncClient.class).in(Scopes.SINGLETON); + bind(CommonSwiftClient.class).to(HPCloudObjectStorageApi.class).in(Scopes.SINGLETON); + bind(CommonSwiftAsyncClient.class).to(HPCloudObjectStorageAsyncApi.class).in(Scopes.SINGLETON); } - + @Provides @Singleton @HPExtensionCDN diff --git a/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/domain/ContainerCDNMetadata.java b/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/domain/CDNContainer.java similarity index 54% rename from providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/domain/ContainerCDNMetadata.java rename to providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/domain/CDNContainer.java index b931ded516..832b276e31 100644 --- a/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/domain/ContainerCDNMetadata.java +++ b/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/domain/CDNContainer.java @@ -24,23 +24,20 @@ import java.net.URI; import org.jclouds.javax.annotation.Nullable; import com.google.common.base.Objects; +import com.google.common.base.Strings; import com.google.common.base.Objects.ToStringHelper; -/** - * @author James Murty - */ -public class ContainerCDNMetadata implements Comparable { +public class CDNContainer implements Comparable { - public static Builder builder() { - return new ConcreteBuilder(); + public static Builder builder() { + return new Builder(); } - public Builder toBuilder() { - return new ConcreteBuilder().fromContainerCDNMetadata(this); + public Builder toBuilder() { + return builder().fromCDNContainer(this); } - public static abstract class Builder> { - protected abstract T self(); + public static class Builder { protected String name; protected boolean cdnEnabled; @@ -51,82 +48,70 @@ public class ContainerCDNMetadata implements Comparable { protected boolean logRetention; /** - * @see ContainerCDNMetadata#getName() + * @see CDNContainer#getName() */ - public T name(String name) { + public Builder name(String name) { this.name = name; - return self(); - } - - /** - * @see ContainerCDNMetadata#isCDNEnabled() - */ - public T CDNEnabled(boolean cdnEnabled) { - this.cdnEnabled = cdnEnabled; - return self(); - } - - /** - * @see ContainerCDNMetadata#getTTL - */ - public T ttl(long ttl) { - this.ttl = ttl; - return self(); - } - - /** - * @see ContainerCDNMetadata#getCDNUri() - */ - public T CDNUri(URI CDNUri) { - this.CDNUri = CDNUri; - return self(); - } - - /** - * @see ContainerCDNMetadata#getReferrerAcl() - */ - public T referrerAcl(String referrerAcl) { - this.referrerAcl = referrerAcl; - return self(); - } - - /** - * @see ContainerCDNMetadata#getUseragentAcl() - */ - public T useragent_acl(String useragentAcl) { - this.useragentAcl = useragentAcl; - return self(); - } - - /** - * @see ContainerCDNMetadata#isLogRetention() - */ - public T logRetention(boolean logRetention) { - this.logRetention = logRetention; - return self(); - } - - public ContainerCDNMetadata build() { - return new ContainerCDNMetadata(name, cdnEnabled, ttl, CDNUri, referrerAcl, useragentAcl, logRetention); - } - - public T fromContainerCDNMetadata(ContainerCDNMetadata in) { - return this - .name(in.getName()) - .CDNEnabled(in.isCDNEnabled()) - .ttl(in.getTTL()) - .CDNUri(in.getCDNUri()) - .referrerAcl(in.getReferrerAcl()) - .useragent_acl(in.getUseragentAcl()) - .logRetention(in.isLogRetention()); - } - } - - private static class ConcreteBuilder extends Builder { - @Override - protected ConcreteBuilder self() { return this; } + + /** + * @see CDNContainer#isCDNEnabled() + */ + public Builder CDNEnabled(boolean cdnEnabled) { + this.cdnEnabled = cdnEnabled; + return this; + } + + /** + * @see CDNContainer#getTTL + */ + public Builder ttl(long ttl) { + this.ttl = ttl; + return this; + } + + /** + * @see CDNContainer#getCDNUri() + */ + public Builder CDNUri(URI CDNUri) { + this.CDNUri = CDNUri; + return this; + } + + /** + * @see CDNContainer#getReferrerAcl() + */ + public Builder referrerAcl(String referrerAcl) { + this.referrerAcl = referrerAcl; + return this; + } + + /** + * @see CDNContainer#getUseragentAcl() + */ + public Builder useragent_acl(String useragentAcl) { + this.useragentAcl = useragentAcl; + return this; + } + + /** + * @see CDNContainer#isLogRetention() + */ + public Builder logRetention(boolean logRetention) { + this.logRetention = logRetention; + return this; + } + + public CDNContainer build() { + return new CDNContainer(name, cdnEnabled, ttl, CDNUri, referrerAcl, useragentAcl, logRetention); + } + + public Builder fromCDNContainer(CDNContainer in) { + return this.name(in.getName()).CDNEnabled(in.isCDNEnabled()).ttl(in.getTTL()).CDNUri(in.getCDNUri()) + .referrerAcl(in.getReferrerAcl()).useragent_acl(in.getUseragentAcl()) + .logRetention(in.isLogRetention()); + } } private final String name; @@ -137,23 +122,21 @@ public class ContainerCDNMetadata implements Comparable { private final String useragentAcl; private final boolean logRetention; - @ConstructorProperties({ - "name", "cdn_enabled", "ttl", "x-cdn-uri", "referrer_acl", "useragent_acl", "log_retention" - }) - protected ContainerCDNMetadata(@Nullable String name, boolean cdnEnabled, long ttl, @Nullable URI CDNUri, - @Nullable String referrerAcl, @Nullable String useragentAcl, boolean logRetention) { - this.name = name; + @ConstructorProperties({ "name", "cdn_enabled", "ttl", "cdn_uri", "referrer_acl", "useragent_acl", "log_retention" }) + protected CDNContainer(@Nullable String name, boolean cdnEnabled, long ttl, @Nullable URI CDNUri, + @Nullable String referrerAcl, @Nullable String useragentAcl, boolean logRetention) { + this.name = Strings.emptyToNull(name); this.cdnEnabled = cdnEnabled; this.ttl = ttl; this.CDNUri = CDNUri; - this.referrerAcl = referrerAcl; - this.useragentAcl = useragentAcl; + this.referrerAcl = Strings.emptyToNull(referrerAcl); + this.useragentAcl = Strings.emptyToNull(useragentAcl); this.logRetention = logRetention; } /** * Beware: The container name is not available from HEAD CDN responses and will be null. - * + * * @return the name of the container to which these CDN settings apply. */ @Nullable @@ -195,16 +178,18 @@ public class ContainerCDNMetadata implements Comparable { @Override public boolean equals(Object obj) { - if (this == obj) return true; - if (obj == null || getClass() != obj.getClass()) return false; - ContainerCDNMetadata that = ContainerCDNMetadata.class.cast(obj); + if (this == obj) + return true; + if (obj == null || getClass() != obj.getClass()) + return false; + CDNContainer that = CDNContainer.class.cast(obj); return Objects.equal(this.name, that.name) && Objects.equal(this.CDNUri, that.CDNUri); } protected ToStringHelper string() { - return Objects.toStringHelper(this) - .add("name", name).add("cdnEnabled", cdnEnabled).add("ttl", ttl).add("CDNUri", CDNUri) - .add("referrerAcl", referrerAcl).add("useragentAcl", useragentAcl).add("logRetention", logRetention); + return Objects.toStringHelper(this).omitNullValues().add("name", name).add("cdnEnabled", cdnEnabled) + .add("ttl", ttl).add("CDNUri", CDNUri).add("referrerAcl", referrerAcl).add("useragentAcl", useragentAcl) + .add("logRetention", logRetention); } @Override @@ -212,7 +197,7 @@ public class ContainerCDNMetadata implements Comparable { return string().toString(); } - public int compareTo(ContainerCDNMetadata o) { + public int compareTo(CDNContainer o) { if (getName() == null) return -1; return (this == o) ? 0 : getName().compareTo(o.getName()); diff --git a/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/extensions/HPCloudCDNClient.java b/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/extensions/CDNContainerApi.java similarity index 74% rename from providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/extensions/HPCloudCDNClient.java rename to providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/extensions/CDNContainerApi.java index d55090ae3b..a659fa14ee 100644 --- a/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/extensions/HPCloudCDNClient.java +++ b/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/extensions/CDNContainerApi.java @@ -19,14 +19,14 @@ package org.jclouds.hpcloud.objectstorage.extensions; import java.net.URI; -import java.util.Set; import java.util.concurrent.TimeUnit; import org.jclouds.concurrent.Timeout; -import org.jclouds.hpcloud.objectstorage.domain.ContainerCDNMetadata; +import org.jclouds.hpcloud.objectstorage.domain.CDNContainer; import org.jclouds.hpcloud.objectstorage.options.ListCDNContainerOptions; import com.google.common.annotations.Beta; +import com.google.common.collect.FluentIterable; import com.google.common.util.concurrent.ListenableFuture; /** @@ -36,30 +36,28 @@ import com.google.common.util.concurrent.ListenableFuture; * All commands return a ListenableFuture of the result. Any exceptions incurred during processing * will be backend in an {@link java.util.concurrent.ExecutionException} as documented in {@link ListenableFuture#get()}. * - * @see org.jclouds.hpcloud.objectstorage.HPCloudObjectStorageClient + * @see org.jclouds.hpcloud.objectstorage.HPCloudObjectStorageApi * @see HP Cloud Object * Storage API + * @see CDNContainerAsyncApi * @author Jeremy Daggett */ +@Beta @Timeout(duration = 120, timeUnit = TimeUnit.SECONDS) -public interface HPCloudCDNClient { - - @Beta - Set listCDNContainers(ListCDNContainerOptions... options); - - @Beta - ContainerCDNMetadata getCDNMetadata(String container); - - @Beta - URI enableCDN(String container, long ttl); - - @Beta - URI enableCDN(String container); - - @Beta - URI updateCDN(String container, long ttl); +public interface CDNContainerApi { - @Beta - boolean disableCDN(String container); + FluentIterable list(); + + FluentIterable list(ListCDNContainerOptions options); + + CDNContainer get(String container); + + URI enable(String container, long ttl); + + URI enable(String container); + + URI update(String container, long ttl); + + boolean disable(String container); } diff --git a/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/extensions/HPCloudCDNAsyncClient.java b/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/extensions/CDNContainerAsyncApi.java similarity index 60% rename from providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/extensions/HPCloudCDNAsyncClient.java rename to providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/extensions/CDNContainerAsyncApi.java index c61019d5b0..554c19dbc2 100644 --- a/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/extensions/HPCloudCDNAsyncClient.java +++ b/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/extensions/CDNContainerAsyncApi.java @@ -19,7 +19,6 @@ package org.jclouds.hpcloud.objectstorage.extensions; import java.net.URI; -import java.util.Set; import javax.ws.rs.Consumes; import javax.ws.rs.GET; @@ -32,10 +31,10 @@ import javax.ws.rs.PathParam; import javax.ws.rs.core.MediaType; import org.jclouds.blobstore.functions.ReturnNullOnContainerNotFound; -import org.jclouds.hpcloud.objectstorage.HPCloudObjectStorageClient; -import org.jclouds.hpcloud.objectstorage.domain.ContainerCDNMetadata; +import org.jclouds.hpcloud.objectstorage.HPCloudObjectStorageApi; +import org.jclouds.hpcloud.objectstorage.domain.CDNContainer; +import org.jclouds.hpcloud.objectstorage.functions.ParseCDNContainerFromHeaders; import org.jclouds.hpcloud.objectstorage.functions.ParseCDNUriFromHeaders; -import org.jclouds.hpcloud.objectstorage.functions.ParseContainerCDNMetadataFromHeaders; import org.jclouds.hpcloud.objectstorage.options.ListCDNContainerOptions; import org.jclouds.hpcloud.objectstorage.reference.HPCloudObjectStorageHeaders; import org.jclouds.hpcloud.services.HPExtensionCDN; @@ -47,84 +46,99 @@ import org.jclouds.rest.annotations.QueryParams; import org.jclouds.rest.annotations.RequestFilters; import org.jclouds.rest.annotations.ResponseParser; import org.jclouds.rest.annotations.SkipEncoding; +import org.jclouds.rest.functions.ReturnEmptyFluentIterableOnNotFoundOr404; import com.google.common.annotations.Beta; +import com.google.common.collect.FluentIterable; import com.google.common.util.concurrent.ListenableFuture; /** * Provides asynchronous access to HP Cloud Object Storage via the REST API. * - *

All commands return a ListenableFuture of the result. Any exceptions incurred - * during processing will be backend in an {@link java.util.concurrent.ExecutionException} as documented in + *

+ * All commands return a ListenableFuture of the result. Any exceptions incurred during processing + * will be backend in an {@link java.util.concurrent.ExecutionException} as documented in * {@link ListenableFuture#get()}. * - * @see HPCloudObjectStorageClient - * @see HP Cloud Object Storage API + * @see HPCloudObjectStorageApi + * @see HP Cloud Object + * Storage API * @author Jeremy Daggett */ @SkipEncoding('/') @RequestFilters(AuthenticateRequest.class) @Endpoint(HPExtensionCDN.class) -public interface HPCloudCDNAsyncClient { - +public interface CDNContainerAsyncApi { /** - * @see HPCloudObjectStorageClient#listCDNContainers(ListCDNContainerOptions...) + * @see HPCloudObjectStorageApi#list() */ @Beta @GET @Consumes(MediaType.APPLICATION_JSON) @QueryParams(keys = "format", values = "json") + @ExceptionParser(ReturnEmptyFluentIterableOnNotFoundOr404.class) @Path("/") - ListenableFuture> listCDNContainers(ListCDNContainerOptions... options); - + ListenableFuture> list(); + /** - * @see HPCloudObjectStorageClient#getCDNMetadata(String) + * @see HPCloudObjectStorageApi#list(ListCDNContainerOptions) + */ + @Beta + @GET + @Consumes(MediaType.APPLICATION_JSON) + @QueryParams(keys = "format", values = "json") + @ExceptionParser(ReturnEmptyFluentIterableOnNotFoundOr404.class) + @Path("/") + ListenableFuture> list(ListCDNContainerOptions options); + + /** + * @see HPCloudObjectStorageApi#get(String) */ @Beta @HEAD - @ResponseParser(ParseContainerCDNMetadataFromHeaders.class) + @ResponseParser(ParseCDNContainerFromHeaders.class) @ExceptionParser(ReturnNullOnContainerNotFound.class) @Path("/{container}") - ListenableFuture getCDNMetadata(@PathParam("container") String container); + ListenableFuture get(@PathParam("container") String container); /** - * @see HPCloudObjectStorageClient#enableCDN(String, long) + * @see HPCloudObjectStorageApi#enable(String, long) */ @Beta @PUT @Path("/{container}") @Headers(keys = HPCloudObjectStorageHeaders.CDN_ENABLED, values = "True") @ResponseParser(ParseCDNUriFromHeaders.class) - ListenableFuture enableCDN(@PathParam("container") String container, - @HeaderParam(HPCloudObjectStorageHeaders.CDN_TTL) long ttl); + ListenableFuture enable(@PathParam("container") String container, + @HeaderParam(HPCloudObjectStorageHeaders.CDN_TTL) long ttl); /** - * @see HPCloudObjectStorageClient#enableCDN(String) + * @see HPCloudObjectStorageApi#enable(String) */ @Beta @PUT @Path("/{container}") @Headers(keys = HPCloudObjectStorageHeaders.CDN_ENABLED, values = "True") @ResponseParser(ParseCDNUriFromHeaders.class) - ListenableFuture enableCDN(@PathParam("container") String container); + ListenableFuture enable(@PathParam("container") String container); /** - * @see HPCloudObjectStorageClient#updateCDN(String, long) + * @see HPCloudObjectStorageApi#update(String, long) */ @Beta @POST @Path("/{container}") @ResponseParser(ParseCDNUriFromHeaders.class) - ListenableFuture updateCDN(@PathParam("container") String container, - @HeaderParam(HPCloudObjectStorageHeaders.CDN_TTL) long ttl); + ListenableFuture update(@PathParam("container") String container, + @HeaderParam(HPCloudObjectStorageHeaders.CDN_TTL) long ttl); /** - * @see HPCloudObjectStorageClient#disableCDN(String) + * @see HPCloudObjectStorageApi#disable(String) */ @Beta @PUT @Path("/{container}") @Headers(keys = HPCloudObjectStorageHeaders.CDN_ENABLED, values = "False") - ListenableFuture disableCDN(@PathParam("container") String container); + ListenableFuture disable(@PathParam("container") String container); } diff --git a/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/functions/ParseContainerCDNMetadataFromHeaders.java b/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/functions/ParseCDNContainerFromHeaders.java similarity index 81% rename from providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/functions/ParseContainerCDNMetadataFromHeaders.java rename to providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/functions/ParseCDNContainerFromHeaders.java index 386cb00ce6..96e63f0c07 100644 --- a/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/functions/ParseContainerCDNMetadataFromHeaders.java +++ b/providers/hpcloud-objectstorage/src/main/java/org/jclouds/hpcloud/objectstorage/functions/ParseCDNContainerFromHeaders.java @@ -24,7 +24,7 @@ import static com.google.common.collect.Lists.newArrayList; import java.net.URI; import java.util.List; -import org.jclouds.hpcloud.objectstorage.domain.ContainerCDNMetadata; +import org.jclouds.hpcloud.objectstorage.domain.CDNContainer; import org.jclouds.hpcloud.objectstorage.reference.HPCloudObjectStorageHeaders; import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpResponse; @@ -39,15 +39,15 @@ import com.google.common.base.Splitter; * * @author James Murty */ -public class ParseContainerCDNMetadataFromHeaders implements - Function, InvocationContext { +public class ParseCDNContainerFromHeaders implements + Function, InvocationContext { private HttpRequest request; /** - * parses the http response headers to create a new {@link ContainerCDNMetadata} object. + * parses the http response headers to create a new {@link CDNContainer} object. */ - public ContainerCDNMetadata apply(final HttpResponse from) { + public CDNContainer apply(final HttpResponse from) { String cdnUri = checkNotNull(from.getFirstHeaderOrNull(HPCloudObjectStorageHeaders.CDN_URI), HPCloudObjectStorageHeaders.CDN_URI); String cdnTTL = checkNotNull(from.getFirstHeaderOrNull(HPCloudObjectStorageHeaders.CDN_TTL), @@ -61,14 +61,14 @@ public class ParseContainerCDNMetadataFromHeaders implements // just need the name from the path List parts = newArrayList(Splitter.on('/').split(request.getEndpoint().getPath())); - return ContainerCDNMetadata.builder().name(parts.get(parts.size() - 1)) + return CDNContainer.builder().name(parts.get(parts.size() - 1)) .CDNEnabled(Boolean.parseBoolean(cdnEnabled)).ttl(Long.parseLong(cdnTTL)).CDNUri(URI.create(cdnUri)) .build(); } } @Override - public ParseContainerCDNMetadataFromHeaders setContext(HttpRequest request) { + public ParseCDNContainerFromHeaders setContext(HttpRequest request) { this.request = request; return this; } diff --git a/providers/hpcloud-objectstorage/src/test/java/org/jclouds/hpcloud/objectstorage/HPCloudObjectStorageClientLiveTest.java b/providers/hpcloud-objectstorage/src/test/java/org/jclouds/hpcloud/objectstorage/HPCloudObjectStorageClientLiveTest.java index 36b7256355..ccb1918f23 100644 --- a/providers/hpcloud-objectstorage/src/test/java/org/jclouds/hpcloud/objectstorage/HPCloudObjectStorageClientLiveTest.java +++ b/providers/hpcloud-objectstorage/src/test/java/org/jclouds/hpcloud/objectstorage/HPCloudObjectStorageClientLiveTest.java @@ -22,27 +22,28 @@ import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import java.net.URI; -import java.util.Set; -import org.jclouds.hpcloud.objectstorage.domain.ContainerCDNMetadata; +import org.jclouds.hpcloud.objectstorage.domain.CDNContainer; import org.jclouds.hpcloud.objectstorage.options.ListCDNContainerOptions; import org.jclouds.openstack.swift.CommonSwiftClientLiveTest; import org.jclouds.openstack.swift.domain.SwiftObject; import org.testng.annotations.Test; +import com.google.common.collect.FluentIterable; + /** * * @author Adrian Cole */ @Test(groups = "live", testName = "HPCloudObjectStorageClientLiveTest") -public class HPCloudObjectStorageClientLiveTest extends CommonSwiftClientLiveTest { +public class HPCloudObjectStorageClientLiveTest extends CommonSwiftClientLiveTest { public HPCloudObjectStorageClientLiveTest(){ provider = "hpcloud-objectstorage"; } @Override - public HPCloudObjectStorageClient getApi() { + public HPCloudObjectStorageApi getApi() { return view.unwrap(HPCloudObjectStorageApiMetadata.CONTEXT_TOKEN).getApi(); } @@ -61,49 +62,49 @@ public class HPCloudObjectStorageClientLiveTest extends CommonSwiftClientLiveTes final String containerNameWithoutCDN = getContainerName(); try { try { - getApi().getCDNExtension().get().disableCDN(containerNameWithCDN); - getApi().getCDNExtension().get().disableCDN(containerNameWithoutCDN); + getApi().getCDNExtension().get().disable(containerNameWithCDN); + getApi().getCDNExtension().get().disable(containerNameWithoutCDN); } catch (Exception e) { e.printStackTrace(); } - ContainerCDNMetadata cdnMetadata = null; + CDNContainer cdnMetadata = null; // Enable CDN with PUT for one container - final URI cdnUri = getApi().getCDNExtension().get().enableCDN(containerNameWithCDN); + final URI cdnUri = getApi().getCDNExtension().get().enable(containerNameWithCDN); assertTrue(cdnUri != null); // Confirm CDN is enabled via HEAD request and has default TTL - cdnMetadata = getApi().getCDNExtension().get().getCDNMetadata(containerNameWithCDN); + cdnMetadata = getApi().getCDNExtension().get().get(containerNameWithCDN); assertTrue(cdnMetadata.isCDNEnabled()); assertEquals(cdnMetadata.getCDNUri(), cdnUri); - cdnMetadata = getApi().getCDNExtension().get().getCDNMetadata(containerNameWithoutCDN); + cdnMetadata = getApi().getCDNExtension().get().get(containerNameWithoutCDN); assert cdnMetadata == null || !cdnMetadata.isCDNEnabled() : containerNameWithoutCDN + " should not have metadata"; - assert getApi().getCDNExtension().get().getCDNMetadata("DoesNotExist") == null; + assert getApi().getCDNExtension().get().get("DoesNotExist") == null; // List CDN metadata for containers, and ensure all CDN info is // available for enabled // container - Set cdnMetadataList = getApi().getCDNExtension().get().listCDNContainers(); + FluentIterable cdnMetadataList = getApi().getCDNExtension().get().list(); assertTrue(cdnMetadataList.size() >= 1); final long initialTTL = cdnMetadata.getTTL(); - assertTrue(cdnMetadataList.contains(ContainerCDNMetadata.builder().name(containerNameWithCDN) + assertTrue(cdnMetadataList.contains(CDNContainer.builder().name(containerNameWithCDN) .CDNEnabled(true).ttl(initialTTL).CDNUri(cdnUri).build())); /* * Test listing with options FIXFIX cdnMetadataList = - * getApi().listCDNContainers(ListCDNContainerOptions.Builder.enabledOnly()); - * assertTrue(Iterables.all(cdnMetadataList, new Predicate() { public - * boolean apply(ContainerCDNMetadata cdnMetadata) { return cdnMetadata.isCDNEnabled(); } + * getApi().list(ListCDNContainerOptions.Builder.enabledOnly()); + * assertTrue(Iterables.all(cdnMetadataList, new Predicate() { public + * boolean apply(CDNContainer cdnMetadata) { return cdnMetadata.isCDNEnabled(); } * })); */ - cdnMetadataList = getApi().getCDNExtension().get().listCDNContainers( + cdnMetadataList = getApi().getCDNExtension().get().list( ListCDNContainerOptions.Builder.afterMarker( containerNameWithCDN.substring(0, containerNameWithCDN.length() - 1)).maxResults(1)); assertEquals(cdnMetadataList.size(), 1); @@ -111,9 +112,9 @@ public class HPCloudObjectStorageClientLiveTest extends CommonSwiftClientLiveTes // Enable CDN with PUT for the same container, this time with a custom // TTL long ttl = 4000; - getApi().getCDNExtension().get().enableCDN(containerNameWithCDN, ttl); + getApi().getCDNExtension().get().enable(containerNameWithCDN, ttl); - cdnMetadata = getApi().getCDNExtension().get().getCDNMetadata(containerNameWithCDN); + cdnMetadata = getApi().getCDNExtension().get().get(containerNameWithCDN); assertTrue(cdnMetadata.isCDNEnabled()); @@ -121,23 +122,23 @@ public class HPCloudObjectStorageClientLiveTest extends CommonSwiftClientLiveTes // Check POST by updating TTL settings ttl = minimumTTL; - getApi().getCDNExtension().get().updateCDN(containerNameWithCDN, minimumTTL); + getApi().getCDNExtension().get().update(containerNameWithCDN, minimumTTL); - cdnMetadata = getApi().getCDNExtension().get().getCDNMetadata(containerNameWithCDN); + cdnMetadata = getApi().getCDNExtension().get().get(containerNameWithCDN); assertTrue(cdnMetadata.isCDNEnabled()); assertEquals(cdnMetadata.getTTL(), minimumTTL); // Confirm that minimum allowed value for TTL is 3600, lower values are // ignored. - getApi().getCDNExtension().get().updateCDN(containerNameWithCDN, 3599L); - cdnMetadata = getApi().getCDNExtension().get().getCDNMetadata(containerNameWithCDN); + getApi().getCDNExtension().get().update(containerNameWithCDN, 3599L); + cdnMetadata = getApi().getCDNExtension().get().get(containerNameWithCDN); assertEquals(cdnMetadata.getTTL(), 3599L); // Disable CDN with POST - assertTrue(getApi().getCDNExtension().get().disableCDN(containerNameWithCDN)); + assertTrue(getApi().getCDNExtension().get().disable(containerNameWithCDN)); - cdnMetadata = getApi().getCDNExtension().get().getCDNMetadata(containerNameWithCDN); + cdnMetadata = getApi().getCDNExtension().get().get(containerNameWithCDN); assertEquals(cdnMetadata.isCDNEnabled(), false); } catch (Exception e) { e.printStackTrace(); diff --git a/providers/hpcloud-objectstorage/src/test/java/org/jclouds/hpcloud/objectstorage/blobstore/HPCloudObjectStorageBlobRequestSignerTest.java b/providers/hpcloud-objectstorage/src/test/java/org/jclouds/hpcloud/objectstorage/blobstore/HPCloudObjectStorageBlobRequestSignerTest.java deleted file mode 100644 index da1c2699ec..0000000000 --- a/providers/hpcloud-objectstorage/src/test/java/org/jclouds/hpcloud/objectstorage/blobstore/HPCloudObjectStorageBlobRequestSignerTest.java +++ /dev/null @@ -1,86 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.hpcloud.objectstorage.blobstore; - -import static org.testng.Assert.assertEquals; - -import java.util.Date; -import java.util.Map; - -import org.jclouds.blobstore.BlobRequestSigner; -import org.jclouds.blobstore.BlobStore; -import org.jclouds.blobstore.domain.Blob; -import org.jclouds.hpcloud.objectstorage.internal.BaseHPCloudObjectStorageBlobStoreExpectTest; -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.ImmutableMultimap; - -/** - * Tests behavior of {@code HPCloudObjectStorageBlobRequestSigner} - * - * @author Adrian Cole - */ -// NOTE:without testName, this will not call @Before* and fail w/NPE during surefire -@Test(groups = "unit", testName = "HPCloudObjectStorageBlobRequestSignerTest") -public class HPCloudObjectStorageBlobRequestSignerTest extends BaseHPCloudObjectStorageBlobStoreExpectTest { - - Map requestResponseMap = ImmutableMap. builder().put( - keystoneAuthWithAccessKeyAndSecretKey, responseWithKeystoneAccess).build(); - - public void testSignGetBlob() { - - BlobRequestSigner signGetBlob = requestsSendResponses(requestResponseMap).getContext().getSigner(); - - HttpRequest request = signGetBlob.signGetBlob("container", "name"); - - assertEquals(request.getRequestLine(), - "GET https://objects.jclouds.org/v1.0/40806637803162/container/name HTTP/1.1"); - assertEquals(request.getHeaders(), ImmutableMultimap.of("X-Auth-Token", "Auth_4f173437e4b013bee56d1007")); - } - - public void testSignRemoveBlob() { - BlobRequestSigner signRemoveBlob = requestsSendResponses(requestResponseMap).getContext().getSigner(); - - HttpRequest request = signRemoveBlob.signRemoveBlob("container", "name"); - assertEquals(request.getRequestLine(), - "DELETE https://objects.jclouds.org/v1.0/40806637803162/container/name HTTP/1.1"); - assertEquals(request.getHeaders(), ImmutableMultimap.of("X-Auth-Token", "Auth_4f173437e4b013bee56d1007")); - - } - - public void testSignPutBlob() { - BlobStore blobStore = requestsSendResponses(requestResponseMap); - BlobRequestSigner signPutBlob = blobStore.getContext().getSigner(); - Blob blob = blobStore.blobBuilder("name").forSigning().contentLength(2l).contentMD5(new byte[] { 0, 2, 4, 8 }) - .contentType("text/plain").expires(new Date(1000)).build(); - - HttpRequest request = signPutBlob.signPutBlob("container", blob); - - assertEquals(request.getRequestLine(), - "PUT https://objects.jclouds.org/v1.0/40806637803162/container/name HTTP/1.1"); - assertEquals(request.getHeaders(), ImmutableMultimap.of("X-Auth-Token", "Auth_4f173437e4b013bee56d1007")); - // TODO: - // assertEquals(request.getPayload(), blob); - - } - -} diff --git a/providers/hpcloud-objectstorage/src/test/java/org/jclouds/hpcloud/objectstorage/blobstore/HPCloudObjectStorageBlobSignerExpectTest.java b/providers/hpcloud-objectstorage/src/test/java/org/jclouds/hpcloud/objectstorage/blobstore/HPCloudObjectStorageBlobSignerExpectTest.java new file mode 100644 index 0000000000..51bf2a44be --- /dev/null +++ b/providers/hpcloud-objectstorage/src/test/java/org/jclouds/hpcloud/objectstorage/blobstore/HPCloudObjectStorageBlobSignerExpectTest.java @@ -0,0 +1,148 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.hpcloud.objectstorage.blobstore; + +import static org.jclouds.openstack.swift.reference.SwiftHeaders.ACCOUNT_TEMPORARY_URL_KEY; + +import java.util.Map; + +import org.jclouds.apis.ApiMetadata; +import org.jclouds.blobstore.internal.BaseBlobSignerExpectTest; +import org.jclouds.hpcloud.objectstorage.HPCloudObjectStorageApiMetadata; +import org.jclouds.hpcloud.objectstorage.HPCloudObjectStorageApiMetadata.HPCloudObjectStorageTemporaryUrlExtensionModule; +import org.jclouds.hpcloud.objectstorage.blobstore.config.HPCloudObjectStorageBlobStoreContextModule; +import org.jclouds.hpcloud.objectstorage.config.HPCloudObjectStorageRestClientModule; +import org.jclouds.http.HttpRequest; +import org.jclouds.http.HttpResponse; +import org.jclouds.openstack.keystone.v2_0.config.KeystoneAuthenticationModule.RegionModule; +import org.jclouds.openstack.swift.config.SwiftRestClientModule.KeystoneStorageEndpointModule; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; +import com.google.inject.Module; + +/** + * Tests behavior of {@code SwiftBlobRequestSigner} + * + * @author Adrian Cole + */ +@Test(groups = "unit", testName = "HPCloudObjectStorageBlobSignerExpectTest") +public class HPCloudObjectStorageBlobSignerExpectTest extends BaseBlobSignerExpectTest { + + public HPCloudObjectStorageBlobSignerExpectTest() { + identity = "12346637803162:identity"; + } + + @Override + protected HttpRequest getBlob() { + return HttpRequest.builder().method("GET") + .endpoint("https://objects.jclouds.org/v1.0/40806637803162/container/name") + .addHeader("X-Auth-Token", "Auth_4f173437e4b013bee56d1007").build(); + } + + @Override + protected HttpRequest getBlobWithTime() { + return HttpRequest.builder().method("GET") + .endpoint("https://objects.jclouds.org/v1.0/40806637803162/container/name?temp_url_sig=40806637803162%3Aidentity%3Ada88bc31122f0d0806b1c7bf71cd3af5c5d5b94c&temp_url_expires=123456792") + .build(); + } + + @Override + protected HttpRequest getBlobWithOptions() { + return HttpRequest.builder().method("GET") + .endpoint("https://objects.jclouds.org/v1.0/40806637803162/container/name") + .addHeader("X-Auth-Token", "Auth_4f173437e4b013bee56d1007").addHeader("Range", "bytes=0-1").build(); + } + + @Override + protected HttpRequest putBlob() { + return HttpRequest.builder().method("PUT") + .endpoint("https://objects.jclouds.org/v1.0/40806637803162/container/name") + .addHeader("X-Auth-Token", "Auth_4f173437e4b013bee56d1007").build(); + } + + @Override + protected HttpRequest putBlobWithTime() { + return HttpRequest.builder().method("PUT") + .endpoint("https://objects.jclouds.org/v1.0/40806637803162/container/name?temp_url_sig=40806637803162%3Aidentity%3Ac90269245ab0a316d5ea5e654d4c2a975fb4bf77&temp_url_expires=123456792") + .build(); + } + + @Override + protected HttpRequest removeBlob() { + return HttpRequest.builder().method("DELETE") + .endpoint("https://objects.jclouds.org/v1.0/40806637803162/container/name") + .addHeader("X-Auth-Token", "Auth_4f173437e4b013bee56d1007").build(); + } + + /** + * add the keystone commands + */ + @Override + protected Map init() { + + HttpRequest authenticate = HttpRequest + .builder() + .method("POST") + .endpoint("https://region-a.geo-1.identity.hpcloudsvc.com:35357/v2.0/tokens") + .addHeader("Accept", "application/json") + .payload( + payloadFromStringWithContentType( + "{\"auth\":{\"passwordCredentials\":{\"username\":\"identity\",\"password\":\"credential\"},\"tenantName\":\"12346637803162\"}}", + "application/json")).build(); + + HttpResponse authenticationResponse = HttpResponse.builder().statusCode(200) + .payload(payloadFromResourceWithContentType("/keystoneAuthResponseWithCDN.json", "application/json")) + .build(); + + HttpRequest temporaryKeyRequest = HttpRequest + .builder() + .method("HEAD") + .endpoint("https://objects.jclouds.org/v1.0/40806637803162/") + .addHeader("X-Auth-Token", "Auth_4f173437e4b013bee56d1007").build(); + + HttpResponse temporaryKeyResponse = HttpResponse.builder().statusCode(200) + .addHeader(ACCOUNT_TEMPORARY_URL_KEY, "TEMPORARY_KEY").build(); + + return ImmutableMap. builder() + .put(authenticate, authenticationResponse) + .put(temporaryKeyRequest, temporaryKeyResponse).build(); + } + + @Override + protected ApiMetadata createApiMetadata() { + return new HPCloudObjectStorageApiMetadata().toBuilder() + .defaultModules(ImmutableSet.>builder() + .add(KeystoneStorageEndpointModule.class) + .add(RegionModule.class) + .add(HPCloudObjectStorageRestClientModule.class) + .add(HPCloudObjectStorageBlobStoreContextModule.class) + .add(StaticTimeAndTemporaryUrlKeyModule.class).build()).build(); + } + + public static class StaticTimeAndTemporaryUrlKeyModule extends HPCloudObjectStorageTemporaryUrlExtensionModule { + public static final long UNIX_EPOCH_TIMESTAMP = 123456789L; + + @Override + protected Long unixEpochTimestampProvider() { + return UNIX_EPOCH_TIMESTAMP; + } + } +} diff --git a/providers/hpcloud-objectstorage/src/test/java/org/jclouds/hpcloud/objectstorage/blobstore/HPCloudObjectStorageBlobStoreExpectTest.java b/providers/hpcloud-objectstorage/src/test/java/org/jclouds/hpcloud/objectstorage/blobstore/HPCloudObjectStorageBlobStoreExpectTest.java index 1651065fac..20e6eaf0f8 100644 --- a/providers/hpcloud-objectstorage/src/test/java/org/jclouds/hpcloud/objectstorage/blobstore/HPCloudObjectStorageBlobStoreExpectTest.java +++ b/providers/hpcloud-objectstorage/src/test/java/org/jclouds/hpcloud/objectstorage/blobstore/HPCloudObjectStorageBlobStoreExpectTest.java @@ -39,7 +39,7 @@ public class HPCloudObjectStorageBlobStoreExpectTest extends BaseHPCloudObjectSt public void testListObjectsWhenResponseIs2xx() throws Exception { Map requestResponseMap = ImmutableMap. builder().put( - keystoneAuthWithAccessKeyAndSecretKey, responseWithKeystoneAccess).build(); + keystoneAuthWithUsernameAndPassword, responseWithKeystoneAccess).build(); BlobStore clientWhenLocationsExist = requestsSendResponses(requestResponseMap); diff --git a/providers/hpcloud-objectstorage/src/test/java/org/jclouds/hpcloud/objectstorage/blobstore/integration/HPCloudObjectStorageBlobSignerLiveTest.java b/providers/hpcloud-objectstorage/src/test/java/org/jclouds/hpcloud/objectstorage/blobstore/integration/HPCloudObjectStorageBlobSignerLiveTest.java index f78fa2436b..3f429f2a63 100644 --- a/providers/hpcloud-objectstorage/src/test/java/org/jclouds/hpcloud/objectstorage/blobstore/integration/HPCloudObjectStorageBlobSignerLiveTest.java +++ b/providers/hpcloud-objectstorage/src/test/java/org/jclouds/hpcloud/objectstorage/blobstore/integration/HPCloudObjectStorageBlobSignerLiveTest.java @@ -18,7 +18,10 @@ */ package org.jclouds.hpcloud.objectstorage.blobstore.integration; +import java.io.IOException; + import org.jclouds.openstack.swift.blobstore.integration.SwiftBlobSignerLiveTest; +import org.jclouds.rest.AuthorizationException; import org.testng.annotations.Test; /** @@ -30,4 +33,20 @@ public class HPCloudObjectStorageBlobSignerLiveTest extends SwiftBlobSignerLiveT provider = "hpcloud-objectstorage"; } + // hp doesn't yet support time-bound request signing + // https://api-docs.hpcloud.com/hpcloud-object-storage/1.0/content/ch_object-storage-dev-overview.html + @Override + @Test(expectedExceptions = AuthorizationException.class) + public void testSignGetUrlWithTime() throws InterruptedException, IOException { + super.testSignGetUrlWithTime(); + } + + // hp doesn't yet support time-bound request signing + // https://api-docs.hpcloud.com/hpcloud-object-storage/1.0/content/ch_object-storage-dev-overview.html + @Override + @Test(expectedExceptions = AuthorizationException.class) + public void testSignPutUrlWithTime() throws Exception { + super.testSignPutUrlWithTime(); + } + } diff --git a/providers/hpcloud-objectstorage/src/test/java/org/jclouds/hpcloud/objectstorage/functions/ParseContainerCDNMetadataListFromJsonResponseTest.java b/providers/hpcloud-objectstorage/src/test/java/org/jclouds/hpcloud/objectstorage/functions/ParseContainerCDNMetadataListFromJsonResponseTest.java deleted file mode 100644 index b3194b566e..0000000000 --- a/providers/hpcloud-objectstorage/src/test/java/org/jclouds/hpcloud/objectstorage/functions/ParseContainerCDNMetadataListFromJsonResponseTest.java +++ /dev/null @@ -1,68 +0,0 @@ -/** - * Licensed to jclouds, Inc. (jclouds) under one or more - * contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. jclouds licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.jclouds.hpcloud.objectstorage.functions; - -import static org.testng.Assert.assertEquals; - -import java.io.InputStream; -import java.net.URI; -import java.util.Set; -import java.util.SortedSet; - -import org.jclouds.hpcloud.objectstorage.domain.ContainerCDNMetadata; -import org.jclouds.http.HttpResponse; -import org.jclouds.http.functions.ParseJson; -import org.jclouds.json.config.GsonModule; -import org.testng.annotations.Test; - -import com.google.common.collect.ImmutableSet; -import com.google.inject.Guice; -import com.google.inject.Injector; -import com.google.inject.Key; -import com.google.inject.TypeLiteral; - -/** - * Tests behavior of {@code ParseContainerCDNMetadataListFromJsonResponse} - * - * @author Jeremy Daggett - */ -@Test(groups = "unit") -public class ParseContainerCDNMetadataListFromJsonResponseTest { - Injector i = Guice.createInjector(new GsonModule()); - - @Test - public void testApplyInputStream() { - - InputStream is = getClass().getResourceAsStream("/test_list_cdn.json"); - - Set expects = ImmutableSet.of( - ContainerCDNMetadata.builder().name("hpcloud-blobstore.testCDNOperationsContainerWithCDN").CDNEnabled(false).ttl(3600) - .CDNUri(URI.create("https://cdnmgmt.hpcloud.net:8080/v1/AUTH_test/")).build(), - ContainerCDNMetadata.builder().name("hpcloud-blobstore5").CDNEnabled(true).ttl(28800) - .CDNUri(URI.create("https://cdnmgmt.hpcloud.net:8080/v1/AUTH_test/")).build(), - ContainerCDNMetadata.builder().name("hpcloud-cfcdnint.testCDNOperationsContainerWithCDN").CDNEnabled(false).ttl(3600) - .CDNUri(URI.create("https://cdnmgmt.hpcloud.net:8080/v1/AUTH_test/")).build()); - - ParseJson> parser = i.getInstance( - Key.get(new TypeLiteral>>() { - })); - - assertEquals(parser.apply(HttpResponse.builder().statusCode(200).message("ok").payload(is).build()), expects); - } -} diff --git a/providers/hpcloud-objectstorage/src/test/java/org/jclouds/hpcloud/objectstorage/parse/CDNContainersTest.java b/providers/hpcloud-objectstorage/src/test/java/org/jclouds/hpcloud/objectstorage/parse/CDNContainersTest.java new file mode 100644 index 0000000000..389b031513 --- /dev/null +++ b/providers/hpcloud-objectstorage/src/test/java/org/jclouds/hpcloud/objectstorage/parse/CDNContainersTest.java @@ -0,0 +1,55 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.hpcloud.objectstorage.parse; + +import java.net.URI; + +import javax.ws.rs.Consumes; +import javax.ws.rs.core.MediaType; + +import org.jclouds.hpcloud.objectstorage.domain.CDNContainer; +import org.jclouds.json.BaseItemParserTest; +import org.testng.annotations.Test; + +import com.google.common.collect.FluentIterable; +import com.google.common.collect.ImmutableSet; + +/** + * @author Adrian Cole + */ +@Test(groups = "unit", testName = "CDNContainersTest") +public class CDNContainersTest extends BaseItemParserTest> { + + @Override + public String resource() { + return "/test_list_cdn.json"; + } + + @Override + @Consumes(MediaType.APPLICATION_JSON) + public FluentIterable expected() { + return FluentIterable.from(ImmutableSet.of( + CDNContainer.builder().name("hpcloud-blobstore.testCDNOperationsContainerWithCDN").CDNEnabled(false) + .ttl(3600).CDNUri(URI.create("https://cdnmgmt.hpcloud.net:8080/v1/AUTH_test/")).build(), + CDNContainer.builder().name("hpcloud-blobstore5").CDNEnabled(true).ttl(28800) + .CDNUri(URI.create("https://cdnmgmt.hpcloud.net:8080/v1/AUTH_test/")).build(), + CDNContainer.builder().name("hpcloud-cfcdnint.testCDNOperationsContainerWithCDN").CDNEnabled(false) + .ttl(3600).CDNUri(URI.create("https://cdnmgmt.hpcloud.net:8080/v1/AUTH_test/")).build())); + } +} diff --git a/providers/hpcloud-objectstorage/src/test/resources/log4j.xml b/providers/hpcloud-objectstorage/src/test/resources/log4j.xml index 12f6512542..fbbca6e6d5 100644 --- a/providers/hpcloud-objectstorage/src/test/resources/log4j.xml +++ b/providers/hpcloud-objectstorage/src/test/resources/log4j.xml @@ -89,9 +89,11 @@ diff --git a/providers/ninefold-compute/pom.xml b/providers/ninefold-compute/pom.xml index b9f96cdb5a..b9299f2c7b 100644 --- a/providers/ninefold-compute/pom.xml +++ b/providers/ninefold-compute/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider diff --git a/providers/ninefold-storage/pom.xml b/providers/ninefold-storage/pom.xml index dbed7413f2..bb3c703a32 100644 --- a/providers/ninefold-storage/pom.xml +++ b/providers/ninefold-storage/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider diff --git a/providers/openhosting-east1/pom.xml b/providers/openhosting-east1/pom.xml index 7e87b05a9e..0248751689 100644 --- a/providers/openhosting-east1/pom.xml +++ b/providers/openhosting-east1/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider diff --git a/providers/pom.xml b/providers/pom.xml index 53ca4767bf..62db71723b 100644 --- a/providers/pom.xml +++ b/providers/pom.xml @@ -24,7 +24,7 @@ jclouds-project org.jclouds - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../project/pom.xml org.jclouds.provider @@ -73,5 +73,7 @@ trystack-nova rackspace-cloudservers-us rackspace-cloudservers-uk + aws-sqs + glesys diff --git a/providers/rackspace-cloudservers-uk/pom.xml b/providers/rackspace-cloudservers-uk/pom.xml index 7d7b8f772a..41293785e8 100644 --- a/providers/rackspace-cloudservers-uk/pom.xml +++ b/providers/rackspace-cloudservers-uk/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider @@ -88,6 +88,13 @@ test-jar test + + org.jclouds.api + openstack-keystone + ${project.version} + test-jar + test + org.jclouds.driver jclouds-slf4j diff --git a/providers/rackspace-cloudservers-uk/src/main/java/org/jclouds/rackspace/cloudservers/uk/CloudServersUKProviderMetadata.java b/providers/rackspace-cloudservers-uk/src/main/java/org/jclouds/rackspace/cloudservers/uk/CloudServersUKProviderMetadata.java index 59696f916b..d84effa2b3 100644 --- a/providers/rackspace-cloudservers-uk/src/main/java/org/jclouds/rackspace/cloudservers/uk/CloudServersUKProviderMetadata.java +++ b/providers/rackspace-cloudservers-uk/src/main/java/org/jclouds/rackspace/cloudservers/uk/CloudServersUKProviderMetadata.java @@ -28,6 +28,7 @@ import java.util.Properties; import org.jclouds.openstack.keystone.v2_0.config.KeystoneAuthenticationModule.ZoneModule; import org.jclouds.openstack.nova.v2_0.NovaApiMetadata; +import org.jclouds.openstack.nova.v2_0.config.NovaParserModule; import org.jclouds.openstack.nova.v2_0.config.NovaRestClientModule; import org.jclouds.providers.ProviderMetadata; import org.jclouds.providers.internal.BaseProviderMetadata; @@ -88,6 +89,7 @@ public class CloudServersUKProviderMetadata extends BaseProviderMetadata { .defaultModules(ImmutableSet.>builder() .add(CloudIdentityAuthenticationModule.class) .add(ZoneModule.class) + .add(NovaParserModule.class) .add(NovaRestClientModule.class) .add(CloudServersUKComputeServiceContextModule.class).build()) .build()) diff --git a/providers/rackspace-cloudservers-uk/src/test/java/org/jclouds/rackspace/cloudservers/uk/CloudServersUKProviderMetadataExpectTest.java b/providers/rackspace-cloudservers-uk/src/test/java/org/jclouds/rackspace/cloudservers/uk/CloudServersUKProviderMetadataExpectTest.java new file mode 100644 index 0000000000..ef6abe25f2 --- /dev/null +++ b/providers/rackspace-cloudservers-uk/src/test/java/org/jclouds/rackspace/cloudservers/uk/CloudServersUKProviderMetadataExpectTest.java @@ -0,0 +1,64 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not uke 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.uk; + +import static org.testng.Assert.assertEquals; + +import org.jclouds.http.HttpRequest; +import org.jclouds.http.HttpResponse; +import org.jclouds.openstack.nova.v2_0.NovaApi; +import org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiExpectTest; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableSet; + +/** + * This test ensures that the wiring in {@link CloudServersUKProviderMetadata} is correct. + * + * @author Adrian Cole + */ +@Test(groups = "unit", testName = "CloudServersUKProviderMetadataExpectTest") +public class CloudServersUKProviderMetadataExpectTest extends BaseNovaApiExpectTest { + + public CloudServersUKProviderMetadataExpectTest() { + this.provider = "rackspace-cloudservers-uk"; + this.identity = "myUsername"; + this.credential = "myApiKey"; + } + + public void testCanGetConfiguredZones() { + + HttpRequest authenticate = HttpRequest.builder().method("POST") + .endpoint("https://lon.identity.api.rackspacecloud.com/v2.0/tokens") + .addHeader("Accept", "application/json") + .payload(payloadFromStringWithContentType( + "{\"auth\":{\"RAX-KSKEY:apiKeyCredentials\":{\"username\":\"myUsername\",\"apiKey\":\"myApiKey\"}}}" + , "application/json")).build(); + + + HttpResponse authenticationResponse = HttpResponse.builder().statusCode(200) + .payload(payloadFromResourceWithContentType("/access_rax_uk.json", "application/json")).build(); + + NovaApi whenNovaRegionExists = requestSendsResponse(authenticate, authenticationResponse); + + assertEquals(whenNovaRegionExists.getConfiguredZones(), ImmutableSet.of("LON")); + + } + +} diff --git a/providers/rackspace-cloudservers-uk/src/test/resources/access_rax_uk.json b/providers/rackspace-cloudservers-uk/src/test/resources/access_rax_uk.json new file mode 100644 index 0000000000..b8bd64494e --- /dev/null +++ b/providers/rackspace-cloudservers-uk/src/test/resources/access_rax_uk.json @@ -0,0 +1 @@ +{"access":{"token":{"id":"bdd18214-e266-4ad3-b985-d9bfb22c8da8","expires":"2012-10-01T02:11:16.000+01:00","tenant":{"id":"10001786","name":"10001786"}},"serviceCatalog":[{"endpoints":[{"region":"LON","tenantId":"MossoCloudFS_83a9d536-2e25-4166-bd3b-a503a934f953","publicURL":"https:\/\/storage101.lon3.clouddrive.com\/v1\/MossoCloudFS_83a9d536-2e25-4166-bd3b-a503a934f953","internalURL":"https:\/\/snet-storage101.lon3.clouddrive.com\/v1\/MossoCloudFS_83a9d536-2e25-4166-bd3b-a503a934f953"}],"name":"cloudFiles","type":"object-store"},{"endpoints":[{"region":"LON","tenantId":"MossoCloudFS_83a9d536-2e25-4166-bd3b-a503a934f953","publicURL":"https:\/\/cdn3.clouddrive.com\/v1\/MossoCloudFS_83a9d536-2e25-4166-bd3b-a503a934f953"}],"name":"cloudFilesCDN","type":"rax:object-cdn"},{"endpoints":[{"tenantId":"10001786","publicURL":"https:\/\/lon.servers.api.rackspacecloud.com\/v1.0\/10001786","versionInfo":"https:\/\/lon.servers.api.rackspacecloud.com\/v1.0","versionList":"https:\/\/lon.servers.api.rackspacecloud.com\/","versionId":"1.0"}],"name":"cloudServers","type":"compute"},{"endpoints":[{"tenantId":"10001786","publicURL":"https:\/\/lon.dns.api.rackspacecloud.com\/v1.0\/10001786"}],"name":"cloudDNS","type":"rax:dns"},{"endpoints":[{"region":"LON","tenantId":"10001786","publicURL":"https:\/\/lon.loadbalancers.api.rackspacecloud.com\/v1.0\/10001786"}],"name":"cloudLoadBalancers","type":"rax:load-balancer"},{"endpoints":[{"tenantId":"10001786","publicURL":"https:\/\/monitoring.api.rackspacecloud.com\/v1.0\/10001786"}],"name":"cloudMonitoring","type":"rax:monitor"},{"endpoints":[{"region":"LON","tenantId":"10001786","publicURL":"https:\/\/lon.databases.api.rackspacecloud.com\/v1.0\/10001786"}],"name":"cloudDatabases","type":"rax:database"},{"endpoints":[{"region":"LON","tenantId":"10001786","publicURL":"https:\/\/lon.servers.api.rackspacecloud.com\/v2\/10001786","versionInfo":"https:\/\/lon.servers.api.rackspacecloud.com\/v2","versionList":"https:\/\/lon.servers.api.rackspacecloud.com\/","versionId":"2"}],"name":"cloudServersOpenStack","type":"compute"}],"user":{"id":"378","roles":[{"id":"3","description":"User Admin Role.","name":"identity:user-admin"}],"name":"jclouds","RAX-AUTH:defaultRegion":""}}} \ No newline at end of file diff --git a/providers/rackspace-cloudservers-us/pom.xml b/providers/rackspace-cloudservers-us/pom.xml index 36cd6cc6b7..e312a7a33e 100644 --- a/providers/rackspace-cloudservers-us/pom.xml +++ b/providers/rackspace-cloudservers-us/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider @@ -88,6 +88,13 @@ test-jar test + + org.jclouds.api + openstack-keystone + ${project.version} + test-jar + test + org.jclouds.driver jclouds-slf4j diff --git a/providers/rackspace-cloudservers-us/src/main/java/org/jclouds/rackspace/cloudservers/us/CloudServersUSProviderMetadata.java b/providers/rackspace-cloudservers-us/src/main/java/org/jclouds/rackspace/cloudservers/us/CloudServersUSProviderMetadata.java index 2758535e3b..845b3d2650 100644 --- a/providers/rackspace-cloudservers-us/src/main/java/org/jclouds/rackspace/cloudservers/us/CloudServersUSProviderMetadata.java +++ b/providers/rackspace-cloudservers-us/src/main/java/org/jclouds/rackspace/cloudservers/us/CloudServersUSProviderMetadata.java @@ -28,6 +28,7 @@ import java.util.Properties; import org.jclouds.openstack.keystone.v2_0.config.KeystoneAuthenticationModule.ZoneModule; import org.jclouds.openstack.nova.v2_0.NovaApiMetadata; +import org.jclouds.openstack.nova.v2_0.config.NovaParserModule; import org.jclouds.openstack.nova.v2_0.config.NovaRestClientModule; import org.jclouds.providers.ProviderMetadata; import org.jclouds.providers.internal.BaseProviderMetadata; @@ -89,6 +90,7 @@ public class CloudServersUSProviderMetadata extends BaseProviderMetadata { .defaultModules(ImmutableSet.>builder() .add(CloudIdentityAuthenticationModule.class) .add(ZoneModule.class) + .add(NovaParserModule.class) .add(NovaRestClientModule.class) .add(CloudServersUSComputeServiceContextModule.class).build()) .build()) diff --git a/providers/rackspace-cloudservers-us/src/test/java/org/jclouds/rackspace/cloudservers/us/CloudServersUSProviderMetadataExpectTest.java b/providers/rackspace-cloudservers-us/src/test/java/org/jclouds/rackspace/cloudservers/us/CloudServersUSProviderMetadataExpectTest.java new file mode 100644 index 0000000000..e3d5df400f --- /dev/null +++ b/providers/rackspace-cloudservers-us/src/test/java/org/jclouds/rackspace/cloudservers/us/CloudServersUSProviderMetadataExpectTest.java @@ -0,0 +1,64 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.rackspace.cloudservers.us; + +import static org.testng.Assert.assertEquals; + +import org.jclouds.http.HttpRequest; +import org.jclouds.http.HttpResponse; +import org.jclouds.openstack.nova.v2_0.NovaApi; +import org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiExpectTest; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableSet; + +/** + * This test ensures that the wiring in {@link CloudServersUSProviderMetadata} is correct. + * + * @author Adrian Cole + */ +@Test(groups = "unit", testName = "CloudServersUSProviderMetadataExpectTest") +public class CloudServersUSProviderMetadataExpectTest extends BaseNovaApiExpectTest { + + public CloudServersUSProviderMetadataExpectTest() { + this.provider = "rackspace-cloudservers-us"; + this.identity = "myUsername"; + this.credential = "myApiKey"; + } + + public void testCanGetConfiguredZones() { + + HttpRequest authenticate = HttpRequest.builder().method("POST") + .endpoint("https://identity.api.rackspacecloud.com/v2.0/tokens") + .addHeader("Accept", "application/json") + .payload(payloadFromStringWithContentType( + "{\"auth\":{\"RAX-KSKEY:apiKeyCredentials\":{\"username\":\"myUsername\",\"apiKey\":\"myApiKey\"}}}" + , "application/json")).build(); + + + HttpResponse authenticationResponse = HttpResponse.builder().statusCode(200) + .payload(payloadFromResourceWithContentType("/access_rax_us.json", "application/json")).build(); + + NovaApi whenNovaRegionExists = requestSendsResponse(authenticate, authenticationResponse); + + assertEquals(whenNovaRegionExists.getConfiguredZones(), ImmutableSet.of("ORD", "DFW")); + + } + +} diff --git a/providers/rackspace-cloudservers-us/src/test/resources/access_rax_us.json b/providers/rackspace-cloudservers-us/src/test/resources/access_rax_us.json new file mode 100644 index 0000000000..a8399465c6 --- /dev/null +++ b/providers/rackspace-cloudservers-us/src/test/resources/access_rax_us.json @@ -0,0 +1 @@ +{"access":{"token":{"id":"myToken","expires":"2012-09-30T17:15:32.000-05:00","tenant":{"id":"717071","name":"717071"}},"serviceCatalog":[{"endpoints":[{"tenantId":"717071","publicURL":"https:\/\/dns.api.rackspacecloud.com\/v1.0\/717071"}],"name":"cloudDNS","type":"rax:dns"},{"endpoints":[{"tenantId":"717071","publicURL":"https:\/\/monitoring.api.rackspacecloud.com\/v1.0\/717071"}],"name":"cloudMonitoring","type":"rax:monitor"},{"endpoints":[{"region":"DFW","tenantId":"717071","publicURL":"https:\/\/dfw.servers.api.rackspacecloud.com\/v2\/717071","versionInfo":"https:\/\/dfw.servers.api.rackspacecloud.com\/v2","versionList":"https:\/\/dfw.servers.api.rackspacecloud.com\/","versionId":"2"},{"region":"ORD","tenantId":"717071","publicURL":"https:\/\/ord.servers.api.rackspacecloud.com\/v2\/717071","versionInfo":"https:\/\/ord.servers.api.rackspacecloud.com\/v2","versionList":"https:\/\/ord.servers.api.rackspacecloud.com\/","versionId":"2"}],"name":"cloudServersOpenStack","type":"compute"},{"endpoints":[{"region":"ORD","tenantId":"717071","publicURL":"https:\/\/ord.loadbalancers.api.rackspacecloud.com\/v1.0\/717071"},{"region":"DFW","tenantId":"717071","publicURL":"https:\/\/dfw.loadbalancers.api.rackspacecloud.com\/v1.0\/717071"}],"name":"cloudLoadBalancers","type":"rax:load-balancer"},{"endpoints":[{"region":"DFW","tenantId":"717071","publicURL":"https:\/\/dfw.databases.api.rackspacecloud.com\/v1.0\/717071"},{"region":"ORD","tenantId":"717071","publicURL":"https:\/\/ord.databases.api.rackspacecloud.com\/v1.0\/717071"}],"name":"cloudDatabases","type":"rax:database"},{"endpoints":[{"region":"DFW","tenantId":"MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9","publicURL":"https:\/\/storage101.dfw1.clouddrive.com\/v1\/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9","internalURL":"https:\/\/snet-storage101.dfw1.clouddrive.com\/v1\/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9"},{"region":"ORD","tenantId":"MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9","publicURL":"https:\/\/storage101.ord1.clouddrive.com\/v1\/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9","internalURL":"https:\/\/snet-storage101.ord1.clouddrive.com\/v1\/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9"}],"name":"cloudFiles","type":"object-store"},{"endpoints":[{"region":"DFW","tenantId":"MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9","publicURL":"https:\/\/cdn1.clouddrive.com\/v1\/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9"},{"region":"ORD","tenantId":"MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9","publicURL":"https:\/\/cdn2.clouddrive.com\/v1\/MossoCloudFS_5bcf396e-39dd-45ff-93a1-712b9aba90a9"}],"name":"cloudFilesCDN","type":"rax:object-cdn"},{"endpoints":[{"tenantId":"717071","publicURL":"https:\/\/servers.api.rackspacecloud.com\/v1.0\/717071","versionInfo":"https:\/\/servers.api.rackspacecloud.com\/v1.0","versionList":"https:\/\/servers.api.rackspacecloud.com\/","versionId":"1.0"}],"name":"cloudServers","type":"compute"},{"endpoints":[{"region":"DFW","tenantId":"717071","publicURL":"https:\/\/dfw.blockstorage.api.rackspacecloud.com\/v1\/717071"}],"name":"cloudBlockStorage","type":"volume"}],"user":{"id":"224085","roles":[{"id":"3","description":"User Admin Role.","name":"identity:user-admin"}],"name":"myUsername","RAX-AUTH:defaultRegion":"DFW"}}} \ No newline at end of file diff --git a/providers/rimuhosting/pom.xml b/providers/rimuhosting/pom.xml index 7ecbb094bb..00cc51a042 100644 --- a/providers/rimuhosting/pom.xml +++ b/providers/rimuhosting/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider diff --git a/providers/rimuhosting/src/test/java/org/jclouds/rimuhosting/miro/RimuHostingClientLiveTest.java b/providers/rimuhosting/src/test/java/org/jclouds/rimuhosting/miro/RimuHostingClientLiveTest.java index 388cabd63a..f54d2acedf 100644 --- a/providers/rimuhosting/src/test/java/org/jclouds/rimuhosting/miro/RimuHostingClientLiveTest.java +++ b/providers/rimuhosting/src/test/java/org/jclouds/rimuhosting/miro/RimuHostingClientLiveTest.java @@ -20,7 +20,7 @@ package org.jclouds.rimuhosting.miro; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertTrue; +import static org.testng.Assert.fail; import java.util.Set; @@ -66,11 +66,10 @@ public class RimuHostingClientLiveTest Set plans = connection.getPricingPlanList(); for (PricingPlan plan : plans) { if (plan.getId().equalsIgnoreCase("MIRO4B")) { - assertTrue(true); return; } } - assertTrue(false); + fail("MIRO4B not found"); } @Test @@ -78,11 +77,10 @@ public class RimuHostingClientLiveTest Set images = connection.getImageList(); for (Image image : images) { if (image.getId().equalsIgnoreCase("lenny")) { - assertTrue(true); return; } } - assertTrue(false, "lenny not found"); + fail("lenny not found"); } @Test diff --git a/providers/serverlove-z1-man/pom.xml b/providers/serverlove-z1-man/pom.xml index 4b0ef8a8c6..2ba3bfc796 100644 --- a/providers/serverlove-z1-man/pom.xml +++ b/providers/serverlove-z1-man/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider diff --git a/providers/skalicloud-sdg-my/pom.xml b/providers/skalicloud-sdg-my/pom.xml index e1b38fa4ce..23e51e6f49 100644 --- a/providers/skalicloud-sdg-my/pom.xml +++ b/providers/skalicloud-sdg-my/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider diff --git a/providers/slicehost/pom.xml b/providers/slicehost/pom.xml index 80f8a67767..56cd1a2426 100644 --- a/providers/slicehost/pom.xml +++ b/providers/slicehost/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider diff --git a/providers/softlayer/pom.xml b/providers/softlayer/pom.xml index 9ddb6e2b76..3e061dabae 100644 --- a/providers/softlayer/pom.xml +++ b/providers/softlayer/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider diff --git a/providers/stratogen-vcloud-mycloud/pom.xml b/providers/stratogen-vcloud-mycloud/pom.xml index 5f80ed3aad..3ab7f848a2 100644 --- a/providers/stratogen-vcloud-mycloud/pom.xml +++ b/providers/stratogen-vcloud-mycloud/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider diff --git a/providers/synaptic-storage/pom.xml b/providers/synaptic-storage/pom.xml index 3e1ed7c8ac..1a2b50f202 100644 --- a/providers/synaptic-storage/pom.xml +++ b/providers/synaptic-storage/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider diff --git a/providers/synaptic-storage/src/test/java/org/jclouds/synaptic/storage/SynapticStorageClientLiveTest.java b/providers/synaptic-storage/src/test/java/org/jclouds/synaptic/storage/SynapticStorageClientLiveTest.java index dd9dfd7744..c8359f08de 100644 --- a/providers/synaptic-storage/src/test/java/org/jclouds/synaptic/storage/SynapticStorageClientLiveTest.java +++ b/providers/synaptic-storage/src/test/java/org/jclouds/synaptic/storage/SynapticStorageClientLiveTest.java @@ -29,4 +29,7 @@ import org.testng.annotations.Test; @Test(groups = "live", sequential = true, testName = "SynapticStorageClientLiveTest") public class SynapticStorageClientLiveTest extends AtmosClientLiveTest { + public SynapticStorageClientLiveTest() { + provider = "synaptic-storage"; + } } diff --git a/providers/trmk-ecloud/pom.xml b/providers/trmk-ecloud/pom.xml index f38b244936..a2e7ad572a 100644 --- a/providers/trmk-ecloud/pom.xml +++ b/providers/trmk-ecloud/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider diff --git a/providers/trmk-vcloudexpress/pom.xml b/providers/trmk-vcloudexpress/pom.xml index df454c230a..8dfe34772b 100644 --- a/providers/trmk-vcloudexpress/pom.xml +++ b/providers/trmk-vcloudexpress/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider diff --git a/providers/trystack-nova/pom.xml b/providers/trystack-nova/pom.xml index 7de9fd5d95..27206c4945 100644 --- a/providers/trystack-nova/pom.xml +++ b/providers/trystack-nova/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider @@ -76,6 +76,13 @@ test-jar test + + org.jclouds.api + openstack-keystone + ${project.version} + test-jar + test + org.jclouds.driver jclouds-slf4j diff --git a/providers/trystack-nova/src/main/java/org/jclouds/trystack/nova/TryStackNovaProviderMetadata.java b/providers/trystack-nova/src/main/java/org/jclouds/trystack/nova/TryStackNovaProviderMetadata.java index fa58662f01..206f1d2697 100644 --- a/providers/trystack-nova/src/main/java/org/jclouds/trystack/nova/TryStackNovaProviderMetadata.java +++ b/providers/trystack-nova/src/main/java/org/jclouds/trystack/nova/TryStackNovaProviderMetadata.java @@ -24,7 +24,10 @@ import static org.jclouds.openstack.nova.v2_0.config.NovaProperties.AUTO_GENERAT import java.net.URI; import java.util.Properties; +import org.jclouds.openstack.keystone.v2_0.config.KeystoneAuthenticationModule; +import org.jclouds.openstack.keystone.v2_0.config.KeystoneAuthenticationModule.ZoneModule; import org.jclouds.openstack.nova.v2_0.NovaApiMetadata; +import org.jclouds.openstack.nova.v2_0.config.NovaParserModule; import org.jclouds.openstack.nova.v2_0.config.NovaRestClientModule; import org.jclouds.providers.ProviderMetadata; import org.jclouds.providers.internal.BaseProviderMetadata; @@ -74,7 +77,12 @@ public class TryStackNovaProviderMetadata extends BaseProviderMetadata { .name("TryStack.org (Nova)") .apiMetadata( new NovaApiMetadata().toBuilder() - .defaultModules(ImmutableSet.>of(NovaRestClientModule.class, TryStackNovaServiceContextModule.class)) + .defaultModules(ImmutableSet.>builder() + .add(KeystoneAuthenticationModule.class) + .add(ZoneModule.class) + .add(NovaParserModule.class) + .add(NovaRestClientModule.class) + .add(TryStackNovaServiceContextModule.class).build()) .build()) .homepage(URI.create("https://trystack.org")) .console(URI.create("https://trystack.org/dash")) diff --git a/providers/trystack-nova/src/test/java/org/jclouds/trystack/nova/TryStackNovaProviderMetadataExpectTest.java b/providers/trystack-nova/src/test/java/org/jclouds/trystack/nova/TryStackNovaProviderMetadataExpectTest.java new file mode 100644 index 0000000000..83a356b470 --- /dev/null +++ b/providers/trystack-nova/src/test/java/org/jclouds/trystack/nova/TryStackNovaProviderMetadataExpectTest.java @@ -0,0 +1,64 @@ +/** + * Licensed to jclouds, Inc. (jclouds) under one or more + * contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. jclouds licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.jclouds.trystack.nova; + +import static org.testng.Assert.assertEquals; + +import org.jclouds.http.HttpRequest; +import org.jclouds.http.HttpResponse; +import org.jclouds.openstack.nova.v2_0.NovaApi; +import org.jclouds.openstack.nova.v2_0.internal.BaseNovaApiExpectTest; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableSet; + +/** + * This test ensures that the wiring in {@link TryStackNovaProviderMetadata} is correct. + * + * @author Adrian Cole + */ +@Test(groups = "unit", testName = "TryStackNovaProviderMetadataExpectTest") +public class TryStackNovaProviderMetadataExpectTest extends BaseNovaApiExpectTest { + + public TryStackNovaProviderMetadataExpectTest() { + this.provider = "trystack-nova"; + this.identity = "demo:demo"; + this.credential = "password"; + } + + public void testCanGetConfiguredZones() { + + HttpRequest authenticate = HttpRequest.builder().method("POST") + .endpoint("https://nova-api.trystack.org:5443/v2.0/tokens") + .addHeader("Accept", "application/json") + .payload(payloadFromStringWithContentType( + "{\"auth\":{\"passwordCredentials\":{\"username\":\"demo\",\"password\":\"password\"},\"tenantName\":\"demo\"}}" + , "application/json")).build(); + + + HttpResponse authenticationResponse = HttpResponse.builder().statusCode(200) + .payload(payloadFromResourceWithContentType("/access_trystack.json", "application/json")).build(); + + NovaApi whenNovaRegionExists = requestSendsResponse(authenticate, authenticationResponse); + + assertEquals(whenNovaRegionExists.getConfiguredZones(), ImmutableSet.of("RegionOne")); + + } + +} diff --git a/providers/trystack-nova/src/test/resources/access_trystack.json b/providers/trystack-nova/src/test/resources/access_trystack.json new file mode 100644 index 0000000000..27844f2fd8 --- /dev/null +++ b/providers/trystack-nova/src/test/resources/access_trystack.json @@ -0,0 +1,49 @@ +{ + "access": { + "token": { + "expires": "2012-03-23T21:44:09", + "id": "Auth_4f173437e4b013bee56d1007", + "tenant": { + "id": "3456", + "name": "508151008" + } + }, + "serviceCatalog": [{ + "endpoints": [{ + "adminURL": "https://nova-api.trystack.org:9774/v1.1/3456", + "region": "RegionOne", + "internalURL": "https://nova-api.trystack.org:9774/v1.1/3456", + "publicURL": "https://nova-api.trystack.org:9774/v1.1/3456" + }], + "type": "compute", + "name": "nova" + }, { + "endpoints": [{ + "adminURL": "https://GLANCE_API_IS_NOT_DISCLOSED/v1.1/3456", + "region": "RegionOne", + "internalURL": "https://GLANCE_API_IS_NOT_DISCLOSED/v1.1/3456", + "publicURL": "https://GLANCE_API_IS_NOT_DISCLOSED/v1.1/3456" + }], + "type": "image", + "name": "glance" + }, { + "endpoints": [{ + "adminURL": "https://nova-api.trystack.org:5443/v2.0", + "region": "RegionOne", + "internalURL": "https://keystone.thefreecloud.org:5000/v2.0", + "publicURL": "https://keystone.thefreecloud.org:5000/v2.0" + }], + "type": "identity", + "name": "keystone" + }], + "user": { + "id": "43", + "roles": [{ + "tenantId": "3456", + "id": "2", + "name": "Member" + }], + "name": "508151008" + } + } +} \ No newline at end of file diff --git a/resources/NOTICE.txt b/resources/NOTICE.txt index b0a56c74b6..ab77979e5b 100644 --- a/resources/NOTICE.txt +++ b/resources/NOTICE.txt @@ -64,3 +64,9 @@ distributed in the Public Domain This product includes software developed at Hewlett-Packard Copyright (c) 2011-2012 Hewlett-Packard Development Company, L.P +This product includes software developed at Cloudsoft +Copyright (c) 2011-2012 Cloudsoft Corporation, Ltd. + +This product includes software developed at MuleSoft +Copyright (c) 2012 MuleSoft Inc. + diff --git a/resources/pom.xml b/resources/pom.xml index 7569bc42f6..80811f07c6 100644 --- a/resources/pom.xml +++ b/resources/pom.xml @@ -24,7 +24,7 @@ jclouds-project org.jclouds - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../project/pom.xml jclouds-resources @@ -46,7 +46,7 @@ maven-remote-resources-plugin - 1.2.1 + 1.3 bundle-remote-resources diff --git a/sandbox-apis/libvirt/pom.xml b/sandbox-apis/libvirt/pom.xml index c0dc683524..063ca5c661 100644 --- a/sandbox-apis/libvirt/pom.xml +++ b/sandbox-apis/libvirt/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.api diff --git a/sandbox-apis/nirvanix/pom.xml b/sandbox-apis/nirvanix/pom.xml index cbd62be6da..aae978496a 100644 --- a/sandbox-apis/nirvanix/pom.xml +++ b/sandbox-apis/nirvanix/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider diff --git a/sandbox-apis/pcs/pom.xml b/sandbox-apis/pcs/pom.xml index 5cd1aa41ea..2906511dc6 100644 --- a/sandbox-apis/pcs/pom.xml +++ b/sandbox-apis/pcs/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.api diff --git a/sandbox-apis/scality-rs2/pom.xml b/sandbox-apis/scality-rs2/pom.xml index 3b42c76c5e..8b50aced34 100644 --- a/sandbox-apis/scality-rs2/pom.xml +++ b/sandbox-apis/scality-rs2/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.api diff --git a/sandbox-apis/simpledb/pom.xml b/sandbox-apis/simpledb/pom.xml index ae47dfba99..67f827671e 100644 --- a/sandbox-apis/simpledb/pom.xml +++ b/sandbox-apis/simpledb/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.api diff --git a/sandbox-apis/simpledb/src/test/java/org/jclouds/simpledb/options/ListDomainsOptionsTest.java b/sandbox-apis/simpledb/src/test/java/org/jclouds/simpledb/options/ListDomainsOptionsTest.java index 880b92981f..e6c6de3eef 100644 --- a/sandbox-apis/simpledb/src/test/java/org/jclouds/simpledb/options/ListDomainsOptionsTest.java +++ b/sandbox-apis/simpledb/src/test/java/org/jclouds/simpledb/options/ListDomainsOptionsTest.java @@ -22,8 +22,6 @@ import static org.jclouds.simpledb.options.ListDomainsOptions.Builder.maxNumberO import static org.jclouds.simpledb.options.ListDomainsOptions.Builder.nextToken; import static org.testng.Assert.assertEquals; -import java.util.Collections; - import org.jclouds.http.options.HttpRequestOptions; import org.testng.annotations.Test; @@ -44,19 +42,19 @@ public class ListDomainsOptionsTest { public void testNextToken() { ListDomainsOptions options = new ListDomainsOptions(); options.nextToken("test"); - assertEquals(options.buildFormParameters().get("NextToken"), Collections.singletonList("test")); + assertEquals(options.buildFormParameters().get("NextToken"), ImmutableList.of("test")); } @Test public void testNullNextToken() { ListDomainsOptions options = new ListDomainsOptions(); - assertEquals(options.buildFormParameters().get("NextToken"), Collections.EMPTY_LIST); + assertEquals(options.buildFormParameters().get("NextToken"), ImmutableList.of()); } @Test public void testNextTokenStatic() { ListDomainsOptions options = nextToken("test"); - assertEquals(options.buildFormParameters().get("NextToken"), Collections.singletonList("test")); + assertEquals(options.buildFormParameters().get("NextToken"), ImmutableList.of("test")); } public void testInvalidMaxNumberOfDomainsZero() { @@ -71,19 +69,19 @@ public class ListDomainsOptionsTest { public void testMaxNumberOfDomains() { ListDomainsOptions options = new ListDomainsOptions(); options.maxNumberOfDomains(1); - assertEquals(options.buildFormParameters().get("MaxNumberOfDomains"), Collections.singletonList("1")); + assertEquals(options.buildFormParameters().get("MaxNumberOfDomains"), ImmutableList.of("1")); } @Test public void testNullMaxNumberOfDomains() { ListDomainsOptions options = new ListDomainsOptions(); - assertEquals(options.buildFormParameters().get("MaxNumberOfDomains"), Collections.EMPTY_LIST); + assertEquals(options.buildFormParameters().get("MaxNumberOfDomains"), ImmutableList.of()); } @Test public void testMaxNumberOfDomainsStatic() { ListDomainsOptions options = maxNumberOfDomains(1); - assertEquals(options.buildFormParameters().get("MaxNumberOfDomains"), Collections.singletonList("1")); + assertEquals(options.buildFormParameters().get("MaxNumberOfDomains"), ImmutableList.of("1")); } } diff --git a/sandbox-drivers/asynchttpclient/pom.xml b/sandbox-drivers/asynchttpclient/pom.xml index db2faa9c74..7c9f963881 100644 --- a/sandbox-drivers/asynchttpclient/pom.xml +++ b/sandbox-drivers/asynchttpclient/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.driver diff --git a/sandbox-providers/aws-simpledb/pom.xml b/sandbox-providers/aws-simpledb/pom.xml index 401013b7f0..425570058a 100644 --- a/sandbox-providers/aws-simpledb/pom.xml +++ b/sandbox-providers/aws-simpledb/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider diff --git a/sandbox-providers/azurequeue/pom.xml b/sandbox-providers/azurequeue/pom.xml index d307069c03..cc60f8c4e5 100644 --- a/sandbox-providers/azurequeue/pom.xml +++ b/sandbox-providers/azurequeue/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider diff --git a/sandbox-providers/azurequeue/src/main/java/org/jclouds/azurequeue/options/GetOptions.java b/sandbox-providers/azurequeue/src/main/java/org/jclouds/azurequeue/options/GetOptions.java index a2af6a3cdb..8dd4435a28 100644 --- a/sandbox-providers/azurequeue/src/main/java/org/jclouds/azurequeue/options/GetOptions.java +++ b/sandbox-providers/azurequeue/src/main/java/org/jclouds/azurequeue/options/GetOptions.java @@ -20,8 +20,6 @@ package org.jclouds.azurequeue.options; import static com.google.common.base.Preconditions.checkArgument; -import java.util.Collections; - import org.jclouds.http.options.BaseHttpRequestOptions; /** @@ -51,7 +49,7 @@ public class GetOptions extends BaseHttpRequestOptions { */ public GetOptions maxMessages(int count) { checkArgument(count > 0&& count <= 32, "count must be a positive number; max 32"); - queryParameters.replaceValues("numofmessages", Collections.singletonList(count + "")); + queryParameters.replaceValues("numofmessages", ImmutableList.of(count + "")); return this; } @@ -62,7 +60,7 @@ public class GetOptions extends BaseHttpRequestOptions { public GetOptions visibilityTimeout(int timeout) { checkArgument(timeout > 0 && timeout <= 2 * 60 * 60, "timeout is in seconds; must be positive and maximum 2 hours"); - queryParameters.replaceValues("visibilitytimeout", Collections.singletonList(timeout + "")); + queryParameters.replaceValues("visibilitytimeout", ImmutableList.of(timeout + "")); return this; } diff --git a/sandbox-providers/boxdotnet/pom.xml b/sandbox-providers/boxdotnet/pom.xml index e6deb79311..722f7f5233 100644 --- a/sandbox-providers/boxdotnet/pom.xml +++ b/sandbox-providers/boxdotnet/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider diff --git a/sandbox-providers/dunkel-vcd/pom.xml b/sandbox-providers/dunkel-vcd/pom.xml index 8c234c1d58..ea1d6b80d1 100644 --- a/sandbox-providers/dunkel-vcd/pom.xml +++ b/sandbox-providers/dunkel-vcd/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider diff --git a/sandbox-providers/googlestorage/pom.xml b/sandbox-providers/googlestorage/pom.xml index aa97217078..7b9d82c96a 100644 --- a/sandbox-providers/googlestorage/pom.xml +++ b/sandbox-providers/googlestorage/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider diff --git a/sandbox-providers/hosteurope-storage/pom.xml b/sandbox-providers/hosteurope-storage/pom.xml index b31e1ce1ed..665657ac20 100644 --- a/sandbox-providers/hosteurope-storage/pom.xml +++ b/sandbox-providers/hosteurope-storage/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider diff --git a/sandbox-providers/ibm-smartcloud/pom.xml b/sandbox-providers/ibm-smartcloud/pom.xml index af0159ee8c..0a86b4758a 100644 --- a/sandbox-providers/ibm-smartcloud/pom.xml +++ b/sandbox-providers/ibm-smartcloud/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider diff --git a/sandbox-providers/scaleup-storage/pom.xml b/sandbox-providers/scaleup-storage/pom.xml index 32b72486fb..942ab4f411 100644 --- a/sandbox-providers/scaleup-storage/pom.xml +++ b/sandbox-providers/scaleup-storage/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider diff --git a/sandbox-providers/tiscali-storage/pom.xml b/sandbox-providers/tiscali-storage/pom.xml index 5630a8eb8e..1404404194 100644 --- a/sandbox-providers/tiscali-storage/pom.xml +++ b/sandbox-providers/tiscali-storage/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider diff --git a/sandbox-providers/twitter/pom.xml b/sandbox-providers/twitter/pom.xml index fbe0a8cee4..d3a4ee4e92 100644 --- a/sandbox-providers/twitter/pom.xml +++ b/sandbox-providers/twitter/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider diff --git a/sandbox-providers/virtacore-publiccloud-lax/pom.xml b/sandbox-providers/virtacore-publiccloud-lax/pom.xml index e41a96159c..805c16f35d 100644 --- a/sandbox-providers/virtacore-publiccloud-lax/pom.xml +++ b/sandbox-providers/virtacore-publiccloud-lax/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.provider diff --git a/scriptbuilder/pom.xml b/scriptbuilder/pom.xml index d8d48d7b6b..b4cb038002 100644 --- a/scriptbuilder/pom.xml +++ b/scriptbuilder/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../project/pom.xml jclouds-scriptbuilder diff --git a/scriptbuilder/src/main/java/org/jclouds/scriptbuilder/domain/AppendFile.java b/scriptbuilder/src/main/java/org/jclouds/scriptbuilder/domain/AppendFile.java index 8fd534c7f5..3a88594a2f 100644 --- a/scriptbuilder/src/main/java/org/jclouds/scriptbuilder/domain/AppendFile.java +++ b/scriptbuilder/src/main/java/org/jclouds/scriptbuilder/domain/AppendFile.java @@ -22,7 +22,6 @@ import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static org.jclouds.scriptbuilder.domain.Statements.interpret; -import java.util.Collections; import java.util.Map; import java.util.Map.Entry; @@ -115,7 +114,7 @@ public class AppendFile implements Statement { @Override public Iterable functionDependencies(OsFamily family) { - return Collections.emptyList(); + return ImmutableList.of(); } @Override diff --git a/scriptbuilder/src/main/java/org/jclouds/scriptbuilder/domain/CreateRunScript.java b/scriptbuilder/src/main/java/org/jclouds/scriptbuilder/domain/CreateRunScript.java index 50ef817ac5..18a70a175b 100644 --- a/scriptbuilder/src/main/java/org/jclouds/scriptbuilder/domain/CreateRunScript.java +++ b/scriptbuilder/src/main/java/org/jclouds/scriptbuilder/domain/CreateRunScript.java @@ -28,7 +28,6 @@ import static org.jclouds.scriptbuilder.domain.Statements.createOrOverwriteFile; import static org.jclouds.scriptbuilder.domain.Statements.exec; import static org.jclouds.scriptbuilder.domain.Statements.interpret; -import java.util.Collections; import java.util.List; import java.util.Map; @@ -40,8 +39,8 @@ import com.google.common.base.Function; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Iterables; import com.google.common.collect.ImmutableList.Builder; +import com.google.common.collect.Iterables; /** * Creates a run script @@ -83,7 +82,7 @@ public class CreateRunScript extends StatementList { @Override public Iterable functionDependencies(OsFamily family) { - return Collections.emptyList(); + return ImmutableList.of(); } @Override @@ -95,7 +94,7 @@ public class CreateRunScript extends StatementList { @Override public Iterable functionDependencies(OsFamily family) { - return Collections.emptyList(); + return ImmutableList.of(); } @Override diff --git a/scriptbuilder/src/main/java/org/jclouds/scriptbuilder/functionloader/BasicFunctionLoader.java b/scriptbuilder/src/main/java/org/jclouds/scriptbuilder/functionloader/BasicFunctionLoader.java index da1f788985..fdc0c80c02 100644 --- a/scriptbuilder/src/main/java/org/jclouds/scriptbuilder/functionloader/BasicFunctionLoader.java +++ b/scriptbuilder/src/main/java/org/jclouds/scriptbuilder/functionloader/BasicFunctionLoader.java @@ -19,7 +19,6 @@ package org.jclouds.scriptbuilder.functionloader; import com.google.common.base.Charsets; -import com.google.common.io.CharStreams; import com.google.common.io.Resources; import org.jclouds.scriptbuilder.domain.OsFamily; import org.jclouds.scriptbuilder.domain.ShellToken; @@ -46,9 +45,9 @@ public enum BasicFunctionLoader implements FunctionLoader { @Override public String loadFunction(String function, OsFamily family) throws FunctionNotFoundException { try { - return CharStreams.toString(Resources.newReaderSupplier(ClassLoadingUtils.loadResource( + return Resources.toString(ClassLoadingUtils.loadResource( BasicFunctionLoader.class, String.format("/functions/%s.%s", function, ShellToken.SH.to(family))), - Charsets.UTF_8)); + Charsets.UTF_8); } catch (IOException e) { throw new FunctionNotFoundException(function, family, e); } diff --git a/scriptbuilder/src/main/java/org/jclouds/scriptbuilder/functionloader/osgi/BundleFunctionLoader.java b/scriptbuilder/src/main/java/org/jclouds/scriptbuilder/functionloader/osgi/BundleFunctionLoader.java index eb7e510d6f..1fc2791f8b 100644 --- a/scriptbuilder/src/main/java/org/jclouds/scriptbuilder/functionloader/osgi/BundleFunctionLoader.java +++ b/scriptbuilder/src/main/java/org/jclouds/scriptbuilder/functionloader/osgi/BundleFunctionLoader.java @@ -32,7 +32,6 @@ import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceRegistration; import com.google.common.base.Charsets; -import com.google.common.io.CharStreams; import com.google.common.io.Resources; /** @@ -93,8 +92,8 @@ public class BundleFunctionLoader implements FunctionLoader { @Override public String loadFunction(String function, OsFamily family) throws FunctionNotFoundException { try { - return CharStreams.toString(Resources.newReaderSupplier(bundleContext.getBundle().getResource( - String.format("/functions/%s.%s", function, ShellToken.SH.to(family))), Charsets.UTF_8)); + return Resources.toString(bundleContext.getBundle().getResource( + String.format("/functions/%s.%s", function, ShellToken.SH.to(family))), Charsets.UTF_8); } catch (IOException e) { throw new FunctionNotFoundException(function, family, e); } diff --git a/scriptbuilder/src/main/java/org/jclouds/scriptbuilder/statements/ssh/AuthorizeRSAPublicKeys.java b/scriptbuilder/src/main/java/org/jclouds/scriptbuilder/statements/ssh/AuthorizeRSAPublicKeys.java index fabf96a37a..85af288628 100644 --- a/scriptbuilder/src/main/java/org/jclouds/scriptbuilder/statements/ssh/AuthorizeRSAPublicKeys.java +++ b/scriptbuilder/src/main/java/org/jclouds/scriptbuilder/statements/ssh/AuthorizeRSAPublicKeys.java @@ -22,7 +22,6 @@ import static com.google.common.base.Preconditions.checkNotNull; import static org.jclouds.scriptbuilder.domain.Statements.appendFile; import static org.jclouds.scriptbuilder.domain.Statements.exec; -import java.util.Collections; import java.util.List; import org.jclouds.scriptbuilder.domain.OsFamily; @@ -53,7 +52,7 @@ public class AuthorizeRSAPublicKeys implements Statement { @Override public Iterable functionDependencies(OsFamily family) { - return Collections.emptyList(); + return ImmutableList.of(); } @Override diff --git a/scriptbuilder/src/main/java/org/jclouds/scriptbuilder/statements/ssh/InstallRSAPrivateKey.java b/scriptbuilder/src/main/java/org/jclouds/scriptbuilder/statements/ssh/InstallRSAPrivateKey.java index 4a999e9131..40c55620b9 100644 --- a/scriptbuilder/src/main/java/org/jclouds/scriptbuilder/statements/ssh/InstallRSAPrivateKey.java +++ b/scriptbuilder/src/main/java/org/jclouds/scriptbuilder/statements/ssh/InstallRSAPrivateKey.java @@ -22,8 +22,6 @@ import static com.google.common.base.Preconditions.checkNotNull; import static org.jclouds.scriptbuilder.domain.Statements.appendFile; import static org.jclouds.scriptbuilder.domain.Statements.exec; -import java.util.Collections; - import org.jclouds.scriptbuilder.domain.OsFamily; import org.jclouds.scriptbuilder.domain.Statement; import org.jclouds.scriptbuilder.domain.StatementList; @@ -51,7 +49,7 @@ public class InstallRSAPrivateKey implements Statement { @Override public Iterable functionDependencies(OsFamily family) { - return Collections.emptyList(); + return ImmutableList.of(); } @Override diff --git a/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/EnvBuilderTest.java b/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/EnvBuilderTest.java index b574989b9f..5a56233644 100644 --- a/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/EnvBuilderTest.java +++ b/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/EnvBuilderTest.java @@ -29,7 +29,6 @@ import org.testng.annotations.Test; import com.google.common.base.Charsets; import com.google.common.collect.ImmutableMap; -import com.google.common.io.CharStreams; import com.google.common.io.Resources; /** @@ -44,16 +43,16 @@ public class EnvBuilderTest { @Test public void testBuildSimpleWindows() throws MalformedURLException, IOException { - assertEquals(testScriptBuilder.build(OsFamily.WINDOWS), CharStreams.toString(Resources - .newReaderSupplier(Resources.getResource("test_env." - + ShellToken.SH.to(OsFamily.WINDOWS)), Charsets.UTF_8))); + assertEquals(testScriptBuilder.build(OsFamily.WINDOWS), + Resources.toString(Resources.getResource("test_env." + + ShellToken.SH.to(OsFamily.WINDOWS)), Charsets.UTF_8)); } @Test public void testBuildSimpleUNIX() throws MalformedURLException, IOException { - assertEquals(testScriptBuilder.build(OsFamily.UNIX), CharStreams.toString(Resources - .newReaderSupplier(Resources.getResource("test_env." - + ShellToken.SH.to(OsFamily.UNIX)), Charsets.UTF_8))); + assertEquals(testScriptBuilder.build(OsFamily.UNIX), + Resources.toString(Resources.getResource("test_env." + + ShellToken.SH.to(OsFamily.UNIX)), Charsets.UTF_8)); } @Test diff --git a/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/InitBuilderTest.java b/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/InitBuilderTest.java index d2274ebdb1..ce12b926bc 100644 --- a/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/InitBuilderTest.java +++ b/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/InitBuilderTest.java @@ -34,7 +34,6 @@ import org.testng.annotations.Test; import com.google.common.base.Charsets; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; -import com.google.common.io.CharStreams; import com.google.common.io.Resources; /** @@ -59,8 +58,7 @@ public class InitBuilderTest { public void testBuildSimpleUNIX() throws MalformedURLException, IOException { assertEquals( testInitBuilder.render(OsFamily.UNIX), - CharStreams.toString(Resources.newReaderSupplier( - Resources.getResource("test_init." + ShellToken.SH.to(OsFamily.UNIX)), Charsets.UTF_8))); + Resources.toString(Resources.getResource("test_init." + ShellToken.SH.to(OsFamily.UNIX)), Charsets.UTF_8)); } @Test @@ -93,7 +91,6 @@ public class InitBuilderTest { "du -sk {varl}EBS_MOUNT_POINT{varr}", "echo size of source", "du -sk {varl}IMAGE_DIR{varr}", "rm -rf {varl}IMAGE_DIR{varr}/*", "umount {varl}EBS_MOUNT_POINT{varr}", "echo ----COMPLETE----"))).render(OsFamily.UNIX), - CharStreams.toString(Resources.newReaderSupplier( - Resources.getResource("test_ebs." + ShellToken.SH.to(OsFamily.UNIX)), Charsets.UTF_8))); + Resources.toString(Resources.getResource("test_ebs." + ShellToken.SH.to(OsFamily.UNIX)), Charsets.UTF_8)); } } diff --git a/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/InitScriptTest.java b/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/InitScriptTest.java index 51e407b5a2..fa80a8827b 100644 --- a/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/InitScriptTest.java +++ b/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/InitScriptTest.java @@ -34,7 +34,6 @@ import org.testng.annotations.Test; import com.google.common.base.Charsets; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; -import com.google.common.io.CharStreams; import com.google.common.io.Resources; /** @@ -54,15 +53,13 @@ public class InitScriptTest { public void testBuildSimpleWindows() throws MalformedURLException, IOException { assertEquals( testInitScript.render(OsFamily.WINDOWS), - CharStreams.toString(Resources.newReaderSupplier( - Resources.getResource("test_init." + ShellToken.SH.to(OsFamily.WINDOWS)), Charsets.UTF_8))); + Resources.toString(Resources.getResource("test_init." + ShellToken.SH.to(OsFamily.WINDOWS)), Charsets.UTF_8)); } public void testBuildSimpleUNIX() throws MalformedURLException, IOException { assertEquals( testInitScript.render(OsFamily.UNIX), - CharStreams.toString(Resources.newReaderSupplier( - Resources.getResource("test_init." + ShellToken.SH.to(OsFamily.UNIX)), Charsets.UTF_8))); + Resources.toString(Resources.getResource("test_init." + ShellToken.SH.to(OsFamily.UNIX)), Charsets.UTF_8)); } public void testBuildEBS() throws MalformedURLException, IOException { @@ -87,8 +84,7 @@ public class InitScriptTest { "du -sk {varl}EBS_MOUNT_POINT{varr}", "echo size of source", "du -sk {varl}IMAGE_DIR{varr}", "rm -rf {varl}IMAGE_DIR{varr}/*", "umount {varl}EBS_MOUNT_POINT{varr}", "echo ----COMPLETE----")).build().render(OsFamily.UNIX), - CharStreams.toString(Resources.newReaderSupplier( - Resources.getResource("test_ebs." + ShellToken.SH.to(OsFamily.UNIX)), Charsets.UTF_8))); + Resources.toString(Resources.getResource("test_ebs." + ShellToken.SH.to(OsFamily.UNIX)), Charsets.UTF_8)); } InitScript testCallInRun = InitScript.builder().name("testcall").init(exec("echo hello")) @@ -98,8 +94,7 @@ public class InitScriptTest { public void testCallInRunUNIX() throws MalformedURLException, IOException { assertEquals( testCallInRun.render(OsFamily.UNIX), - CharStreams.toString(Resources.newReaderSupplier( - Resources.getResource("test_init_script." + ShellToken.SH.to(OsFamily.UNIX)), Charsets.UTF_8))); + Resources.toString(Resources.getResource("test_init_script." + ShellToken.SH.to(OsFamily.UNIX)), Charsets.UTF_8)); } } diff --git a/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/ScriptBuilderTest.java b/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/ScriptBuilderTest.java index e5d366487b..61177e10fe 100644 --- a/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/ScriptBuilderTest.java +++ b/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/ScriptBuilderTest.java @@ -43,7 +43,6 @@ import com.google.common.base.Charsets; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; -import com.google.common.io.CharStreams; import com.google.common.io.Resources; /** @@ -72,16 +71,14 @@ public class ScriptBuilderTest { public void testBuildSimpleWindows() throws MalformedURLException, IOException { assertEquals( testScriptBuilder.render(OsFamily.WINDOWS), - CharStreams.toString(Resources.newReaderSupplier( - Resources.getResource("test_script." + ShellToken.SH.to(OsFamily.WINDOWS)), Charsets.UTF_8))); + Resources.toString(Resources.getResource("test_script." + ShellToken.SH.to(OsFamily.WINDOWS)), Charsets.UTF_8)); } @Test public void testBuildSimpleUNIX() throws MalformedURLException, IOException { assertEquals( testScriptBuilder.render(OsFamily.UNIX), - CharStreams.toString(Resources.newReaderSupplier( - Resources.getResource("test_script." + ShellToken.SH.to(OsFamily.UNIX)), Charsets.UTF_8))); + Resources.toString(Resources.getResource("test_script." + ShellToken.SH.to(OsFamily.UNIX)), Charsets.UTF_8)); } ScriptBuilder findPidBuilder = new ScriptBuilder().addStatement(findPid("{args}")).addStatement( @@ -91,32 +88,29 @@ public class ScriptBuilderTest { public void testFindPidWindows() throws MalformedURLException, IOException { assertEquals( findPidBuilder.render(OsFamily.WINDOWS), - CharStreams.toString(Resources.newReaderSupplier( - Resources.getResource("test_find_pid." + ShellToken.SH.to(OsFamily.WINDOWS)), Charsets.UTF_8))); + Resources.toString(Resources.getResource("test_find_pid." + ShellToken.SH.to(OsFamily.WINDOWS)), Charsets.UTF_8)); } @Test public void testFindPidUNIX() throws MalformedURLException, IOException { assertEquals( findPidBuilder.render(OsFamily.UNIX), - CharStreams.toString(Resources.newReaderSupplier( - Resources.getResource("test_find_pid." + ShellToken.SH.to(OsFamily.UNIX)), Charsets.UTF_8))); + Resources.toString(Resources.getResource("test_find_pid." + ShellToken.SH.to(OsFamily.UNIX)), Charsets.UTF_8)); } ScriptBuilder seekAndDestroyBuilder = new ScriptBuilder().addStatement(findPid("{args}")).addStatement(kill()); @Test public void testSeekAndDestroyWindows() throws MalformedURLException, IOException { - assertEquals(seekAndDestroyBuilder.render(OsFamily.WINDOWS), CharStreams.toString(Resources.newReaderSupplier( - Resources.getResource("test_seek_and_destroy." + ShellToken.SH.to(OsFamily.WINDOWS)), Charsets.UTF_8))); + assertEquals(seekAndDestroyBuilder.render(OsFamily.WINDOWS), Resources.toString( + Resources.getResource("test_seek_and_destroy." + ShellToken.SH.to(OsFamily.WINDOWS)), Charsets.UTF_8)); } @Test public void testSeekAndDestroyUNIX() throws MalformedURLException, IOException { assertEquals( seekAndDestroyBuilder.render(OsFamily.UNIX), - CharStreams.toString(Resources.newReaderSupplier( - Resources.getResource("test_seek_and_destroy." + ShellToken.SH.to(OsFamily.UNIX)), Charsets.UTF_8))); + Resources.toString(Resources.getResource("test_seek_and_destroy." + ShellToken.SH.to(OsFamily.UNIX)), Charsets.UTF_8)); } @Test diff --git a/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/AppendFileTest.java b/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/AppendFileTest.java index e8b6a2ec2d..f9eb7ce765 100644 --- a/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/AppendFileTest.java +++ b/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/AppendFileTest.java @@ -27,7 +27,6 @@ import org.testng.annotations.Test; import com.google.common.base.Charsets; import com.google.common.collect.ImmutableList; -import com.google.common.io.CharStreams; import com.google.common.io.Resources; /** @@ -39,13 +38,13 @@ public class AppendFileTest { "log_location STDOUT", String.format("chef_server_url \"%s\"", "http://localhost:4000"))); public void testUNIX() throws IOException { - assertEquals(statement.render(OsFamily.UNIX), CharStreams.toString(Resources.newReaderSupplier(Resources - .getResource("client_rb_append." + ShellToken.SH.to(OsFamily.UNIX)), Charsets.UTF_8))); + assertEquals(statement.render(OsFamily.UNIX), Resources.toString(Resources + .getResource("client_rb_append." + ShellToken.SH.to(OsFamily.UNIX)), Charsets.UTF_8)); } public void testWINDOWS() throws IOException { - assertEquals(statement.render(OsFamily.WINDOWS), CharStreams.toString(Resources.newReaderSupplier(Resources - .getResource("client_rb_append." + ShellToken.SH.to(OsFamily.WINDOWS)), Charsets.UTF_8))); + assertEquals(statement.render(OsFamily.WINDOWS), Resources.toString(Resources + .getResource("client_rb_append." + ShellToken.SH.to(OsFamily.WINDOWS)), Charsets.UTF_8)); } } diff --git a/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/CreateOrOverwriteFileTest.java b/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/CreateOrOverwriteFileTest.java index eb8929654c..c20cb5592e 100644 --- a/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/CreateOrOverwriteFileTest.java +++ b/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/CreateOrOverwriteFileTest.java @@ -27,7 +27,6 @@ import org.testng.annotations.Test; import com.google.common.base.Charsets; import com.google.common.collect.ImmutableList; -import com.google.common.io.CharStreams; import com.google.common.io.Resources; /** @@ -39,13 +38,13 @@ public class CreateOrOverwriteFileTest { "log_location STDOUT", String.format("chef_server_url \"%s\"", "http://localhost:4000"))); public void testUNIX() throws IOException { - assertEquals(statement.render(OsFamily.UNIX), CharStreams.toString(Resources.newReaderSupplier(Resources - .getResource("client_rb_overwrite." + ShellToken.SH.to(OsFamily.UNIX)), Charsets.UTF_8))); + assertEquals(statement.render(OsFamily.UNIX), Resources.toString(Resources + .getResource("client_rb_overwrite." + ShellToken.SH.to(OsFamily.UNIX)), Charsets.UTF_8)); } public void testWINDOWS() throws IOException { - assertEquals(statement.render(OsFamily.WINDOWS), CharStreams.toString(Resources.newReaderSupplier(Resources - .getResource("client_rb_overwrite." + ShellToken.SH.to(OsFamily.WINDOWS)), Charsets.UTF_8))); + assertEquals(statement.render(OsFamily.WINDOWS), Resources.toString(Resources + .getResource("client_rb_overwrite." + ShellToken.SH.to(OsFamily.WINDOWS)), Charsets.UTF_8)); } } diff --git a/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/CreateRunScriptTest.java b/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/CreateRunScriptTest.java index c265bc107c..4278236bd8 100644 --- a/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/CreateRunScriptTest.java +++ b/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/CreateRunScriptTest.java @@ -29,7 +29,6 @@ import org.testng.annotations.Test; import com.google.common.base.Charsets; import com.google.common.collect.ImmutableList; -import com.google.common.io.CharStreams; import com.google.common.io.Resources; /** @@ -49,8 +48,8 @@ public class CreateRunScriptTest { exec("echo {varl}JAVA_HOME{varr}{fs}bin{fs}java -DinstanceName={varl}INSTANCE_NAME{varr} myServer.Main"))); public void testUNIX() throws IOException { - assertEquals(statement.render(OsFamily.UNIX), CharStreams.toString(Resources.newReaderSupplier(Resources - .getResource("test_runrun." + ShellToken.SH.to(OsFamily.UNIX)), Charsets.UTF_8))); + assertEquals(statement.render(OsFamily.UNIX), Resources.toString(Resources + .getResource("test_runrun." + ShellToken.SH.to(OsFamily.UNIX)), Charsets.UTF_8)); } @Test(expectedExceptions = UnsupportedOperationException.class) diff --git a/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/SwitchArgTest.java b/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/SwitchArgTest.java index fdde97d12c..7f5b6bb7c5 100644 --- a/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/SwitchArgTest.java +++ b/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/domain/SwitchArgTest.java @@ -27,6 +27,7 @@ import java.util.Collections; import org.testng.annotations.Test; +import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; /** @@ -37,7 +38,7 @@ public class SwitchArgTest { public void testSwitchArgUNIX() { assertEquals(new SwitchArg(1, ImmutableMap.of("0", newStatementList(appendFile( - "{tmp}{fs}{uid}{fs}scripttest{fs}temp.txt", Collections.singleton("hello world")), + "{tmp}{fs}{uid}{fs}scripttest{fs}temp.txt", ImmutableList.of("hello world")), interpret("echo hello zero{lf}")), "1", interpret("echo hello one{lf}"))).render(OsFamily.UNIX), "case $1 in\n"+ "0)\n"+ diff --git a/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/statements/git/InstallGitTest.java b/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/statements/git/InstallGitTest.java index 12ee9e203b..908f8068bc 100644 --- a/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/statements/git/InstallGitTest.java +++ b/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/statements/git/InstallGitTest.java @@ -29,7 +29,6 @@ import org.jclouds.scriptbuilder.statements.git.InstallGit; import org.testng.annotations.Test; import com.google.common.base.Charsets; -import com.google.common.io.CharStreams; import com.google.common.io.Resources; /** @@ -44,9 +43,7 @@ public class InstallGitTest { public void testInstallGitUNIXInScriptBuilderSourcesSetupPublicCurl() throws IOException { assertEquals(InitScript.builder().name("install_git").run(new InstallGit()).build().render(OsFamily.UNIX), - CharStreams.toString(Resources.newReaderSupplier( - Resources.getResource("test_install_git_scriptbuilder." + ShellToken.SH.to(OsFamily.UNIX)), - Charsets.UTF_8))); + Resources.toString(Resources.getResource("test_install_git_scriptbuilder." + ShellToken.SH.to(OsFamily.UNIX)), Charsets.UTF_8)); } } diff --git a/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/statements/java/InstallJDKTest.java b/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/statements/java/InstallJDKTest.java index 8bb7033d4b..fb8cfa5521 100644 --- a/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/statements/java/InstallJDKTest.java +++ b/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/statements/java/InstallJDKTest.java @@ -30,7 +30,6 @@ import org.jclouds.scriptbuilder.domain.Statement; import org.testng.annotations.Test; import com.google.common.base.Charsets; -import com.google.common.io.CharStreams; import com.google.common.io.Resources; /** @@ -47,9 +46,7 @@ public class InstallJDKTest { public void testInstallJDKUNIXInScriptBuilderSourcesSetupPublicCurl() throws IOException { assertEquals(InitScript.builder().name("install_jdk").run(InstallJDK.fromOpenJDK()).build().render(OsFamily.UNIX), - CharStreams.toString(Resources.newReaderSupplier( - Resources.getResource("test_install_jdk_scriptbuilder." + ShellToken.SH.to(OsFamily.UNIX)), - Charsets.UTF_8))); + Resources.toString(Resources.getResource("test_install_jdk_scriptbuilder." + ShellToken.SH.to(OsFamily.UNIX)), Charsets.UTF_8)); } public void testInstallJDKUNIXWithURL() throws IOException { diff --git a/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/statements/login/AdminAccessTest.java b/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/statements/login/AdminAccessTest.java index 64d0fbe714..4c35d21d9c 100644 --- a/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/statements/login/AdminAccessTest.java +++ b/scriptbuilder/src/test/java/org/jclouds/scriptbuilder/statements/login/AdminAccessTest.java @@ -27,7 +27,6 @@ import org.jclouds.scriptbuilder.domain.OsFamily; import org.testng.annotations.Test; import com.google.common.base.Charsets; -import com.google.common.io.CharStreams; import com.google.common.io.Resources; /** @@ -40,8 +39,7 @@ public class AdminAccessTest { TestConfiguration.INSTANCE.reset(); try { assertEquals(AdminAccess.standard().init(TestConfiguration.INSTANCE).render(OsFamily.UNIX), - CharStreams.toString(Resources.newReaderSupplier(Resources.getResource("test_adminaccess_standard.sh"), - Charsets.UTF_8))); + Resources.toString(Resources.getResource("test_adminaccess_standard.sh"), Charsets.UTF_8)); } finally { TestConfiguration.INSTANCE.reset(); } @@ -55,8 +53,7 @@ public class AdminAccessTest { .adminPublicKey("fooPublicKey").adminUsername("foo") .adminHome("/over/ridden/foo").build() .init(TestConfiguration.INSTANCE).render(OsFamily.UNIX), - CharStreams.toString(Resources.newReaderSupplier( - Resources.getResource("test_adminaccess_params.sh"), Charsets.UTF_8))); + Resources.toString(Resources.getResource("test_adminaccess_params.sh"), Charsets.UTF_8)); } finally { TestConfiguration.INSTANCE.reset(); @@ -71,8 +68,7 @@ public class AdminAccessTest { .adminPublicKey("fooPublicKey").adminUsername("foo").adminFullName("JClouds Foo") .adminHome("/over/ridden/foo").build() .init(TestConfiguration.INSTANCE).render(OsFamily.UNIX), - CharStreams.toString(Resources.newReaderSupplier( - Resources.getResource("test_adminaccess_params_and_fullname.sh"), Charsets.UTF_8))); + Resources.toString(Resources.getResource("test_adminaccess_params_and_fullname.sh"), Charsets.UTF_8)); } finally { TestConfiguration.INSTANCE.reset(); @@ -86,8 +82,8 @@ public class AdminAccessTest { assertEquals( AdminAccess.builder().grantSudoToAdminUser(false).authorizeAdminPublicKey(true) .installAdminPrivateKey(true).lockSsh(false).resetLoginPassword(false).build() - .init(TestConfiguration.INSTANCE).render(OsFamily.UNIX), CharStreams.toString(Resources - .newReaderSupplier(Resources.getResource("test_adminaccess_plainuser.sh"), Charsets.UTF_8))); + .init(TestConfiguration.INSTANCE).render(OsFamily.UNIX), + Resources.toString(Resources.getResource("test_adminaccess_plainuser.sh"), Charsets.UTF_8)); } finally { TestConfiguration.INSTANCE.reset(); } diff --git a/skeletons/pom.xml b/skeletons/pom.xml index 857e1904a9..01768daaba 100644 --- a/skeletons/pom.xml +++ b/skeletons/pom.xml @@ -23,7 +23,7 @@ jclouds-project org.jclouds - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../project/pom.xml 4.0.0 diff --git a/skeletons/standalone-compute/pom.xml b/skeletons/standalone-compute/pom.xml index 5760dd91a0..0a8dff7343 100644 --- a/skeletons/standalone-compute/pom.xml +++ b/skeletons/standalone-compute/pom.xml @@ -24,7 +24,7 @@ org.jclouds jclouds-project - 1.5.0-SNAPSHOT + 1.6.0-SNAPSHOT ../../project/pom.xml org.jclouds.api